Process the source tree to the output result.
@param xmlSource  The input for the source tree.
@param outputTarget The output source target.
@param shouldRelease  Flag indicating whether to release DTMManager.

@throws TransformerException
773679
public void transform(Source xmlSource, Result outputTarget, boolean shouldRelease)
          throws TransformerException
  {

    synchronized (m_reentryGuard)
    {
      SerializationHandler xoh = createSerializationHandler(outputTarget);
      this.setSerializationHandler(xoh);        

      m_outputTarget = outputTarget;

      transform(xmlSource, shouldRelease);
    }
  }
719682
private Object readMetadataFromXML(InputSource source, Class target)
            throws MalformedURLException, ParserConfigurationException, SAXException, IOException
    {
        // TODO: make this configurable
        boolean validate = false;
        
        // get a xml reader instance:
        SAXParserFactory factory = SAXParserFactory.newInstance();
        log.info("RepositoryPersistor using SAXParserFactory : " + factory.getClass().getName());
        if (validate)
        {
            factory.setValidating(true);
        }
        SAXParser p = factory.newSAXParser();
        XMLReader reader = p.getXMLReader();
        if (validate)
        {
            reader.setErrorHandler(new OJBErrorHandler());
        }

        Object result;
        if (DescriptorRepository.class.equals(target))
        {
            // create an empty repository:
            DescriptorRepository repository = new DescriptorRepository();
            // create handler for building the repository structure
            ContentHandler handler = new RepositoryXmlHandler(repository);
            // tell parser to use our handler:
            reader.setContentHandler(handler);
            reader.parse(source);
            result = repository;
        }
        else if (ConnectionRepository.class.equals(target))
        {
            // create an empty repository:
            ConnectionRepository repository = new ConnectionRepository();
            // create handler for building the repository structure
            ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);
            // tell parser to use our handler:
            reader.setContentHandler(handler);
            reader.parse(source);
            //LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs");
            result = repository;
        }
        else
            throw new MetadataException("Could not build a repository instance for '" + target +
                    "', using source " + source);
        return result;
    }
469224
public void execute(
          TransformerImpl transformer)
            throws TransformerException
  {

    if (null != m_template)
    {
      XPathContext xctxt = transformer.getXPathContext();
      VariableStack vars = xctxt.getVarStack();

      int thisframe = vars.getStackFrame();
      int nextFrame = vars.link(m_template.m_frameSize);
      
      // We have to clear the section of the stack frame that has params 
      // so that the default param evaluation will work correctly.
      if(m_template.m_inArgsSize > 0)
      {
        vars.clearLocalSlots(0, m_template.m_inArgsSize);
      
        if(null != m_paramElems)
        {
          int currentNode = xctxt.getCurrentNode();
          vars.setStackFrame(thisframe);
          int size = m_paramElems.length;
          
          for (int i = 0; i < size; i++) 
          {
            ElemWithParam ewp = m_paramElems[i];
            if(ewp.m_index >= 0)
            {
              XObject obj = ewp.getValue(transformer, currentNode);

              // Note here that the index for ElemWithParam must have been
              // statically made relative to the xsl:template being called, 
              // NOT this xsl:template.
              vars.setLocalVariable(ewp.m_index, obj, nextFrame);
            }
          }
          vars.setStackFrame(nextFrame);
        }
      }
      
      SourceLocator savedLocator = xctxt.getSAXLocator();

      try
      {
        xctxt.setSAXLocator(m_template);

        // template.executeChildTemplates(transformer, sourceNode, mode, true);
        transformer.pushElemTemplateElement(m_template);
        m_template.execute(transformer);
      }
      finally
      {
        transformer.popElemTemplateElement();
        xctxt.setSAXLocator(savedLocator);
        // When we entered this function, the current 
        // frame buffer (cfb) index in the variable stack may 
        // have been manually set.  If we just call 
        // unlink(), however, it will restore the cfb to the 
        // previous link index from the link stack, rather than 
        // the manually set cfb.  So, 
        // the only safe solution is to restore it back 
        // to the same position it was on entry, since we're 
        // really not working in a stack context here. (Bug4218)
        vars.unlink(thisframe);
      }
    }
    else
    {
      transformer.getMsgMgr().error(this, XSLTErrorResources.ER_TEMPLATE_NOT_FOUND,
                                    new Object[]{ m_templateName });  //"Could not find template named: '"+templateName+"'");
    }
    
  }
