Java Code Examples for javax.xml.transform.TransformerException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project jdocbook-core, under directory /src/main/java/org/jboss/jdocbook/xslt/.

Source file: ClasspathResolver.java

  31 
vote

public Source resolve(String href,String base) throws TransformerException {
  if (!href.startsWith(SCHEME)) {
    return null;
  }
  try {
    URL url=componentRegistry.getEnvironment().getResourceDelegate().locateResource(href);
    if (url != null) {
      return new StreamSource(url.openStream(),url.toExternalForm());
    }
  }
 catch (  Throwable ignore) {
  }
  throw new TransformerException("Unable to resolve requested classpath URL [" + href + "]");
}
 

Example 2

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/xpath/.

Source file: XPathFunctionsProvider.java

  31 
vote

/** 
 * Executes the extension function.
 * @param ns the namespace of the function.
 * @param funcName the function name.
 * @param argVec the function arguments.
 * @param methodKey the method key.
 * @return the execution result.
 * @throws TransformerException if the function executed with errors or the function is not available.
 * @see org.apache.xpath.ExtensionsProvider#extFunction(java.lang.String,java.lang.String,java.util.Vector,java.lang.Object)
 */
public Object extFunction(String ns,String funcName,Vector argVec,Object methodKey) throws TransformerException {
  XPathFunction func=getFunction(ns,funcName);
  if (func != null) {
    try {
      return func.execute(argVec);
    }
 catch (    Exception e) {
      throw new TransformerException("Function '" + funcName + "' of namespace '"+ ns+ "' executed with error",e);
    }
  }
 else {
    throw new TransformerException("Function '" + funcName + "' of namespace '"+ ns+ "' is not available");
  }
}
 

Example 3

From project core_5, under directory /exo.core.component.xml-processing/src/main/java/org/exoplatform/services/xml/transform/impl/html/.

Source file: TidyTransformerImpl.java

  30 
vote

@Override protected void internalTransform(Source source) throws NotSupportedIOTypeException, TransformerException, IllegalStateException {
  InputStream input=sourceAsInputStream(source);
  try {
    LOG.debug(" input available bytes " + input.available());
    if (input.available() == 0)     return;
  }
 catch (  IOException ex) {
    LOG.error("Error on read Source",ex);
    new TransformerException("Error on read source",ex);
  }
  tidy.setConfigurationFromProps(props);
  if (getResult() instanceof StreamResult) {
    OutputStream output=((StreamResult)getResult()).getOutputStream();
    LOG.debug("Prepare to write transform result direct to OutputStream");
    tidy.parse(input,output);
    LOG.debug("Tidy parse is complete");
  }
 else {
    ByteArrayOutputStream output=new ByteArrayOutputStream();
    LOG.debug("Prepare to write transform result to temp output");
    tidy.parse(input,output);
    LOG.debug("Tidy parse is complete");
    String outputString=output.toString();
    try {
      outputString=outputString.replaceFirst("<\\?xml version=\"1.0\"\\?>","<?xml version=\"1.0\" encoding=\"" + getCurrentIANAEncoding() + "\"?>");
      output.flush();
    }
 catch (    IOException ex) {
      throw new TransformerException(ex);
    }
    processNotNativeResult(new ByteArrayInputStream(outputString.getBytes()));
  }
}
 

Example 4

From project jboss-jstl-api_spec, under directory /src/main/java/org/apache/taglibs/standard/tag/common/xml/.

Source file: TransformSupport.java

  30 
vote

public Source resolve(String href,String base) throws TransformerException {
  if (href == null)   return null;
  int index;
  if (base != null && (index=base.indexOf("jstl:")) != -1) {
    base=base.substring(index + 5);
  }
  if (ImportSupport.isAbsoluteUrl(href) || (base != null && ImportSupport.isAbsoluteUrl(base)))   return null;
  if (base == null || base.lastIndexOf("/") == -1)   base="";
 else   base=base.substring(0,base.lastIndexOf("/") + 1);
  String target=base + href;
  InputStream s;
  if (target.startsWith("/")) {
    s=ctx.getServletContext().getResourceAsStream(target);
    if (s == null)     throw new TransformerException(Resources.getMessage("UNABLE_TO_RESOLVE_ENTITY",href));
  }
 else {
    String pagePath=((HttpServletRequest)ctx.getRequest()).getServletPath();
    String basePath=pagePath.substring(0,pagePath.lastIndexOf("/"));
    s=ctx.getServletContext().getResourceAsStream(basePath + "/" + target);
    if (s == null)     throw new TransformerException(Resources.getMessage("UNABLE_TO_RESOLVE_ENTITY",href));
  }
  return new StreamSource(s);
}
 

Example 5

From project jsword, under directory /src/main/java/org/crosswire/common/xml/.

Source file: TransformingSAXEventProvider.java

  30 
vote

@Override public void transform(Source xmlSource,Result outputTarget) throws TransformerException {
  TemplateInfo tinfo;
  try {
    tinfo=getTemplateInfo();
  }
 catch (  IOException e) {
    throw new TransformerException(e);
  }
  Transformer transformer=tinfo.getTemplates().newTransformer();
  for (  Object obj : outputs.keySet()) {
    String key=(String)obj;
    String val=getOutputProperty(key);
    transformer.setOutputProperty(key,val);
  }
  for (  String key : params.keySet()) {
    Object val=params.get(key);
    transformer.setParameter(key,val);
  }
  if (errors != null) {
    transformer.setErrorListener(errors);
  }
  if (resolver != null) {
    transformer.setURIResolver(resolver);
  }
  transformer.transform(xmlSource,outputTarget);
}
 

Example 6

From project addis, under directory /application/src/main/java/org/drugis/addis/entities/.

Source file: DomainManager.java

  29 
vote

/** 
 * Replace the Domain by a new instance loaded from a XML stream (old format, .xml).
 * @param is Stream to read objects from.
 * @throws IOException
 * @throws ClassNotFoundException
 */
public void loadLegacyXMLDomain(InputStream is) throws IOException {
  try {
    InputStream transformedXmlStream=JAXBConvertor.transformLegacyXML(is);
    is.close();
    loadXMLDomain(transformedXmlStream,1);
  }
 catch (  TransformerException e) {
    throw new RuntimeException(e);
  }
}
 

Example 7

From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/mailer/.

Source file: Mailer.java

  29 
vote

/** 
 * Transform xml.
 * @param outputDirectory the output directory
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws TransformerException the transformer exception
 */
private void transformXml(String outputDirectory) throws IOException, TransformerException {
  File logsData=new File(outputDirectory,logsDataDir);
  File xsl=new File(logsData,"email.xsl");
  File xml=new File(outputDirectory,resultsName);
  htmlFile=new File(outputDirectory,"email.html");
  HTMLLogTransformer transformer=new HTMLLogTransformer(xsl,null);
  transformer.transform(xml,htmlFile);
  logger.info("Suite email: " + htmlFile.toURI().toURL());
}
 

Example 8

From project any23, under directory /core/src/main/java/org/apache/any23/extractor/html/.

Source file: DomUtils.java

  29 
vote

/** 
 * Given a <i>DOM</i>  {@link Node} produces the <i>XML</i> serializationomitting the <i>XML declaration</i>.
 * @param node node to be serialized.
 * @param indent if <code>true</code> the output is indented.
 * @return the XML serialization.
 * @throws TransformerException if an error occurs during theserializator initialization and activation.
 * @throws java.io.IOException
 */
public static String serializeToXML(Node node,boolean indent) throws TransformerException, IOException {
  final DOMSource domSource=new DOMSource(node);
  final Transformer transformer=TransformerFactory.newInstance().newTransformer();
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
  transformer.setOutputProperty(OutputKeys.METHOD,"xml");
  transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  if (indent) {
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
  }
  final StringWriter sw=new StringWriter();
  final StreamResult sr=new StreamResult(sw);
  transformer.transform(domSource,sr);
  sw.close();
  return sw.toString();
}
 

Example 9

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: XsltTask.java

  29 
vote

private void transform(File infile,File outfile) throws IOException {
  InputStream fis=null;
  OutputStream fos=null;
  try {
    final Transformer transformer=createTransformer();
    fis=new BufferedInputStream(new FileInputStream(infile));
    fos=new BufferedOutputStream(createOutputStream(outfile));
    StreamResult res=new StreamResult(fos);
    Source src=new StreamSource(fis);
    setTransformationParameters(transformer);
    if (env.isVerbose()) {
      logVerbose("Processing :'%s'\n",infile);
      logVerbose("        to :'%s'\n",outfile);
      logVerbose("using xslt :'%s'\n",styleFile);
    }
 else {
      env.logInfo("Processing 1 file.\n");
    }
    transformer.transform(src,res);
    fis.close();
    fos.flush();
    fos.close();
  }
 catch (  TransformerException e) {
    throw new BuildException(e);
  }
 finally {
    StreamUtils.close(fis);
    StreamUtils.close(fos);
  }
}
 