952836
@Nonnull
  public static ESuccess visualize (@Nonnull final EEbInterfaceVersion eVersion,
                                    @Nonnull final Source aSource,
                                    @Nonnull final Result aResult)
  {
    ValueEnforcer.notNull (eVersion, "version");

    // Get cache XSL templates
    final Templates aTemplates = getXSLTTemplates (eVersion);
    if (aTemplates == null)
      return ESuccess.FAILURE;

    // Start the main transformation
    try
    {
      final Transformer aTransformer = aTemplates.newTransformer ();
      aTransformer.transform (aSource, aResult);
      return ESuccess.SUCCESS;
    }
    catch (final TransformerException ex)
    {
      LOGGER.error ("Failed to apply transformation for ebInterface " + eVersion + " invoice", ex);
      return ESuccess.FAILURE;
    }
  }
1155348
public static void transformDocumentToXml(DomDocument document, StreamResult result) {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    try {
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      synchronized(document) {
        transformer.transform(document.getDomSource(), result);
      }
    } catch (TransformerConfigurationException e) {
      throw new ModelIoException("Unable to create a transformer for the model", e);
    } catch (TransformerException e) {
      throw new ModelIoException("Unable to transform model to xml", e);
    }
  }
279790
public void transformSelectedNodes(TransformerImpl transformer)
          throws TransformerException
  {

    final XPathContext xctxt = transformer.getXPathContext();
    final int sourceNode = xctxt.getCurrentNode();
    DTMIterator sourceNodes = m_selectExpression.asIterator(xctxt,
            sourceNode);

    try
    {

      final Vector keys = (m_sortElems == null)
              ? null
              : transformer.processSortKeys(this, sourceNode);

      // Sort if we need to.
      if (null != keys)
        sourceNodes = sortNodes(xctxt, keys, sourceNodes);

      xctxt.pushCurrentNode(DTM.NULL);

      IntStack currentNodes = xctxt.getCurrentNodeStack();

      xctxt.pushCurrentExpressionNode(DTM.NULL);

      IntStack currentExpressionNodes = xctxt.getCurrentExpressionNodeStack();

      xctxt.pushSAXLocatorNull();
      xctxt.pushContextNodeList(sourceNodes);
      transformer.pushElemTemplateElement(null);

      // pushParams(transformer, xctxt);
      // Should be able to get this from the iterator but there must be a bug.
      DTM dtm = xctxt.getDTM(sourceNode);
      int docID = sourceNode & DTMManager.IDENT_DTM_DEFAULT;
      int child;

      while (DTM.NULL != (child = sourceNodes.nextNode()))
      {
        currentNodes.setTop(child);
        currentExpressionNodes.setTop(child);

        if ((child & DTMManager.IDENT_DTM_DEFAULT) != docID)
        {
          dtm = xctxt.getDTM(child);
          docID = child & DTMManager.IDENT_DTM_DEFAULT;
        }

        //final int exNodeType = dtm.getExpandedTypeID(child);
        final int nodeType = dtm.getNodeType(child); 

        // And execute the child templates.
        // Loop through the children of the template, calling execute on 
        // each of them.
        for (ElemTemplateElement t = this.m_firstChild; t != null;
             t = t.m_nextSibling)
        {
          xctxt.setSAXLocator(t);
          transformer.setCurrentElement(t);
          t.execute(transformer);
        }

        // KLUGE: Implement <?xalan:doc_cache_off?>
	 	// ASSUMPTION: This will be set only when the XPath was indeed
	 	// a call to the Document() function. Calling it in other
	 	// situations is likely to fry Xalan.
	 	//
	 	// %REVIEW% We need a MUCH cleaner solution -- one that will
	 	// handle cleaning up after document() and getDTM() in other
		// contexts. The whole SourceTreeManager mechanism should probably
	 	// be moved into DTMManager rather than being explicitly invoked in
	 	// FuncDocument and here.
	 	if(m_doc_cache_off)
		{
	 	  if(DEBUG)
	 	    System.out.println("JJK***** CACHE RELEASE *****\n"+
				       "\tdtm="+dtm.getDocumentBaseURI());
	  	// NOTE: This will work because this is _NOT_ a shared DTM, and thus has
	  	// only a single Document node. If it could ever be an RTF or other
	 	// shared DTM, this would require substantial rework.
	 	  xctxt.getSourceTreeManager().removeDocumentFromCache(dtm.getDocument());
	 	  xctxt.release(dtm,false);
	 	}
      }
    }
    finally
    {
      xctxt.popSAXLocator();
      xctxt.popContextNodeList();
      transformer.popElemTemplateElement();
      xctxt.popCurrentExpressionNode();
      xctxt.popCurrentNode();
      sourceNodes.detach();
    }
  }