Example 10

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/coreutils/.

Source file: XMLUtil.java

  29 
vote

/** 
 * Saves XML files to disk
 * @param clazz the class this method is invoked from
 * @param xmlPath the full path to save the XML to
 * @param encoding to encoding, such as "UTF-8", to encode the file with
 * @param doc the document to save
 */
public static boolean saveDoc(Class clazz,String xmlPath,String encoding,final Document doc){
  TransformerFactory xf=TransformerFactory.newInstance();
  xf.setAttribute("indent-number",new Integer(1));
  boolean success=false;
  try {
    Transformer xformer=xf.newTransformer();
    xformer.setOutputProperty(OutputKeys.METHOD,"xml");
    xformer.setOutputProperty(OutputKeys.INDENT,"yes");
    xformer.setOutputProperty(OutputKeys.ENCODING,encoding);
    xformer.setOutputProperty(OutputKeys.STANDALONE,"yes");
    xformer.setOutputProperty(OutputKeys.VERSION,"1.0");
    File file=new File(xmlPath);
    FileOutputStream stream=new FileOutputStream(file);
    Result out=new StreamResult(new OutputStreamWriter(stream,encoding));
    xformer.transform(new DOMSource(doc),out);
    stream.flush();
    stream.close();
    success=true;
  }
 catch (  UnsupportedEncodingException e) {
    Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Should not happen",e);
  }
catch (  TransformerConfigurationException e) {
    Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error writing XML file",e);
  }
catch (  TransformerException e) {
    Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error writing XML file",e);
  }
catch (  FileNotFoundException e) {
    Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error writing XML file: cannot write to file: " + xmlPath,e);
  }
catch (  IOException e) {
    Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error writing XML file: cannot write to file: " + xmlPath,e);
  }
  return success;
}
 

Example 11

From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/main/java/com/microsoft/samples/federation/.

Source file: SamlTokenValidator.java

  29 
vote

private static SignableSAMLObject getSamlTokenFromRstr(String rstr) throws ParserConfigurationException, SAXException, IOException, UnmarshallingException, FederationException {
  Document document=getDocument(rstr);
  String xpath="//*[local-name() = 'Assertion']";
  NodeList nodes=null;
  try {
    nodes=org.apache.xpath.XPathAPI.selectNodeList(document,xpath);
  }
 catch (  TransformerException e) {
    e.printStackTrace();
  }
  if (nodes.getLength() == 0) {
    throw new FederationException("SAML token was not found");
  }
  Element samlTokenElement=(Element)nodes.item(0);
  Unmarshaller unmarshaller=Configuration.getUnmarshallerFactory().getUnmarshaller(samlTokenElement);
  SignableSAMLObject samlToken=(SignableSAMLObject)unmarshaller.unmarshall(samlTokenElement);
  return samlToken;
}
 

Example 12

From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.

Source file: PubchemStructureGenerator.java

  29 
vote

public static List<IMolecule> doDownload(String formula,IProgressMonitor monitor) throws TransformerConfigurationException, ParserConfigurationException, IOException, SAXException, FactoryConfigurationError, TransformerFactoryConfigurationError, TransformerException, NodeNotAvailableException {
  PubchemStructureGenerator request=new PubchemStructureGenerator();
  request.submitInitalRequest(formula);
  worked=0;
  while (!request.getStatus().isFinished()) {
    if (monitor.isCanceled())     return null;
    request.refresh();
    worked++;
    monitor.worked(worked);
  }
  request.submitDownloadRequest();
  while (!request.getStatusDownload().isFinished()) {
    if (monitor.isCanceled())     return null;
    request.refresh();
    worked++;
    monitor.worked(worked);
  }
  URLConnection uc=request.getResponseURL().openConnection();
  String contentType=uc.getContentType();
  int contentLength=uc.getContentLength();
  if (contentType.startsWith("text/") || contentLength == -1) {
    throw new IOException("This is not a binary file.");
  }
  InputStream raw=uc.getInputStream();
  InputStream in=new BufferedInputStream(raw);
  List<IMolecule> list=new ArrayList<IMolecule>();
  IteratingMDLReader reader=new IteratingMDLReader(in,DefaultChemObjectBuilder.getInstance());
  while (reader.hasNext()) {
    list.add((IMolecule)reader.next());
  }
  return list;
}
 

Example 13

From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.

Source file: BlacktieStompAdministrationService.java

  29 
vote

String printNode(Node node){
  try {
    TransformerFactory transfac=TransformerFactory.newInstance();
    Transformer trans=transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
    trans.setOutputProperty(OutputKeys.INDENT,"yes");
    StringWriter sw=new StringWriter();
    StreamResult result=new StreamResult(sw);
    DOMSource source=new DOMSource(node);
    trans.transform(source,result);
    String xmlString=sw.toString();
    return xmlString;
  }
 catch (  TransformerException e) {
    log.error(e);
  }
  return null;
}
 

Example 14

From project BMach, under directory /src/jsyntaxpane/actions/.

Source file: XmlPrettifyAction.java

  29 
vote

@Override public void actionPerformed(ActionEvent e){
  if (transformer == null) {
    return;
  }
  JTextComponent target=getTextComponent(e);
  try {
    SyntaxDocument sdoc=ActionUtils.getSyntaxDocument(target);
    StringWriter out=new StringWriter(sdoc.getLength());
    StringReader reader=new StringReader(target.getText());
    InputSource src=new InputSource(reader);
    Document doc=getDocBuilder().parse(src);
    getTransformer().transform(new DOMSource(doc),new StreamResult(out));
    target.setText(out.toString());
  }
 catch (  SAXParseException ex) {
    showErrorMessage(target,String.format("XML error: %s\nat(%d, %d)",ex.getMessage(),ex.getLineNumber(),ex.getColumnNumber()));
    ActionUtils.setCaretPosition(target,ex.getLineNumber(),ex.getColumnNumber() - 1);
  }
catch (  TransformerException ex) {
    showErrorMessage(target,ex.getMessageAndLocation());
  }
catch (  SAXException ex) {
    showErrorMessage(target,ex.getLocalizedMessage());
  }
catch (  IOException ex) {
    showErrorMessage(target,ex.getLocalizedMessage());
  }
}
 

Example 15

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/util/.

Source file: BPELUnitUtil.java

  29 
vote

/** 
 * Outputs a DOM Document node to a string with identation.
 * @param element
 * @return
 */
public static String toFormattedString(Document element){
  try {
    return serializeXML(element);
  }
 catch (  TransformerException e) {
    return "(no data)";
  }
}
 

Example 16

From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/adapter/.

Source file: ExchangeCalendarAdapter.java

  29 
vote

/** 
 * Retrieve a set of CalendarEvents from the Exchange server for the specified period and email address.
 * @param calendar
 * @param period
 * @param emailAddress
 * @return
 * @throws CalendarException
 */
public Set<VEvent> retrieveExchangeEvents(CalendarConfiguration calendar,Interval interval,String emailAddress) throws CalendarException {
  if (log.isDebugEnabled()) {
    log.debug("Retrieving exchange events for period: " + interval);
  }
  Set<VEvent> events=new HashSet<VEvent>();
  try {
    GetUserAvailabilityRequest soapRequest=getAvailabilityRequest(interval,emailAddress);
    final WebServiceMessageCallback actionCallback=new SoapActionCallback(AVAILABILITY_SOAP_ACTION);
    final WebServiceMessageCallback customCallback=new WebServiceMessageCallback(){
      @Override public void doWithMessage(      WebServiceMessage message) throws IOException, TransformerException {
        actionCallback.doWithMessage(message);
        SoapMessage soap=(SoapMessage)message;
        QName rsv=new QName("http://schemas.microsoft.com/exchange/services/2006/types","RequestServerVersion","ns3");
        SoapHeaderElement version=soap.getEnvelope().getHeader().addHeaderElement(rsv);
        version.addAttribute(new QName("Version"),"Exchange2010_SP2");
      }
    }
;
    GetUserAvailabilityResponse response=(GetUserAvailabilityResponse)webServiceOperations.marshalSendAndReceive(soapRequest,customCallback);
    for (    FreeBusyResponseType freeBusy : response.getFreeBusyResponseArray().getFreeBusyResponses()) {
      ArrayOfCalendarEvent eventArray=freeBusy.getFreeBusyView().getCalendarEventArray();
      if (eventArray != null && eventArray.getCalendarEvents() != null) {
        List<com.microsoft.exchange.types.CalendarEvent> msEvents=eventArray.getCalendarEvents();
        for (        com.microsoft.exchange.types.CalendarEvent msEvent : msEvents) {
          VEvent event=getInternalEvent(calendar.getId(),msEvent);
          events.add(event);
        }
      }
    }
  }
 catch (  DatatypeConfigurationException e) {
    throw new CalendarException(e);
  }
  return events;
}
 

Example 17

From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/dao/.

Source file: ScreenScrapingService.java

  29 
vote

public T getItem(String key,String url){
  try {
    log.debug(url);
    final String htmlContent=getHtmlContent(url);
    final String cleanedContent=getCleanedHtmlContent(htmlContent);
    final String xml=getXml(cleanedContent);
    log.debug(xml);
    final T item=deserializeItem(xml);
    for (    IScreenScrapingPostProcessor<T> processor : postProcessors) {
      processor.postProcess(key,item);
    }
    return item;
  }
 catch (  ClientProtocolException e) {
    log.error("Failed to retrieve dining hall menu",e);
  }
catch (  TransformerConfigurationException e) {
    throw new RuntimeException("Failed to create identity transformer to serialize Node to String",e);
  }
catch (  TransformerException e) {
    throw new RuntimeException("Failed to convert Node to String using Transformer",e);
  }
catch (  IOException e) {
    log.error("Failed to retrieve dining hall menu",e);
  }
catch (  ScanException e) {
    log.error("Failed to parse dining hall menu",e);
  }
catch (  PolicyException e) {
    log.error("Failed to parse dining hall menu",e);
  }
catch (  JAXBException e) {
    log.error("Failed to parse dining hall menu",e);
  }
  return null;
}
 

Example 18

From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/schematron/.

Source file: SchematronValidator.java

  29 
vote

/** 
 * This is the lowest level validation call, which returns an XML validation report in schematron output format. (see http://purl.oclc.org/dsdl/svrl)
 * @param source XML Source to validate
 * @param schema name of the schema to use
 * @return schematron output document
 */
public Document validate(Source source,String schema){
  Templates template=templates.get(schema);
  if (template == null) {
    throw new Error("Unknown Schematron schema name: " + schema);
  }
  Transformer t=null;
  try {
    t=template.newTransformer();
  }
 catch (  TransformerConfigurationException e) {
    throw new Error("There was a problem configuring the transformer.",e);
  }
  JDOMResult svrlRes=new JDOMResult();
  try {
    t.transform(source,svrlRes);
  }
 catch (  TransformerException e) {
    throw new Error("There was a problem running Schematron validation XSL.",e);
  }
  return svrlRes.getDocument();
}
 

Example 19

From project cascading, under directory /src/xml/cascading/operation/xml/.

Source file: XPathOperation.java

  29 
vote

protected String writeAsXML(Node node){
  StringWriter stringWriter=new StringWriter();
  Result result=new StreamResult(stringWriter);
  Source source=new DOMSource(node);
  try {
    getTransformer().transform(source,result);
  }
 catch (  TransformerException exception) {
    throw new OperationException("writing to xml failed",exception);
  }
  return stringWriter.toString();
}
 

Example 20

From project cider, under directory /src/net/yacy/cider/parser/idiom/rdfa/.

Source file: RDFaParser.java

  29 
vote

public void parse(Reader in,String base) throws IOException, TransformerException, TransformerConfigurationException {
  RDFaParserImp anImp=new RDFaParserImp(){
    public void reportDataProperty(    String subjectURI,    String subjectNodeID,    String propertyURI,    String value,    String datatype,    String lang){
      handleDataProperty(subjectURI,subjectNodeID,propertyURI,value,datatype,lang);
    }
    public void reportObjectProperty(    String subjectURI,    String subjectNodeID,    String propertyURI,    String objectURI,    String objectNodeID){
      handleObjectProperty(subjectURI,subjectNodeID,propertyURI,objectURI,objectNodeID);
    }
  }
;
  anImp.parse(in,base);
}
 

Example 21

From project cilia-workbench, under directory /cilia-workbench-common/src/fr/liglab/adele/cilia/workbench/common/xml/.

Source file: XMLHelpers.java

  29 
vote

/** 
 * Writes a document using its DOM representation.
 * @param document the document
 * @param file the file, on the local file system.
 * @throws CiliaException the metadata exception
 */
public static void writeDOM(Document document,File file) throws CiliaException {
  Source source=new DOMSource(document);
  TransformerFactory transformerFactory=TransformerFactory.newInstance();
  try {
    Transformer xformer=transformerFactory.newTransformer();
    xformer.setOutputProperty(OutputKeys.INDENT,"yes");
    StreamResult result=new StreamResult(file);
    xformer.transform(source,result);
  }
 catch (  TransformerException e) {
    throw new CiliaException("XML transformer error",e);
  }
}
 

Example 22

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/framework/data/.

Source file: XmlTools.java

  29 
vote

/** 
 * Convert a Node in XML String.
 * @param node to be converted.
 * @return the XML string. 
 */
public static String nodeToString(Node node) throws CiliaException {
  Source source=new DOMSource(node);
  StringWriter stringWriter=new StringWriter();
  Result result=new StreamResult(stringWriter);
  try {
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.transform(source,result);
    String strResult=stringWriter.getBuffer().toString();
    strResult=strResult.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>","");
    return strResult;
  }
 catch (  TransformerException e) {
    e.printStackTrace();
    throw new CiliaException(e.getMessage());
  }
}
 

Example 23

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.

Source file: MicrosoftAzureModelUtils.java

  29 
vote

private static String getStringFromDocument(final Document doc) throws MicrosoftAzureException {
  try {
    DOMSource domSource=new DOMSource(doc);
    StringWriter writer=new StringWriter();
    StreamResult result=new StreamResult(writer);
    TransformerFactory tf=TransformerFactory.newInstance();
    Transformer transformer=tf.newTransformer();
    transformer.transform(domSource,result);
    return writer.toString();
  }
 catch (  TransformerException ex) {
    throw new MicrosoftAzureException(ex);
  }
}
 

Example 24

From project code_swarm, under directory /src/org/codeswarm/repository/svn/.

Source file: SVNHistory.java

  29 
vote

/** 
 * serializes the log entries
 */
public void finishLogEntries(){
  try {
    CodeSwarmEventsSerializer serializer=new CodeSwarmEventsSerializer(list);
    serializer.serialize(getFilePath());
  }
 catch (  ParserConfigurationException ex) {
    LOGGER.log(Level.SEVERE,null,ex);
  }
catch (  TransformerConfigurationException ex) {
    LOGGER.log(Level.SEVERE,null,ex);
  }
catch (  IOException ex) {
    LOGGER.log(Level.SEVERE,null,ex);
  }
catch (  TransformerException ex) {
    LOGGER.log(Level.SEVERE,null,ex);
  }
}
 

Example 25

From project code_swarm-gource-my-conf, under directory /src/org/codeswarm/repository/svn/.

Source file: SVNHistory.java

  29 
vote

/** 
 * serializes the log entries
 */
public void finishLogEntries(){
  try {
    CodeSwarmEventsSerializer serializer=new CodeSwarmEventsSerializer(list);
    serializer.serialize(getFilePath());
  }
 catch (  ParserConfigurationException ex) {
    LOGGER.log(Level.SEVERE,null,ex);
  }
catch (  TransformerConfigurationException ex) {
    LOGGER.log(Level.SEVERE,null,ex);
  }
catch (  IOException ex) {
    LOGGER.log(Level.SEVERE,null,ex);
  }
catch (  TransformerException ex) {
    LOGGER.log(Level.SEVERE,null,ex);
  }
}
 

Example 26

From project codjo-data-process, under directory /codjo-data-process-common/src/main/java/net/codjo/dataprocess/common/util/.

Source file: XMLUtils.java

  29 
vote

public static String nodeToString(Node node,boolean replaceCRLF,boolean removeSpaceChar) throws TransformerException {
  String result;
  StringWriter strWriter=new StringWriter();
  TransformerFactory tFactory=TransformerFactory.newInstance();
  Transformer transformer=tFactory.newTransformer();
  transformer.transform(new DOMSource(node),new StreamResult(strWriter));
  String str=getRidOfHeader(strWriter.toString());
  if (replaceCRLF) {
    result=flattenAndReplaceCRLF(str,removeSpaceChar);
  }
 else {
    result=flatten(str,removeSpaceChar);
  }
  return result;
}
 

Example 27

From project codjo-segmentation, under directory /codjo-segmentation-server/src/main/java/net/codjo/segmentation/server/plugin/.

Source file: PreferenceGuiHome.java

  29 
vote