1092347
public void execute(
          TransformerImpl transformer)
            throws TransformerException
  {
    try
    {
      SerializationHandler rth = transformer.getResultTreeHandler();

        if (m_disableOutputEscaping)
      {
        rth.processingInstruction(javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, "");
      }

      rth.characters(m_ch, 0, m_ch.length);

      if (m_disableOutputEscaping)
      {
        rth.processingInstruction(javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, "");
      }
    }
    catch(SAXException se)
    {
      throw new TransformerException(se);
    }
  }
793488
public boolean createReprojectTransformTask(Integer importJobId, Integer taskId,
                                                String sourceSrs, String targetSrs) throws URISyntaxException, HttpException {
        RESTReprojectTransform transformTask = new RESTReprojectTransform();
        if (StringUtils.isNotEmpty(sourceSrs)) {
            transformTask.setSource(sourceSrs);
        }
        transformTask.setTarget(targetSrs);

        return createTransformTask(importJobId, taskId, transformTask);
    }
859049
public void updateByXml(Source source) throws IOException {
        checkPermission(CONFIGURE);
        StringWriter out = new StringWriter();
        try {
            // this allows us to use UTF-8 for storing data,
            // plus it checks any well-formedness issue in the submitted
            // data
            XMLUtils.safeTransform(source, new StreamResult(out));
            out.close();
        } catch (TransformerException|SAXException e) {
            throw new IOException("Failed to persist configuration.xml", e);
        }

        // try to reflect the changes by reloading
        try (InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8)))){
            // Do not allow overwriting view name as it might collide with another
            // view in same ViewGroup and might not satisfy Jenkins.checkGoodName.
            String oldname = name;
            ViewGroup oldOwner = owner; // oddly, this field is not transient
            Object o = Jenkins.XSTREAM2.unmarshal(XStream2.getDefaultDriver().createReader(in), this, null, true);
            if (!o.getClass().equals(getClass())) {
                // ensure that we've got the same view type. extending this code to support updating
                // to different view type requires destroying & creating a new view type
                throw new IOException("Expecting view type: "+this.getClass()+" but got: "+o.getClass()+" instead." +
                    "\nShould you needed to change to a new view type, you must first delete and then re-create " +
                    "the view with the new view type.");
            }
            name = oldname;
            owner = oldOwner;
        } catch (StreamException | ConversionException | Error e) {// mostly reflection errors
            throw new IOException("Unable to read",e);
        }
        save();
    }
758413
protected boolean transform(IResource resource) throws Exception {
        String name = StringUtils.trimToEmpty(resource.getSourcePath());
        
        if (resource.isDirectory() || mojo.isExcluded(name)) {
            return false;
        }
        
        AbstractTransform transform = getTransform(name);
        String targetPath = transform == null ? null : transform.getTargetPath(resource);
        
        if (targetPath != null) {
            File out = mojo.newStagingFile(relocateResource(targetPath), resource.getTime());
            try (OutputStream outputStream = new FileOutputStream(out);) {
                transform.transform(resource, outputStream);
                return true;
            }
        }
        
        return false;
    }
220852
public static void copySubtree(@NotNull Resource targetParent, @NotNull Resource source) {
    Resource targetChild = GraniteUiSyntheticResource.child(targetParent, source.getName(), source.getResourceType(), source.getValueMap());
    for (Resource sourceChild : source.getChildren()) {
      copySubtree(targetChild, sourceChild);
    }
  }