public String buildResponse(InputSource confFile) throws ParserConfigurationException, TransformerException, IOException, XmlException {
  DocumentBuilder builder=initFactory();
  Document root=builder.getDOMImplementation().createDocument(null,"family-list",null);
  XmlParser xmlParser=new XmlParser();
  RootBuilder reader=new RootBuilder(root);
  xmlParser.parse(confFile,reader);
  return domToString(root);
}
 

Example 28

From project core_1, under directory /common/src/main/java/org/switchyard/common/xml/.

Source file: XMLHelper.java

  29 
vote

/** 
 * Compare two DOM Nodes.
 * @param node1 The first Node.
 * @param node2 The second Node.
 * @return true if equals, false otherwise.
 * @throws ParserConfigurationException Parser confiuration exception
 * @throws TransformerException Transformer exception
 * @throws SAXException SAX exception
 * @throws IOException If unable to read the stream
 */
public static boolean compareXMLContent(final Node node1,final Node node2) throws ParserConfigurationException, TransformerException, SAXException, IOException {
  TransformerFactory transFactory=TransformerFactory.newInstance();
  Transformer transformer=transFactory.newTransformer();
  StringWriter writer1=new StringWriter();
  StringWriter writer2=new StringWriter();
  DOMSource source=new DOMSource(node1);
  StreamResult result=new StreamResult(writer1);
  transformer.transform(source,result);
  source=new DOMSource(node2);
  result=new StreamResult(writer2);
  transformer.transform(source,result);
  return compareXMLContent(writer1.toString(),writer2.toString());
}
 

Example 29

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/information_client/.

Source file: MainForm.java

  29 
vote

private void envoieButtonActionPerformed(java.awt.event.ActionEvent evt){
  if (this.ferryText.getText().isEmpty() || this.voyageurText.getText().isEmpty()) {
    this.erreurLabel.setText("Veillez ? renseigner les champs Ferry et Nom voyageur");
  }
 else {
    try {
      this.erreurLabel.setText("");
      Document doc=this.genDocument();
      this.sendDocument(doc);
    }
 catch (    ClassNotFoundException ex) {
      Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,null,ex);
    }
catch (    TransformerConfigurationException ex) {
      Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,null,ex);
    }
catch (    IOException ex) {
      Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,null,ex);
    }
catch (    ParserConfigurationException ex) {
      Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,null,ex);
    }
catch (    TransformerException ex) {
      Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,null,ex);
    }
  }
}
 

Example 30

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/xml/.

Source file: XMLUtils.java

  29 
vote

private static String getNodeValue(NodeList nodeList) throws TransformerFactoryConfigurationError, TransformerException {
  final Transformer serializer=TransformerFactory.newInstance().newTransformer();
  serializer.setURIResolver(null);
  final StringBuilder buf=new StringBuilder();
  for (int i=0; i < nodeList.getLength(); i++) {
    final StringWriter sw=new StringWriter();
    serializer.transform(new DOMSource(nodeList.item(i)),new StreamResult(sw));
    String xml=sw.toString();
    final Matcher matcher=HEADER_PATTERN.matcher(xml);
    if (matcher.matches()) {
      xml=matcher.group(1);
    }
    buf.append(xml);
    buf.append("\n");
  }
  return buf.toString();
}
 

Example 31

From project descriptors, under directory /metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/.

Source file: MetadataParser.java

  29 
vote

/** 
 * Generates source code by applying the <code>ddJavaAll.xsl</code> XSLT extracted from the resource stream.
 * @throws TransformerException
 */
public void generateCode(final MetadataParserPath path,final boolean verbose) throws TransformerException {
  final Map<String,String> xsltParameters=new HashMap<String,String>();
  xsltParameters.put("gOutputFolder",path.getPathToImpl());
  xsltParameters.put("gOutputFolderApi",path.getPathToApi());
  xsltParameters.put("gOutputFolderTest",path.getPathToTest());
  xsltParameters.put("gOutputFolderService",path.getPathToServices());
  xsltParameters.put("gVerbose",Boolean.toString(verbose));
  final InputStream is=MetadataParser.class.getResourceAsStream("/META-INF/ddJavaAll.xsl");
  if (log.isLoggable(Level.FINE)) {
    log.fine("Stream resource: " + is);
  }
  XsltTransformer.simpleTransform(pathToMetadata,is,new File("./tempddJava.xml"),xsltParameters);
}
 

Example 32

From project DeuceSTM, under directory /src/test/org/deuce/benchmark/lee/.

Source file: XMLHelper.java

  29 
vote

static void generateXMLReportSummary(boolean timeout,boolean xmlreport,double elapsed) throws TransformerFactoryConfigurationError {
  try {
    LeeRouterGlobalLock.obtainStats(null,elapsed,xmlreport);
    LeeRouterGlobalLock.xmlReport(doc);
    Element root=doc.getDocumentElement();
    Element element=doc.createElement("ElapsedTime");
    element.setTextContent(Double.toString(elapsed));
    root.appendChild(element);
    element=doc.createElement("Timeout");
    element.setTextContent(Boolean.toString(timeout));
    root.appendChild(element);
    DOMSource domSource=new DOMSource(doc);
    TransformerFactory tf=TransformerFactory.newInstance();
    Transformer transformer=tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD,"xml");
    transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    StringWriter sw=new StringWriter();
    StreamResult sr=new StreamResult(sw);
    transformer.transform(domSource,sr);
    System.out.println(sw.toString());
  }
 catch (  TransformerConfigurationException e) {
    e.printStackTrace();
  }
catch (  TransformerException e) {
    e.printStackTrace();
  }
}
 

Example 33

From project dev-examples, under directory /template/src/main/java/org/richfaces/example/.

Source file: XMLBodySerializer.java

  29 
vote

public String serialize(NodeList childNodes,Document xmlDocument) throws ParsingException {
  try {
    StringWriter out;
    DocumentFragment fragment=xmlDocument.createDocumentFragment();
    for (int i=0; i < childNodes.getLength(); i++) {
      fragment.appendChild(childNodes.item(i).cloneNode(true));
    }
    TransformerFactory transformerFactory=TransformerFactory.newInstance();
    Transformer transformer=transformerFactory.newTransformer();
    transformer.setErrorListener(new ErrorListener(){
      public void error(      TransformerException exception) throws TransformerException {
      }
      public void fatalError(      TransformerException exception) throws TransformerException {
      }
      public void warning(      TransformerException exception) throws TransformerException {
      }
    }
);
    transformer.setOutputProperty("indent","yes");
    transformer.setOutputProperty("omit-xml-declaration","yes");
    out=new StringWriter();
    StreamResult result=new StreamResult(out);
    transformer.transform(new DOMSource(fragment),result);
    return out.toString();
  }
 catch (  Exception e) {
    throw new ParsingException(e);
  }
}
 

Example 34

From project DTE, under directory /src/cl/nic/dte/util/.

Source file: Utilities.java

  29 
vote

public static void generatePDF(InputStream xmlFile,InputStream xslFile,OutputStream pdfFile) throws FOPException, FileNotFoundException, TransformerException {
  FopFactory fopFactory=FopFactory.newInstance();
  FOUserAgent foUserAgent=fopFactory.newFOUserAgent();
  Fop fop=fopFactory.newFop(MimeConstants.MIME_PDF,foUserAgent,pdfFile);
  TransformerFactory factory=TransformerFactory.newInstance();
  Transformer transformer=factory.newTransformer(new StreamSource(xslFile));
  transformer.setParameter("versionParam","2.0");
  Source src=new StreamSource(xmlFile);
  Result res=new SAXResult(fop.getDefaultHandler());
  transformer.transform(src,res);
}
 

Example 35

From project EasySOA, under directory /easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/preview/.

Source file: WSDLTransformer.java

  29 
vote

public static void generateHtmlView(InputStream xmlStream,OutputStream out) throws Exception {
  TransformerFactory tFactory=TransformerFactory.newInstance();
  Transformer transformer=tFactory.newTransformer(new StreamSource(getXLST()));
  transformer.setErrorListener(new ErrorListener(){
    @Override public void warning(    TransformerException exception) throws TransformerException {
      log.warn("Problem during transformation",exception);
    }
    @Override public void fatalError(    TransformerException exception) throws TransformerException {
      log.error("Fatal error during transformation",exception);
    }
    @Override public void error(    TransformerException exception) throws TransformerException {
      log.error("Error during transformation",exception);
    }
  }
);
  transformer.setURIResolver(null);
  transformer.transform(new StreamSource(xmlStream),new StreamResult(out));
}
 

Example 36

From project echo2, under directory /src/exampleapp/chatclient/src/java/echo2example/chatclient/.

Source file: XmlHttpConnection.java

  29 
vote

/** 
 * POSTs an XML message to a web service.
 * @param url the URL of the service
 * @param requestDocument the DOM document to POST
 * @return the XML response
 */
public static Document send(String url,Document requestDocument) throws IOException {
  try {
    URL u=new URL(url);
    HttpURLConnection conn=(HttpURLConnection)u.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStream out=conn.getOutputStream();
    TransformerFactory tFactory=TransformerFactory.newInstance();
    Transformer transformer=tFactory.newTransformer();
    DOMSource source=new DOMSource(requestDocument);
    StreamResult result=new StreamResult(out);
    transformer.transform(source,result);
    out.close();
    conn.connect();
    InputStream in=conn.getInputStream();
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder=factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver(){
      /** 
 * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String,java.lang.String)
 */
      public InputSource resolveEntity(      String publicId,      String systemId) throws SAXException, IOException {
        throw new SAXException("External entities not supported.");
      }
    }
);
    return builder.parse(in);
  }
 catch (  ParserConfigurationException ex) {
    throw new IOException("Unable to parse response: " + ex.toString());
  }
catch (  SAXException ex) {
    throw new IOException("Unable to parse response: " + ex.toString());
  }
catch (  TransformerException ex) {
    throw new IOException("Unable to write document to OutputStream: " + ex.toString());
  }
}
 

Example 37

From project echo3, under directory /src/server-java/app/nextapp/echo/app/util/.

Source file: DomUtil.java

  29 
vote

/** 
 * Work method for public save() methods.
 */
private static void saveImpl(Document document,StreamResult output,Properties outputProperties) throws SAXException {
  try {
    TransformerFactory tFactory=getTransformerFactory();
    Transformer transformer=tFactory.newTransformer();
    if (outputProperties != null) {
      transformer.setOutputProperties(outputProperties);
    }
    DOMSource source=new DOMSource(document);
    transformer.transform(source,output);
  }
 catch (  TransformerException ex) {
    throw new SAXException("Unable to write document to OutputStream.",ex);
  }
}
 

Example 38

From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.content.core/src/org/springsource/ide/eclipse/commons/content/core/util/.

Source file: DescriptorReader.java

  29 
vote

public void write(File file) throws CoreException {
  DocumentBuilder documentBuilder=ContentUtil.createDocumentBuilder();
  Transformer serializer=ContentUtil.createTransformer();
  Document document=documentBuilder.newDocument();
  writeDocument(document);
  DOMSource source=new DOMSource(document);
  try {
    StreamResult target=new StreamResult(file);
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    serializer.transform(source,target);
  }
 catch (  TransformerException e) {
    throw new CoreException(new Status(Status.ERROR,ContentPlugin.PLUGIN_ID,"Could not write initialization data for tutorial"));
  }
}
 

Example 39

From project ElasticSearchExample, under directory /src/main/java/de/jetwick/ese/util/.

Source file: Helper.java

  29 
vote

public static String getDocumentAsString(Node node,boolean prettyXml) throws TransformerException, UnsupportedEncodingException {
  Transformer transformer=TransformerFactory.newInstance().newTransformer();
  if (prettyXml) {
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
  }
  transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  transformer.transform(new DOMSource(node),new StreamResult(baos));
  return baos.toString("UTF-8");
}
 

Example 40

From project emite, under directory /src/main/java/com/calclab/emite/base/xml/.

Source file: XMLPacketImpl.java

  29 
vote

@Override public String toString(){
  try {
    final StringWriter buffer=new StringWriter();
    transformer.transform(new DOMSource(element),new StreamResult(buffer));
    return buffer.toString();
  }
 catch (  final TransformerException e) {
    throw new InternalError("Transformer error");
  }
}
 

Example 41

From project Euclidean-Pattern-Generator, under directory /src/com/hisschemoller/sequencer/controller/file/.

Source file: SaveProjectCommand.java

  29 
vote

private void saveFile(Document document,String saveType){
  FileProxy fileProxy=(FileProxy)getFacade().retrieveProxy(FileProxy.NAME);
  if (saveType == SeqNotifications.SAVE_PROJECT_AS || (saveType == SeqNotifications.SAVE_PROJECT && fileProxy.getFile() == null)) {
    JFileChooser fileChooser=fileProxy.getFileChooser();
    fileChooser.setDialogTitle("Save Project File");
    fileChooser.setSelectedFile(new File("Euclidean-Patterns-Project.xml"));
    int returnVal=fileChooser.showSaveDialog(fileProxy.getDialogParent());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      fileProxy.setFile(fileChooser.getSelectedFile());
    }
 else {
      return;
    }
  }
  System.out.println("SaveProjectCommand.saveFile() file.getAbsolutePath: " + fileProxy.getFile().getAbsolutePath());
  Source source=new DOMSource(document);
  Result result=new StreamResult(fileProxy.getFile());
  try {
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    transformer.transform(source,result);
  }
 catch (  TransformerConfigurationException exception) {
    System.out.println("SaveProjectCommand.saveFile() TransformerConfigurationException: " + exception.getMessage());
  }
catch (  TransformerException exception) {
    System.out.println("SaveProjectCommand.saveFile() TransformerException: " + exception.getMessage());
  }
}
 

Example 42

From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/util/.

Source file: XmlSerializer.java

  29 
vote