1172499
@Override
    protected void emitStartElement(final INodeReadTrx rtx) throws TTIOException {
        switch (rtx.getNode().getKind()) {
        case ROOT:
            break;
        case ELEMENT:
            generateElement(rtx);
            break;
        case TEXT:
            generateText(rtx);
            break;
        default:
            throw new UnsupportedOperationException("Node kind not supported by Treetank!");
        }
    }
437186
public static Element sourceToElement(Source source) throws IOException
   {
      Element retElement = null;

      if (source instanceof StreamSource)
      {
         StreamSource streamSource = (StreamSource)source;

         InputStream ins = streamSource.getInputStream();
         if (ins != null)
         {
            retElement = DOMUtils.parse(ins);
         }
         Reader reader = streamSource.getReader();
         if (reader != null)
         {
            retElement = DOMUtils.parse(new InputSource(reader));
         }
      }
      else if (source instanceof DOMSource)
      {
         DOMSource domSource = (DOMSource)source;
         Node node = domSource.getNode();
         if (node instanceof Element)
         {
            retElement = (Element)node;
         }
         else if (node instanceof Document)
         {
            retElement = ((Document)node).getDocumentElement();
         }
      }
      else if (source instanceof SAXSource)
      {
         // The fact that JAXBSource derives from SAXSource is an implementation detail.
         // Thus in general applications are strongly discouraged from accessing methods defined on SAXSource.
         // The XMLReader object obtained by the getXMLReader method shall be used only for parsing the InputSource object returned by the getInputSource method.

         final boolean hasInputSource = ((SAXSource) source).getInputSource() != null; 
         final boolean hasXMLReader = ((SAXSource) source).getXMLReader() != null;

         if (hasInputSource || hasXMLReader)
         {
            try
            {
               TransformerFactory tf = TransformerFactory.newInstance();
               ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
               Transformer transformer = tf.newTransformer();
               transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
               transformer.setOutputProperty(OutputKeys.METHOD, "xml");
               transformer.transform(source, new StreamResult(baos));
               retElement = DOMUtils.parse(new ByteArrayInputStream(baos.toByteArray()));
            }
            catch (TransformerException ex)
            {
               throw new IOException(ex);
            }
         }
      }
      else
      {
         throw MESSAGES.sourceTypeNotImplemented(source.getClass());
      }

      return retElement;
   }
220801
public void setSource(final String sourceText) {
		String formattedSource;

		if (sourceText == null) {
			formattedSource = "";
		} else {
			formattedSource = WebUtilities.encode(sourceText); // XML escape content
		}

		source.setText(formattedSource);
	}
1094002
public void transform(Source pIn) throws JspException {
        try {
            // Create transformer
            Transformer transformer = TransformerFactory.newInstance()
                    .newTransformer(getSource(mStylesheetURI));

            // Store temporary output in a bytearray, as the transformer will
            // usually try to flush the stream (illegal operation from a custom
            // tag).
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            StreamResult out = new StreamResult(os);

            // Perform the transformation
            transformer.transform(pIn, out);

            // Write the result back to the JSP writer
            pageContext.getOut().print(os.toString());
        }
        catch (MalformedURLException murle) {
            throw new JspException(murle.getMessage(), murle);
        }
        catch (IOException ioe) {
            throw new JspException(ioe.getMessage(), ioe);
        }
        catch (TransformerException te) {
            throw new JspException("XSLT Trandformation failed: " + te.getMessage(), te);
        }
    }
1224992
public void parse(Reader xmlReader) throws XMLStreamException {
    if (isoControlCharsAwareParser) {
      throw new XMLStreamException("Method call not supported when isoControlCharsAwareParser=true");
    }
    parse(inf.rootElementCursor(xmlReader));
  }
26589
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
			throws IOException {
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			Document document = builder.newDocument();

			document.appendChild(emitterToElement(document, emitter));
			Result result = new StreamResult(new OutputStreamWriter(out,
					"utf-8"));
			DOMSource source = new DOMSource(document);

			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer xformer = factory.newTransformer();
			xformer.setOutputProperty(OutputKeys.INDENT, "yes");

			xformer.transform(source, result);
		} catch (Exception e) {
			Log.error(e);
			throw new IOException("Failed to save emitter");
		}
	}