protected static byte[] doc2bytes(Node node){
  try {
    Source source=new DOMSource(node);
    ByteArrayOutputStream out=new ByteArrayOutputStream();
    Result result=new StreamResult(out);
    TransformerFactory factory=TransformerFactory.newInstance();
    Transformer transformer=factory.newTransformer();
    transformer.transform(source,result);
    return out.toByteArray();
  }
 catch (  TransformerConfigurationException e) {
    e.printStackTrace();
  }
catch (  TransformerException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 43

From project fiftyfive-wicket, under directory /fiftyfive-wicket-test/src/main/java/fiftyfive/wicket/test/.

Source file: WicketTestUtils.java

  29 
vote

/** 
 * Asserts that exactly  {@code count} number of instances of a givenXPath expression can be found in the most recently rendered Wicket page. Uses <a href="http://htmlcleaner.sourceforge.net/">HtmlCleaner</a> under the hood to parse even the sloppiest HTML into XML that can be queryied by XPath. It is therefore possible that the XPath assertion will pass, even though  {@link #assertValidMarkup(WicketTester) assertValidMarkup()}fails.
 */
public static void assertXPath(int count,WicketTester wt,String expr) throws IOException, SAXException, ParserConfigurationException, TransformerException, XPathExpressionException {
  if (count > 0) {
    assertXPath(wt,expr);
  }
  final int matches=matchCount(wt,expr);
  if (matches != count) {
    String s=1 == count ? "" : "s";
    Assert.fail(String.format("Expected %d occurance%s of XPath expression [%s], but " + "found %d in document:%n%s",count,s,expr,matches,document(wt)));
  }
}
 

Example 44

From project flyingsaucer, under directory /flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/.

Source file: ViewSourceAction.java

  29 
vote

public void actionPerformed(ActionEvent evt){
  TransformerFactory tfactory=TransformerFactory.newInstance();
  Transformer serializer;
  try {
    serializer=tfactory.newTransformer();
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
    Element document=panel.getRootBox().getElement();
    DOMSource source=new DOMSource(document);
    StreamResult output=new StreamResult(System.out);
    serializer.transform(source,output);
  }
 catch (  TransformerException ex) {
    ex.printStackTrace();
    throw new RuntimeException(ex);
  }
}
 

Example 45

From project galaxy, under directory /src/co/paralleluniverse/common/util/.

Source file: DOMElementProprtyEditor.java

  29 
vote

@Override public String getAsText(){
  try {
    final Node node=(Node)getValue();
    Source source=new DOMSource(node);
    StringWriter stringWriter=new StringWriter();
    Result result=new StreamResult(stringWriter);
    TransformerFactory factory=TransformerFactory.newInstance();
    Transformer transformer=factory.newTransformer();
    transformer.transform(source,result);
    return stringWriter.getBuffer().toString();
  }
 catch (  TransformerConfigurationException e) {
    e.printStackTrace();
  }
catch (  TransformerException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 46

From project gatein-common, under directory /common/src/main/java/org/gatein/common/xml/.

Source file: XMLTools.java

  29 
vote

/** 
 * Converts an element to a String representation. 
 */
private static String toString(Element element,Properties properties) throws ParserConfigurationException, TransformerException {
  Document doc=getDocumentBuilderFactory().newDocumentBuilder().newDocument();
  element=(Element)doc.importNode(element,true);
  doc.appendChild(element);
  return toString(doc,properties);
}
 

Example 47

From project GeoBI, under directory /print/src/test/java/org/mapfish/print/.

Source file: CustomXPathTest.java

  29 
vote

public void testXslt() throws TransformerException, IOException {
  final StringReader xsltStream=new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n" + "                xmlns:xalan=\"http://xml.apache.org/xalan\"\n"+ "                xmlns:custom=\"Custom\"\n"+ "                version=\"1.0\">\n"+ "  <xalan:component prefix=\"custom\" functions=\"factorArray\">\n"+ "    <xalan:script lang=\"javaclass\" src=\"org.mapfish.print.CustomXPath\"/>\n"+ "  </xalan:component>\n"+ "  <xsl:template match=\"/*\">\n"+ "    <tutu b=\"{custom:factorArray(@a,3)}\"/>\n"+ "  </xsl:template>\n"+ "</xsl:stylesheet>");
  final StringReader xmlStream=new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<toto a=\"1,2,3\"/>");
  DOMResult transformedSvg=new DOMResult();
  final TransformerFactory factory=TransformerFactory.newInstance();
  javax.xml.transform.Transformer xslt=factory.newTransformer(new StreamSource(xsltStream));
  xslt.transform(new StreamSource(xmlStream),transformedSvg);
  Document doc=(Document)transformedSvg.getNode();
  Node main=doc.getFirstChild();
  assertEquals("tutu",main.getNodeName());
  final Node attrB=main.getAttributes().getNamedItem("b");
  assertNotNull(attrB);
  assertEquals("3,6,9",attrB.getNodeValue());
  xmlStream.close();
  xsltStream.close();
}
 

Example 48

From project GnucashMobile, under directory /GnucashMobile/src/org/gnucash/android/ui/accounts/.

Source file: ExportDialogFragment.java

  29 
vote

/** 
 * Writes out the file held in <code>document</code> to <code>outputWriter</code>
 * @param document {@link Document} containing the OFX document structure
 * @param outputWriter {@link Writer} to use in writing the file to stream
 */
public void write(Document document,Writer outputWriter){
  try {
    TransformerFactory transformerFactory=TransformerFactory.newInstance();
    Transformer transformer=transformerFactory.newTransformer();
    DOMSource source=new DOMSource(document);
    StreamResult result=new StreamResult(outputWriter);
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    transformer.transform(source,result);
  }
 catch (  TransformerConfigurationException txconfigException) {
    txconfigException.printStackTrace();
  }
catch (  TransformerException tfException) {
    tfException.printStackTrace();
  }
}
 

Example 49

From project grails-ide, under directory /org.grails.ide.eclipse.core/src/org/grails/ide/eclipse/core/model/.

Source file: GrailsInstallManager.java

  29 
vote

private void save(Document document){
  try {
    IPath grailsInstallFile=GrailsCoreActivator.getDefault().getStateLocation().append("grails.installs");
    TransformerFactory transformerFactory=TransformerFactory.newInstance();
    Transformer transformer=transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no");
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
    Writer out=new OutputStreamWriter(new FileOutputStream(grailsInstallFile.toFile()),"ISO-8859-1");
    StreamResult result=new StreamResult(out);
    DOMSource source=new DOMSource(document);
    transformer.transform(source,result);
    out.close();
  }
 catch (  IOException e) {
    GrailsCoreActivator.log(e);
  }
catch (  TransformerException e) {
    GrailsCoreActivator.log(e);
  }
}
 

Example 50

From project GraphWalker, under directory /src/main/java/org/graphwalker/.

Source file: StatisticsManager.java

  29 
vote

public void writeFullReport(PrintStream out){
  log.info("Writing full report");
  try {
    styleTemplate.transform(new JDOMSource((Document)this.progress.clone()),new StreamResult(out));
  }
 catch (  TransformerException e) {
    throw new RuntimeException("Could not create report",e);
  }
}
 

Example 51

From project Guit, under directory /src/main/java/com/guit/junit/dom/.

Source file: ElementMock.java

  29 
vote

public static String getOuterXml(Node n) throws ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException {
  Transformer xformer=TransformerFactory.newInstance().newTransformer();
  xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
  StreamResult result=new StreamResult(new StringWriter());
  DOMSource source=new DOMSource(n);
  xformer.transform(source,result);
  String xmlString=result.getWriter().toString();
  return xmlString;
}
 

Example 52

From project interoperability-framework, under directory /interfaces/web/generic-soap-client/src/main/java/eu/impact_project/wsclient/generic/.

Source file: WsdlDocument.java

  29 
vote

private void initXsom() throws IOException {
  try {
    SchemaImpl schema=(SchemaImpl)wsdlObject.getTypes().getExtensibilityElements().get(0);
    Element el=schema.getElement();
    InputStream is=prepareSchema(el);
    XSOMParser parser=new XSOMParser();
    parser.setAnnotationParser(new AnnotationFactory());
    parser.parse(is);
    String targetNamespace=wsdlObject.getTargetNamespace();
    if (parser.getResult() == null)     throw new IOException("Could not initialize XML Schema");
    schemaObject=parser.getResult().getSchema(targetNamespace);
    addSchemaElements();
  }
 catch (  TransformerConfigurationException e) {
    throw new IOException("Problem initializing XML Schema.",e);
  }
catch (  TransformerException e) {
    throw new IOException("Problem initializing XML Schema.",e);
  }
catch (  SAXException e) {
    throw new IOException("Problem initializing XML Schema.",e);
  }
}
 

Example 53

From project ISAvalidator-ISAconverter-BIImanager, under directory /import_layer/src/main/java/org/isatools/isatab/isaconfigurator/ontology_services/.

Source file: BioPortalClient.java

  29 
vote

/** 
 * Gives a map of Symbol=>BioPortalID. It is cached.
 */
private Map<String,String> getOntologyIds(){
  if (_ontologyIdsCache != null) {
    return _ontologyIdsCache;
  }
  _ontologyIdsCache=new HashMap<String,String>();
  try {
    Document dom=callREST("http://rest.bioontology.org/bioportal/ontologies");
    if (dom == null) {
      return _ontologyIdsCache;
    }
    NodeIterator ontoItr=XPathAPI.selectNodeIterator(dom,"success/data/list/ontologyBean");
    for (Node node=ontoItr.nextNode(); node != null; node=ontoItr.nextNode()) {
      String abbr=getTextNode(node,"abbreviation");
      if (abbr == null) {
        continue;
      }
      String id=getTextNode(node,"ontologyId");
      if (id == null) {
        continue;
      }
      _ontologyIdsCache.put(abbr,id);
    }
  }
 catch (  TransformerException e) {
    log.debug("Internal error while invoking BioPortal Service:" + e.getMessage(),e);
  }
  return _ontologyIdsCache;
}
 

Example 54

From project iserve, under directory /iserve-parent/iserve-importer-hrests/src/main/java/uk/ac/open/kmi/iserve/importer/hrests/.

Source file: HrestsImporter.java

  29 
vote

@Override protected InputStream transformStream(String serviceDescription) throws ImporterException {
  Document document=parser.parseDOM(new ByteArrayInputStream(serviceDescription.getBytes()),null);
  DOMSource source=new DOMSource(document);
  ByteArrayOutputStream bout=new ByteArrayOutputStream();
  StreamResult result=new StreamResult(bout);
  try {
    transformer.transform(source,result);
  }
 catch (  TransformerException e) {
    throw new ImporterException(e);
  }
  if (null == result.getOutputStream())   return null;
  String resultString=result.getOutputStream().toString();
  return new ByteArrayInputStream(resultString.getBytes());
}
 

Example 55

From project jangaroo-tools, under directory /asdoc-scraping/src/main/java/net/jangaroo/tools/asdocscreenscraper/.

Source file: ASDocScreenScraper.java

  29 
vote

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, TransformerException, URISyntaxException {
  if (args.length > 0) {
    new ASDocScreenScraper(ADOBE_FLASH_PLATFORM_REFERENCE_BASE_URL + args[0].replaceAll("\\.","/") + ".html").scrape();
    return;
  }
  Document classSummaryDocument=loadAndParse(new URI(ADOBE_FLASH_PLATFORM_REFERENCE_BASE_URL + "class-summary.html"));
  XPath xpath=xPathFactory.newXPath();
  XPathExpression classNodesExpression=xpath.compile("//*[@class='summaryTable']//*[name()='tr'][not(@product)][contains(@runtime,'Flash::')]//*[name()='a']/@href");
  NodeList classNodes=(NodeList)classNodesExpression.evaluate(classSummaryDocument,XPathConstants.NODESET);
  System.out.println("Hits: " + classNodes.getLength());
  for (int i=0; i < classNodes.getLength(); i++) {
    String relativeClassUrl=classNodes.item(i).getNodeValue();
    if (!relativeClassUrl.endsWith("package-detail.html")) {
      System.out.println(relativeClassUrl);
      new ASDocScreenScraper(ADOBE_FLASH_PLATFORM_REFERENCE_BASE_URL + relativeClassUrl).scrape();
    }
  }
}
 

Example 56

From project jASM_16, under directory /src/main/java/de/codesourcery/jasm16/ide/.

Source file: ProjectConfiguration.java

  29 
vote

private void writeXML(Document doc,File file) throws TransformerFactoryConfigurationError, TransformerException {
  final Source source=new DOMSource(doc);
  final Result result=new StreamResult(file);
  final Transformer xformer=TransformerFactory.newInstance().newTransformer();
  xformer.transform(source,result);
}
 

Example 57

From project jbpm-form-builder, under directory /jbpm-gwt-form-builder/src/main/java/org/jbpm/formbuilder/server/render/xsl/.

Source file: Renderer.java

  29 
vote

@Override public Object render(URL url,Map<String,Object> inputData) throws RendererException {
  try {
    StreamSource template=new StreamSource(url.openStream());
    Transformer transformer=factory.newTransformer(template);
    StringWriter writer=new StringWriter();
    StreamResult result=new StreamResult(writer);
    StreamSource inputSource=new StreamSource(toInputString(inputData));
    transformer.transform(inputSource,result);
    return writer.toString();
  }
 catch (  IOException e) {
    throw new RendererException("I/O problem rendering " + url,e);
  }
catch (  TransformerConfigurationException e) {
    throw new RendererException("transformer configuration problem rendering " + url,e);
  }
catch (  TransformerException e) {
    throw new RendererException("transformer problem rendering " + url,e);
  }
 finally {
    new File(url.getFile()).delete();
  }
}
 

Example 58

From project jbpmmigration, under directory /src/main/java/org/jbpm/migration/.

Source file: JbpmMigration.java

  29 
vote

/** 
 * Accept two or three command line arguments: - the name of an XML file (required) - the name of an XSLT stylesheet (optional, default is jpdl 3.2) - the name of the file the result of the transformation is to be written to.
 */
public static void main(final String[] args) throws TransformerException {
  if (args.length == 2) {
    transform(args[0],null,args[1]);
  }
 else   if (args.length == 3) {
    transform(args[0],args[1],args[2]);
  }
 else {
    System.err.println("Usage:");
    System.err.println("  java " + JbpmMigration.class.getName() + " jpdlProcessDefinitionFileName xsltFileName outputFileName");
    System.err.println(" or you can use the default jpdl 3.2 transformation:");
    System.err.println("  java " + JbpmMigration.class.getName() + " jpdlProcessDefinitionFileName outputFileName");
    System.exit(1);
  }
}
 

Example 59

From project jCAE, under directory /amibe/src/org/jcae/mesh/xmldata/.

Source file: XMLHelper.java

  29 
vote

/** 
 * Write a DOM to a file. 
 */
public static void writeXML(Document document,File file) throws IOException {
  StreamResult result=new StreamResult(new BufferedOutputStream(new FileOutputStream(file)));
  TransformerFactory transFactory=TransformerFactory.newInstance();
  try {
    Transformer transformer=transFactory.newTransformer();
    transformer.setOutputProperty("indent","yes");
    transformer.transform(new DOMSource(document),result);
  }
 catch (  TransformerConfigurationException ex) {
    throw new IOException(ex.getMessage());
  }
catch (  TransformerException ex) {
    throw new IOException(ex.getMessage());
  }
  result.getOutputStream().close();
}
 

Example 60

From project JDave, under directory /jdave-report-plugin/src/java/org/jdave/maven/report/.

Source file: JDaveReportMojo.java

  29 
vote

@Override protected void executeReport(Locale locale) throws MavenReportException {
  try {
    getSink().rawText("<iframe src=\"jdave.html\" width=\"100%\" height=\"800\" />");
    getSink().flush();
    getSink().close();
    new SpecdoxTransformer().transform("jdave.html",reportsDirectory.toURI().toString(),outputDirectory,xrefLocation);
  }
 catch (  TransformerException e) {
    throw new MavenReportException("could not create a file",e);
  }
}
 

Example 61

From project jdeltasync, under directory /src/main/java/com/googlecode/jdeltasync/.

Source file: XmlUtil.java

  29 
vote

/** 
 * Writes the specified  {@link Document} to an {@link OutputStream} in the specified format.
 * @param doc the {@link Document}.
 * @param out the stream to write to.
 * @param compact if <code>true</code> the XML will be written in compactformat without any extra whitespaces.
 * @throws XmlException on XML errors.
 */
public static void writeDocument(Document doc,OutputStream out,boolean compact) throws XmlException {
  try {
    TransformerFactory tf=TransformerFactory.newInstance();
    Transformer serializer=tf.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT,compact ? "no" : "yes");
    serializer.transform(new DOMSource(doc),new StreamResult(out));
  }
 catch (  TransformerException e) {
    throw new XmlException(e);
  }
}
 

Example 62

From project Jenkins-Repository, under directory /jenkins-maven-plugin/src/main/java/com/nirima/jenkins/.

Source file: SimpleArtifactCopier.java

  29 
vote

public void updateAll(Artifact art) throws IOException, HttpException, URISyntaxException, ParserConfigurationException, SAXException, TransformerException {
  List<String> items=fetchFiles(art);
  for (  String item : items) {
    fetchFile(art,item);
  }
}
 

Example 63

From project jetty-project, under directory /jetty-jboss/src/main/java/org/jboss/jetty/.

Source file: Jetty.java

  29 
vote

/** 
 * @param configElement XML fragment from jboss-service.xml
 */
public void setConfigurationElement(Element configElement){
  _configElement=configElement;
  try {
    DOMSource source=new DOMSource(configElement);
    CharArrayWriter writer=new CharArrayWriter();
    StreamResult result=new StreamResult(writer);
    TransformerFactory factory=TransformerFactory.newInstance();
    Transformer transformer=factory.newTransformer();
    transformer.transform(source,result);
    _xmlConfigString=writer.toString();
    int index=_xmlConfigString.indexOf("?>");
    if (index >= 0) {
      index+=2;
      while ((_xmlConfigString.charAt(index) == '\n') || (_xmlConfigString.charAt(index) == '\r'))       index++;
    }
    _xmlConfigString=_xmlConfigString.substring(index);
    if (_log.isDebugEnabled())     _log.debug("Passing xml config to jetty:\n" + _xmlConfigString);
    setXMLConfiguration(_xmlConfigString);
  }
 catch (  TransformerConfigurationException tce) {
    _log.error("Can't transform config Element -> xml:",tce);
  }
catch (  TransformerException te) {
    _log.error("Can't transform config Element -> xml:",te);
  }
catch (  Exception e) {
    _log.error("Unexpected exception converting configuration Element -> xml",e);
  }
}
 

Example 64

From project Jetwick, under directory /src/main/java/de/jetwick/util/.

Source file: Helper.java

  29 
vote

public static String getDocumentAsString(Node node,boolean prettyXml) throws TransformerException, UnsupportedEncodingException {
  Transformer transformer=TransformerFactory.newInstance().newTransformer();
  if (prettyXml) {
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
  }
  transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  transformer.transform(new DOMSource(node),new StreamResult(baos));
  return baos.toString("UTF-8");
}
 

Example 65

From project jMemorize, under directory /src/jmemorize/core/io/.

Source file: XmlBuilder.java

  29 
vote

/** 
 * Saves the lesson to an  {@link OutputStream} which contains an XMLdocument. Don't use this method directly. Use the  {@link LessonProvider} instead.XML-Schema: <lesson>  <deck>  <card frontside="bla" backside="bla"/> ..  </deck> .. </lesson>
 */
public static void saveAsXMLFile(File file,Lesson lesson) throws IOException, TransformerException, ParserConfigurationException {
  OutputStream out;
  ZipOutputStream zipOut=null;
  if (Settings.loadIsSaveCompressed()) {
    out=zipOut=new ZipOutputStream(new FileOutputStream(file));
    zipOut.putNextEntry(new ZipEntry(LESSON_ZIP_ENTRY_NAME));
  }
 else {
    out=new FileOutputStream(file);
  }
  try {
    Document document=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element lessonTag=document.createElement(LESSON);
    document.appendChild(lessonTag);
    writeCategory(document,lessonTag,lesson.getRootCategory());
    writeLearnHistory(document,lesson.getLearnHistory());
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    transformer.transform(new DOMSource(document),new StreamResult(out));
  }
  finally {
    if (zipOut != null)     zipOut.closeEntry();
 else     if (out != null)     out.close();
  }
  try {
    removeUnusedImagesFromRepository(lesson);
    if (zipOut == null)     writeImageRepositoryToDisk(new File(file.getParent()));
 else     writeImageRepositoryToZip(zipOut);
  }
  finally {
    if (zipOut != null)     zipOut.close();
  }
}
 

Example 66

From project jOOX, under directory /jOOX/src/main/java/org/joox/.

Source file: Impl.java

  29 
vote

@Override public final Impl transform(Transformer transformer){
  List<DOMResult> results=new ArrayList<DOMResult>();
  List<Element> newElements=new ArrayList<Element>();
  try {
    for (    Element element : get()) {
      DOMResult result=new DOMResult();
      transformer.transform(new DOMSource(element),result);
      results.add(result);
    }
  }
 catch (  TransformerException e) {
    throw new RuntimeException(e);
  }
  for (int i=0; i < size(); i++) {
    Element element=get(i);
    Element result=((Document)results.get(i).getNode()).getDocumentElement();
    result=(Element)document().importNode(result,true);
    element.getParentNode().replaceChild(result,element);
    newElements.add(result);
  }
  return new Impl(document,namespaces).addElements(newElements);
}
 

Example 67

From project Kairos, under directory /src/java/org/apache/nutch/util/.

Source file: DomUtil.java

  29 
vote

/** 
 * save dom into ouputstream
 * @param os
 * @param e
 */
public static void saveDom(OutputStream os,Element e){
  DOMSource source=new DOMSource(e);
  TransformerFactory transFactory=TransformerFactory.newInstance();
  Transformer transformer;
  try {
    transformer=transFactory.newTransformer();
    transformer.setOutputProperty("indent","yes");
    StreamResult result=new StreamResult(os);
    transformer.transform(source,result);
    os.flush();
  }
 catch (  UnsupportedEncodingException e1) {
    e1.printStackTrace(LogUtil.getWarnStream(LOG));
  }
catch (  IOException e1) {
    e1.printStackTrace(LogUtil.getWarnStream(LOG));
  }
catch (  TransformerConfigurationException e2) {
    e2.printStackTrace(LogUtil.getWarnStream(LOG));
  }
catch (  TransformerException ex) {
    ex.printStackTrace(LogUtil.getWarnStream(LOG));
  }
}
 

Example 68

From project LABPipe, under directory /src/org/bultreebank/labpipe/utils/.

Source file: XmlUtils.java

  29 
vote

/** 
 * Prints the <code>Document</code> as a <code>String</code> into the <code>OutputStream</code>.
 * @param doc XML DOM object
 * @param out <code>OutputStream</code>
 */
public static void print(Document doc,OutputStream out){
  TransformerFactory tfactory=TransformerFactory.newInstance();
  Transformer serializer;
  try {
    serializer=tfactory.newTransformer();
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
    serializer.transform(new DOMSource(doc),new StreamResult(out));
    if (!out.equals(System.out)) {
      out.close();
    }
  }
 catch (  IOException ex) {
    logger.log(Level.SEVERE,ServiceConstants.EXCEPTION_IO,ex);
  }
catch (  TransformerException ex) {
    logger.log(Level.SEVERE,null,ex);
  }
}
 

Example 69

From project lenya, under directory /org.apache.lenya.core.cocoon/src/main/java/org/apache/lenya/cms/cocoon/source/.

Source file: RepositorySource.java

  29 
vote

protected InputStream convert(org.w3c.dom.Document edoc) throws IOException {
  final org.w3c.dom.Document doc=edoc;
  final PipedOutputStream pos=new PipedOutputStream();
  PipedInputStream pis=new PipedInputStream();
  pis.connect(pos);
  (new Thread(new Runnable(){
    public void run(){
      try {
        transform(doc,pos);
      }
 catch (      TransformerException e) {
        throw new RuntimeException("Failed to tranform org.w3c.dom.Document to PipedOutputStream",e);
      }
 finally {
        try {
          pos.close();
        }
 catch (        Exception ignore) {
          ignore.printStackTrace();
        }
      }
    }
  }
,getClass().getName() + ".convert(org.w3c.dom.Document edoc)")).start();
  return pis;
}
 

Example 70

From project leviathan, under directory /scrapper/src/main/java/com/zaubersoftware/leviathan/api/engine/impl/pipe/.

Source file: XMLPipe.java

  29 
vote

/** 
 * Applies the XSL Transformation and returns the resulting Node.
 * @param node
 * @param model
 * @param oformat
 * @return
 * @throws TransformerFactoryConfigurationError
 */
private Node applyXSLT(final Node node,final Map<String,Object> model,final Properties oformat){
  Validate.notNull(node,"The node cannot be null.");
  try {
    final Transformer transformer=template.newTransformer();
    Validate.notNull(transformer);
    for (    final Entry<String,Object> entry : model.entrySet()) {
      transformer.setParameter(entry.getKey(),entry.getValue());
    }
    Properties options;
    if (oformat != null) {
      options=new Properties(oformat);
    }
 else {
      options=new Properties();
    }
    if (this.encoding != null) {
      options.setProperty(OutputKeys.ENCODING,this.encoding);
    }
    transformer.setOutputProperties(options);
    final DOMResult result=new DOMResult();
    transformer.transform(new DOMSource(node),result);
    return result.getNode();
  }
 catch (  final TransformerException e) {
    this.logger.error("An error ocurred while applying the XSL transformation",e);
    throw new NotImplementedException("Handle exception with context stack handlers");
  }
catch (  final TransformerFactoryConfigurationError e) {
    this.logger.error("An error ocurred while applying the XSL transformation",e);
    throw new NotImplementedException("Handle exception with context stack handlers");
  }
}
 

Example 71

From project libra, under directory /tests/org.eclipse.libra.facet.test/src/org/eclipse/libra/facet/test/.

Source file: WebContextRootSynchronizerTest.java

  29 
vote

private void setWebContextRootInSettings(IProject wabProject,String newValue) throws ParserConfigurationException, SAXException, IOException, TransformerException, CoreException {
  IFile settingsFile=wabProject.getFile(VIRTUAL_COMPONENT_PATH);
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  DocumentBuilder db=dbf.newDocumentBuilder();
  Document xmlDocument=db.parse(settingsFile.getContents());
  changeWebContextRootFromSettings(xmlDocument,newValue);
  InputStream is=new ByteArrayInputStream(saveDomToBytes(xmlDocument));
  settingsFile.setContents(is,IResource.KEEP_HISTORY | IResource.FORCE,null);
}
 

Example 72

From project license-maven-plugin, under directory /src/test/java/org/codehaus/mojo/license/.

Source file: LicenseSummaryTest.java

  29 
vote

/** 
 * Test writing license information to a license.xml file and then read this file back in to make sure it's ok.
 */
@Test public void testWriteReadLicenseSummary() throws IOException, SAXException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException {
  List<ProjectLicenseInfo> licSummary=new ArrayList<ProjectLicenseInfo>();
  ProjectLicenseInfo dep1=new ProjectLicenseInfo("org.test","test1","1.0");
  ProjectLicenseInfo dep2=new ProjectLicenseInfo("org.test","test2","2.0");
  License lic=new License();
  lic.setName("lgpl");
  lic.setUrl("http://www.gnu.org/licenses/lgpl-3.0.txt");
  lic.setComments("lgpl version 3.0");
  dep1.addLicense(lic);
  dep2.addLicense(lic);
  licSummary.add(dep1);
  licSummary.add(dep2);
  File licenseSummaryFile=File.createTempFile("licSummary","tmp");
  LicenseSummaryWriter.writeLicenseSummary(licSummary,licenseSummaryFile);
  Assert.assertTrue(licenseSummaryFile.exists());
  FileInputStream fis=new FileInputStream(licenseSummaryFile);
  List<ProjectLicenseInfo> list=LicenseSummaryReader.parseLicenseSummary(fis);
  fis.close();
  ProjectLicenseInfo dep=list.get(0);
  Assert.assertEquals("org.test",dep.getGroupId());
  Assert.assertEquals("test1",dep.getArtifactId());
  Assert.assertEquals("1.0",dep.getVersion());
}
 

Example 73

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/util/xml/.

Source file: DefaultXmlWriter.java

  29 
vote

public void write(Document doc,OutputStream outputStream) throws IOException {
  try {
    TransformerFactory factory=TransformerFactory.newInstance();
    try {
      factory.setAttribute("indent-number",4);
    }
 catch (    Exception e) {
      ;
    }
    Transformer transformer=factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD,"xml");
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
    transformer.transform(new DOMSource(doc),new StreamResult(new OutputStreamWriter(outputStream,"utf-8")));
  }
 catch (  TransformerException e) {
    throw new IOException(e.getMessage());
  }
}
 

Example 74

From project lyo.core, under directory /OSLC4JJenaProvider/src/org/eclipse/lyo/oslc4j/provider/jena/.

Source file: JenaModelHelper.java

  29 
vote

private static Transformer createTransformer(){
  try {
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
    return transformer;
  }
 catch (  TransformerException e) {
    throw new RuntimeException(e);
  }
}