Java Code Examples for javax.xml.transform.stream.StreamSource

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 c24-spring, under directory /c24-spring-core/src/main/java/biz/c24/io/spring/oxm/.

Source file: C24Marshaller.java

  33 
vote

public Object unmarshal(Source source) throws IOException, XmlMappingException {
  Assert.isInstanceOf(StreamSource.class,source,UNSUPPORTED_SOURCE);
  StreamSource streamSource=(StreamSource)source;
  XMLSource xmlSource=getXmlSourceFrom(streamSource);
  ComplexDataObject result=xmlSource.readObject(model.getRootElement());
  return C24Utils.potentiallyUnwrapDocumentRoot(result);
}
 

Example 2

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

Source file: ScreenScrapingService.java

  33 
vote

/** 
 * Get portlet-specific XML for clean, valid HTML.
 * @param cleanHtml
 * @return
 * @throws TransformerException
 * @throws IOException
 */
protected String getXml(String cleanHtml) throws TransformerException, IOException {
  final StreamSource xsltSource=new StreamSource(xslt.getInputStream());
  final Transformer identityTransformer=transformerFactory.newTransformer(xsltSource);
  identityTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
  final StringWriter outputWriter=new StringWriter();
  final StreamResult outputTarget=new StreamResult(outputWriter);
  final StreamSource xmlSource=new StreamSource(new StringReader(cleanHtml));
  identityTransformer.transform(xmlSource,outputTarget);
  final String content=outputWriter.toString();
  return content;
}
 

Example 3

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

Source file: MODSUIPFilter.java

  32 
vote

public MODSUIPFilter(){
  SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  StreamSource modsSource=new StreamSource(getClass().getResourceAsStream("/schemas/mods-3-4.xsd"));
  Schema modsSchema;
  try {
    modsSchema=sf.newSchema(modsSource);
  }
 catch (  SAXException e) {
    throw new RuntimeException("Initialization of MODS UIP Filter ran into an unexpected exception",e);
  }
  modsValidator=modsSchema.newValidator();
}
 

Example 4

From project coala, under directory /modules/coala-communication/src/main/java/org/openehealth/coala/transformer/.

Source file: XmlTransformer.java

  32 
vote

/** 
 * Transform a XSL InputStream into a StreamSource and set it as data field ( {@link XmlTransformer#xslStreamSource}).
 * @param inputStream required: the InputStream of a XSL file.
 * @throws IllegalArgumentException if the XSL InputStream isn't valid.
 * @throws XslTransformerException if the XSL InputStream can't be transformed to a StreamSource.
 */
public XmlTransformer(InputStream inputStream) throws IllegalArgumentException, XslTransformerException {
  if (inputStream == null)   throw new IllegalArgumentException("XSL InputStream is required.");
  try {
    StreamSource xslStreamSource=new StreamSource(inputStream);
    TransformerFactory transFact=TransformerFactory.newInstance();
    transformer=transFact.newTransformer(xslStreamSource);
  }
 catch (  Exception e) {
    throw new XslTransformerException("Can't transform a XSL InputStream into StreamSource.",e);
  }
}
 

Example 5

From project components, under directory /soap/src/main/java/org/switchyard/component/soap/util/.

Source file: WSDLUtil.java

  32 
vote

/** 
 * Read the WSDL document accessible via the specified URI into a StreamSource.
 * @param wsdlURI a URI (can be a filename or URL) pointing to aWSDL XML definition.
 * @return the StreamSource.
 * @throws WSDLException If unable to read the WSDL
 */
public static StreamSource getStream(final String wsdlURI) throws WSDLException {
  try {
    URL url=getURL(wsdlURI);
    InputStream inputStream=url.openStream();
    StreamSource inputSource=new StreamSource(inputStream);
    inputSource.setSystemId(url.toString());
    return inputSource;
  }
 catch (  Exception e) {
    throw new WSDLException(WSDLException.OTHER_ERROR,"Unable to resolve WSDL document at '" + wsdlURI,e);
  }
}
 

Example 6

From project gatein-toolbox, under directory /gen/core/src/main/java/org/gatein/descriptorgenerator/.

Source file: Main.java

  32 
vote

private static void reformatXML(Reader src,Writer dst) throws Exception {
  String s="" + "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n" + "<xsl:output method=\"xml\" omit-xml-declaration=\"yes\"/>\n"+ "<xsl:strip-space elements=\"*\"/>\n"+ "<xsl:template match=\"@*|node()\">\n"+ "<xsl:copy>\n"+ "<xsl:apply-templates select=\"@*|node()\"/>\n"+ "</xsl:copy>\n"+ "</xsl:template>\n"+ "</xsl:stylesheet>";
  TransformerFactory factory=TransformerFactory.newInstance();
  factory.setAttribute("indent-number",2);
  Transformer transformer=factory.newTransformer(new StreamSource(new StringReader(s)));
  transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  transformer.setOutputProperty(OutputKeys.METHOD,"xml");
  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",Integer.toString(2));
  transformer.setOutputProperty(OutputKeys.INDENT,"yes");
  StreamSource source=new StreamSource(src);
  StreamResult result=new StreamResult(dst);
  transformer.transform(source,result);
}
 

Example 7

From project gravitext, under directory /gravitext-xmlprod/src/main/java/com/gravitext/xml/jruby/.

Source file: XMLHelper.java

  32 
vote

@JRubyMethod(name="stax_parse_string",meta=true,required=2,argTypes={RubyString.class,StAXConsumer.class}) public static IRubyObject staxParse(ThreadContext tc,IRubyObject klazz,IRubyObject input,IRubyObject csmr) throws FactoryConfigurationError, XMLStreamException {
  ByteBuffer in=IOUtils.toByteBuffer(input.convertToString());
  StreamSource source=new StreamSource(Streams.inputStream(in));
  XMLStreamReader staxReader=StAXUtils.staxReader(source);
  StAXConsumer consumer=null;
  if (csmr.isNil()) {
    consumer=new StAXConsumer();
  }
 else {
    consumer=(StAXConsumer)csmr.toJava(StAXConsumer.class);
  }
  Element element=consumer.readDocument(staxReader);
  return Java.getInstance(tc.getRuntime(),element);
}
 

Example 8

From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/xml/.

Source file: ValidationXmlParser.java

  32 
vote

private ValidationConfigType unmarshal(InputStream inputStream,Schema schema){
  log.parsingXMLFile(VALIDATION_XML_FILE);
  try {
    JAXBContext jc=JAXBContext.newInstance(ValidationConfigType.class);
    Unmarshaller unmarshaller=jc.createUnmarshaller();
    unmarshaller.setSchema(schema);
    StreamSource stream=new StreamSource(inputStream);
    JAXBElement<ValidationConfigType> root=unmarshaller.unmarshal(stream,ValidationConfigType.class);
    return root.getValue();
  }
 catch (  JAXBException e) {
    throw log.getUnableToParseValidationXmlFileException(VALIDATION_XML_FILE,e);
  }
}
 

Example 9

From project miso-lims, under directory /core/src/main/java/uk/ac/bbsrc/tgac/miso/core/util/.

Source file: SubmissionUtils.java

  32 
vote

private static Reader bomCheck(File fromPath) throws IOException {
  StreamSource bomcheck=new StreamSource(new FileReader(fromPath));
  Reader reader=new BufferedReader(bomcheck.getReader());
  try {
    removeBOM(reader);
    return reader;
  }
 catch (  Exception e) {
    throw new IOException("Cannot remove byte-order-mark from XML file");
  }
}
 

Example 10

From project Ohmage_Server_2, under directory /src/org/ohmage/config/xml/.

Source file: CampaignValidator.java

  32 
vote

/** 
 * Validates a campaign's schema.
 * @param xml The campaign that will have its schema validated.
 * @param schema The schema used to validate the campaign XML.
 * @throws IOException Thrown if the schema file cannot be found or read.
 * @throws SAXException Thrown if the schema validation fails.
 */
private void checkSchemaOnStrings(String xml,String schemaFileName) throws IOException, SAXException {
  SAXSource xmlSource=new SAXSource(new InputSource(new StringReader(xml)));
  StreamSource schemaDocument=new StreamSource(new File(schemaFileName));
  SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Schema s=sf.newSchema(schemaDocument);
  Validator v=s.newValidator();
  v.validate(xmlSource);
}
 

Example 11

From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.

Source file: AlfrescoKickstartServiceImpl.java

  31 
vote

protected void prettyLogXml(String xml){
  try {
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    Source xmlInput=new StreamSource(new StringReader(xml));
    StreamResult xmlOutput=new StreamResult(new StringWriter());
    transformer.transform(xmlInput,xmlOutput);
    LOGGER.info(xmlOutput.getWriter().toString());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 12

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

Source file: HTMLLogTransformer.java

  31 
vote

/** 
 * Constructs  {@link HTMLLogTransformer} with initial XSL template andrelative path to html log data.
 * @param xsl initial template file
 * @param relative template variable that contains relative path from html log tohtml data (e.g. '../html-data')
 * @throws TransformerConfigurationException the transformer configuration exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public HTMLLogTransformer(File xsl,String relative) throws TransformerConfigurationException, IOException {
  System.setProperty("javax.xml.transform.TransformerFactory","net.sf.saxon.TransformerFactoryImpl");
  TransformerFactory factory=TransformerFactory.newInstance();
  transformer=factory.newTransformer(new StreamSource(xsl));
  transformer.setParameter("contextPath",relative);
}
 

Example 13

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

Source file: XSLTStylesheet.java

  31 
vote

public XSLTStylesheet(InputStream xsltFile){
  try {
    transformer=TransformerFactory.newInstance().newTransformer(new StreamSource(xsltFile));
  }
 catch (  TransformerConfigurationException e) {
    throw new RuntimeException("Should not happen, we use the default configuration",e);
  }
}
 

Example 14

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

Source file: XsltTask.java

  31 
vote

private Templates readTemplates() throws TransformerConfigurationException {
  InputStream xslStream=null;
  try {
    xslStream=new BufferedInputStream(new FileInputStream(styleFile));
    Source src=new StreamSource(xslStream);
    return factory.newTemplates(src);
  }
 catch (  FileNotFoundException e) {
    throw new BuildException(e);
  }
 finally {
    StreamUtils.close(xslStream);
  }
}
 

Example 15

From project Archimedes, under directory /br.org.archimedes.io.xml/src/br/org/archimedes/io/xml/.

Source file: XMLImporter.java

  31 
vote

/** 
 * @param inputStream The input stream to load the schema file.
 * @return A schema related to this input stream or null if the inputStreamwas null or there was a parse error
 */
private static Schema obtainSchema(InputStream inputStream){
  if (inputStream == null) {
    return null;
  }
  SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Source schemaFile=new StreamSource(inputStream);
  try {
    return factory.newSchema(schemaFile);
  }
 catch (  SAXException e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 16

From project bam, under directory /release/jbossas/tests/activity-management/bean-service/src/main/java/org/overlord/bam/tests/actmgmt/jbossas/beanservice/.

Source file: Transformers.java

  31 
vote

private Element toElement(String xml){
  DOMResult dom=new DOMResult();
  try {
    TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new StringReader(xml)),dom);
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return ((Document)dom.getNode()).getDocumentElement();
}
 

Example 17

From project blacktie, under directory /jatmibroker-nbf/src/main/java/org/jboss/narayana/blacktie/jatmibroker/nbf/.

Source file: NBFParser.java

  31 
vote

public boolean parse(byte[] buffer) throws ConfigurationException {
  boolean result=false;
  try {
    schema.newValidator().validate(new StreamSource(new ByteArrayInputStream(buffer)));
    saxParser.parse(new ByteArrayInputStream(buffer),handler);
    result=true;
  }
 catch (  Throwable e) {
    log.error("Parser buffer failed with " + e.getMessage(),e);
    throw new ConfigurationException("Parser buffer failed with " + e.getMessage());
  }
  return result;
}
 

Example 18

From project bundlemaker, under directory /main/org.bundlemaker.core/src/org/bundlemaker/core/internal/projectdescription/.

Source file: XmlProjectDescriptionExporterUtils.java

  31 
vote

/** 
 * <p> </p>
 * @param outputStream
 * @return
 */
public static XmlProjectDescriptionType unmarshal(InputStream inputStream){
  try {
    JaxbCompoundClassLoader jaxbCompoundClassLoader=new JaxbCompoundClassLoader();
    JAXBContext jaxbContext=JAXBContext.newInstance(jaxbCompoundClassLoader.getPackageString(),jaxbCompoundClassLoader.getCompoundClassLoader());
    Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
    JAXBElement<XmlProjectDescriptionType> root=unmarshaller.unmarshal(new StreamSource(inputStream),XmlProjectDescriptionType.class);
    return root.getValue();
  }
 catch (  Exception e) {
    throw new RuntimeException(e.getMessage(),e);
  }
}
 

Example 19

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

Source file: XSLTICalendarContentProcessorImpl.java

  31 
vote

protected final InputStream transformToICal(InputStream in) throws CalendarException {
  StreamSource xmlSource=new StreamSource(in);
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  try {
    log.debug("Stylesheet is " + xslFile);
    InputStream xsl=this.getClass().getClassLoader().getResourceAsStream(xslFile);
    Transformer tx=TransformerFactory.newInstance().newTransformer(new StreamSource(xsl));
    tx.transform(xmlSource,new StreamResult(out));
    log.debug(out.toString());
    InputStream result=new ByteArrayInputStream(out.toByteArray());
    return result;
  }
 catch (  TransformerConfigurationException tce) {
    log.error("Failed to configure transformer",tce);
    throw new CalendarException("Failed to configure transformer",tce);
  }
catch (  TransformerException txe) {
    throw new CalendarException("Failed transformation",txe);
  }
}
 

Example 20

From project catalog-api-client, under directory /client/src/main/java/com/shopzilla/api/service/.

Source file: ProductService.java

  31 
vote

public ProductResponse xmlInputStreamToJava(InputStream in) throws IOException, JAXBException {
  try {
    ProductResponse productResponse=(ProductResponse)unmarshaller.unmarshal(new StreamSource(in));
    System.out.println("productResponse = " + productResponse);
    return productResponse;
  }
 catch (  XmlMappingException xme) {
    xme.printStackTrace();
  }
  return null;
}
 

Example 21

From project CCR-Validator, under directory /src/main/java/org/openhealthdata/validation/.

Source file: CCRV1SchemaValidator.java

  31 
vote

/** 
 * Constructor which excepts the File location of the XSD.  If no  File was used special URIResolver would be needed.
 * @param schemaLocation
 * @throws SAXException
 */
public CCRV1SchemaValidator(String schemaLocation) throws SAXException {
  SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Source schemaFile=new StreamSource(new File(schemaLocation));
  Schema schema=factory.newSchema(schemaFile);
  validator=schema.newValidator();
  validator.setErrorHandler(eHandler);
  logger.log(Level.INFO,"Created " + this.getClass().getName() + " instance");
}
 

Example 22

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

Source file: RDFaParserImp.java

  31 
vote

public void parse(Reader in,String base) throws IOException, TransformerException, TransformerConfigurationException {
  if (theTemplates == null) {
    this.getClass().getClassLoader();
    StreamSource aSource=new StreamSource(ClassLoader.getSystemResource("net/yacy/serlex/parser/rdfa/RDFaParser.xsl").openStream());
    TransformerFactory aFactory=TransformerFactory.newInstance();
    theTemplates=aFactory.newTemplates(aSource);
  }
  Transformer aTransformer=theTemplates.newTransformer();
  aTransformer.setParameter("parser",this);
  aTransformer.setParameter("url",base);
  aTransformer.transform(new StreamSource(in),new StreamResult(new OutputStream(){
    public void write(    int b) throws IOException {
    }
  }
));
}
 

Example 23

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

Source file: PreferenceGuiHome.java

  31 
vote

private String domToString(Document rootDocument) throws TransformerException {
  StringWriter writer=new StringWriter();
  TransformerFactory tFactory=TransformerFactory.newInstance();
  Transformer transformer=tFactory.newTransformer(new StreamSource(new StringReader("<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + "    <xsl:output method=\"xml\" encoding=\"ISO-8859-1\"/>" + "    <xsl:template match=\"/\" > <xsl:copy-of select=\".\"/> </xsl:template>"+ "</xsl:stylesheet>")));
  transformer.transform(new DOMSource(rootDocument),new StreamResult(writer));
  return writer.toString();
}
 

Example 24

From project cogroo4, under directory /cogroo-gc/src/main/java/org/cogroo/tools/checker/rules/applier/.

Source file: RulesXmlAccess.java

  31 
vote

private void loadSchema(){
  if (this.schema == null) {
    InputStream in=null;
    try {
      in=this.schemaName.openStream();
      StreamSource ss=new StreamSource(in);
      SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      this.schema=sf.newSchema(ss);
    }
 catch (    SAXException saxe) {
      this.schema=null;
      throw new RulesException("Could not read file " + this.schemaName,saxe);
    }
catch (    IOException e) {
      throw new RulesException("Could not open schema " + this.schemaName,e);
    }
 finally {
      Closeables.closeQuietly(in);
    }
  }
}
 

Example 25

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

Source file: XMLHelper.java

  31 
vote

/** 
 * Validate the specified xml against the schema.
 * @param schema The resource schema for validation.
 * @param xml The XML to validate.
 * @return true if valid, false otherwise.
 */
public static boolean validate(final Schema schema,final String xml){
  final Validator validator=schema.newValidator();
  try {
    validator.validate(new StreamSource(new StringReader(xml)));
    return true;
  }
 catch (  final IOException ioe) {
    LOGGER.debug(ioe.getMessage(),ioe);
  }
catch (  final SAXException saxe) {
    LOGGER.debug(saxe.getMessage(),saxe);
  }
  return false;
}
 

Example 26

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

Source file: TestPipe.java

  31 
vote

public void testTidyAndXsl() throws Exception {
  InputStream res=resourceStream("rss-in.xhtml");
  assertTrue("Empty input file",res.available() > 0);
  String OUTPUT_FILENAME=resourceURL("rss-out.xml").getPath();
  OutputStream outputFileOutputStream=new FileOutputStream(OUTPUT_FILENAME);
  TRAXTransformer traxTransformer=traxTemplates.newTransformer();
  htmlTransformer.initResult(traxTransformer.getTransformerAsResult());
  traxTransformer.initResult(new StreamResult(outputFileOutputStream));
  htmlTransformer.transform(new StreamSource(res));
  res.close();
  FileInputStream outputFileInputStream=new FileInputStream(OUTPUT_FILENAME);
  assertTrue("Output is empty",outputFileInputStream.available() > 0);
  outputFileInputStream.close();
}
 

Example 27

From project Cours-3eme-ann-e, under directory /XML/XSLT-examples/XSLT1/.

Source file: XSLT1.java

  31 
vote

public static void main(String[] args) throws IOException, TransformerException {
  File stylesheet=new File("../../exemples/XSLT/ex8.xslt");
  File srcFile=new File("../../exemples/XSLT/library.xml");
  java.io.Writer destFile=new OutputStreamWriter(System.out,"ISO-8859-1");
  TransformerFactory factory=TransformerFactory.newInstance();
  Source xslt=new StreamSource(stylesheet);
  Transformer transformer=factory.newTransformer(xslt);
  Source request=new StreamSource(srcFile);
  Result response=new StreamResult(destFile);
  transformer.transform(request,response);
}
 

Example 28

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

Source file: XSDChecker.java

  31 
vote

public static boolean validateFile(final String filePath) throws SAXException, IOException {
  SchemaFactory factory=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  Schema schema=factory.newSchema(new StreamSource(XSDChecker.class.getResourceAsStream("dad.xsd")));
  Validator validator=schema.newValidator();
  Source source=new StreamSource(filePath);
  validator.validate(source);
  return true;
}
 

Example 29

From project dcm4che, under directory /dcm4che-tool/dcm4che-tool-dcm2xml/src/main/java/org/dcm4che/tool/dcm2xml/.

Source file: Dcm2Xml.java

  31 
vote

private TransformerHandler getTransformerHandler() throws TransformerConfigurationException, IOException {
  SAXTransformerFactory tf=(SAXTransformerFactory)TransformerFactory.newInstance();
  if (xslt == null)   return tf.newTransformerHandler();
  TransformerHandler th=tf.newTransformerHandler(new StreamSource(xslt.openStream(),xslt.toExternalForm()));
  return th;
}
 

Example 30

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

Source file: XsltTransformer.java

  31 
vote

/** 
 * Simple transformation method. 
 * @param sourcePath - Absolute path to source xml file. 
 * @param xsltPath - Absolute path to xslt file. 
 * @param resultDir - Directory where you want to put resulting files. 
 * @param parameters - Map defining global XSLT parameters based via tranformer to the XSLT file. 
 * @throws TransformerException 
 */
public static void simpleTransform(final String sourcePath,final String xsltPath,final String resultDir,final Map<String,String> parameters) throws TransformerException {
  final TransformerFactory tFactory=TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",null);
  final Transformer transformer=tFactory.newTransformer(new StreamSource(new File(xsltPath)));
  applyParameters(transformer,parameters);
  transformer.transform(new StreamSource(new File(sourcePath)),new StreamResult(new File(resultDir)));
}
 

Example 31

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

Source file: Utilities.java

  31 
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 32

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-scaffolderproxy/src/main/java/org/easysoa/scaffolding/.

Source file: XsltFormGenerator.java

  31 
vote

public String generateHtmlFormFromWsdl(String wsdlXmlSource,String formWsdlXmlSource,String xsltSource,String htmlOutput){
  logger.debug("wsdlXmlSource : " + wsdlXmlSource);
  logger.debug("formWsdlXmlSource : " + formWsdlXmlSource);
  logger.debug("xsltSource : " + xsltSource);
  logger.debug("htmlOutput : " + htmlOutput);
  logger.debug("defautWsdl : " + defaultWsdl);
  try {
    if (formWsdlXmlSource == null || "".equals(formWsdlXmlSource)) {
      formWsdlXmlSource=wsdlXmlSource;
    }
    if (xsltSource == null || "".equals(xsltSource)) {
      throw new IllegalArgumentException("The parameter xsltSource cannot be null or empty !");
    }
 else     if (htmlOutput == null || "".equals(htmlOutput)) {
      throw new IllegalArgumentException("The parameter html cannot be null or empty !");
    }
    if (formWsdlXmlSource == null || "".equals(formWsdlXmlSource)) {
      formWsdlXmlSource=defaultWsdl;
    }
    URL formWsdlXmlUrl=ProxyUtil.getUrlOrFile(formWsdlXmlSource);
    SAXSource source=new SAXSource(new InputSource(new InputStreamReader(formWsdlXmlUrl.openStream())));
    File htmlOutputFile=new File(htmlOutput);
    Result result=new StreamResult(htmlOutputFile);
    TransformerFactory tFactory=TransformerFactory.newInstance();
    StreamSource xsltSourceStream=new StreamSource(new File(xsltSource));
    Transformer transformer=tFactory.newTransformer(xsltSourceStream);
    transformer.setParameter("wsdlUrl",wsdlXmlSource);
    transformer.transform(source,result);
    return readResultFile(htmlOutputFile);
  }
 catch (  Exception ex) {
    String msg="Transformation failed";
    logger.error(msg,ex);
    return msg + " : " + ex.getMessage();
  }
}
 

Example 33

From project freemind, under directory /freemind/accessories/plugins/.

Source file: ExportWithXSLT.java

  31 
vote

/** 
 * @throws IOException
 */
private boolean transformMapWithXslt(String xsltFileName,File saveFile,String areaCode) throws IOException {
  StringWriter writer=getMapXml();
  StringReader reader=new StringReader(writer.getBuffer().toString());
  URL xsltUrl=getResource(xsltFileName);
  if (xsltUrl == null) {
    logger.severe("Can't find " + xsltFileName + " as resource.");
    throw new IllegalArgumentException("Can't find " + xsltFileName + " as resource.");
  }
  InputStream xsltFile=xsltUrl.openStream();
  return transform(new StreamSource(reader),xsltFile,saveFile,areaCode);
}
 

Example 34

From project gedcomx, under directory /gedcomx-rt-support/src/main/java/org/gedcomx/rt/.

Source file: SerializationUtil.java

  31 
vote

@SuppressWarnings({"unchecked"}) public static <C>C processThroughXml(Object reference,Class<? extends C> instanceClass,JAXBContext context,SerializationProcessListener... listeners) throws JAXBException, UnsupportedEncodingException {
  byte[] out=toXmlStream(reference,instanceClass,context,listeners);
  JAXBElement<? extends C> element=context.createUnmarshaller().unmarshal(new StreamSource(new ByteArrayInputStream(out)),instanceClass);
  reference=element.getValue();
  return (C)reference;
}
 

Example 35

From project GenericKnimeNodes, under directory /com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/config/.

Source file: CTDNodeConfigurationReader.java

  31 
vote

/** 
 * Initializes a SAXReader with the Param and CTD schema.
 * @return A fully configured {@link SAXReader}.
 * @throws SAXException See  {@link SAXReader} documentation.
 * @throws ParserConfigurationException See  {@link SAXReader} documentation.
 */
private SAXReader initializeSAXReader() throws SAXException, ParserConfigurationException {
  SAXParserFactory factory=SAXParserFactory.newInstance();
  SchemaFactory schemaFactory=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  factory.setSchema(schemaFactory.newSchema(new Source[]{new StreamSource(SchemaProvider.class.getResourceAsStream("CTD.xsd")),new StreamSource(SchemaProvider.class.getResourceAsStream("Param_1_3.xsd"))}));
  SAXParser parser=factory.newSAXParser();
  SAXReader reader=new SAXReader(parser.getXMLReader());
  reader.setValidation(false);
  return reader;
}
 

Example 36

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

Source file: StatisticsManager.java

  31 
vote

public void setReportTemplate(InputStream inputStream){
  log.info("Setting template to '" + inputStream + "'");
  try {
    styleTemplate=TransformerFactory.newInstance().newTemplates(new StreamSource(inputStream)).newTransformer();
  }
 catch (  TransformerConfigurationException e) {
    throw new RuntimeException("A serious configuration exception detected in '" + inputStream + "' while creating report template.",e);
  }
catch (  TransformerFactoryConfigurationError e) {
    throw new RuntimeException("A serious configuration error detected in '" + inputStream + "' while creating report template.",e);
  }
}
 

Example 37

From project gxa, under directory /atlas-index-api/src/test/java/uk/ac/ebi/gxa/index/.

Source file: MockIndexLoader.java

  31 
vote

private static void loadSolrDump(CoreContainer container,String core,String dump) throws SolrServerException, IOException, TransformerException {
  SolrServer solr=new EmbeddedSolrServer(container,core);
  Source source=new StreamSource(MockIndexLoader.class.getClassLoader().getResourceAsStream("META-INF/" + dump));
  Source xslt=new StreamSource(MockIndexLoader.class.getClassLoader().getResourceAsStream("META-INF/dumpconverter.xslt"));
  StringWriter sw=new StringWriter();
  Result result=new StreamResult(sw);
  TransformerFactory transfactory=TransformerFactory.newInstance();
  Transformer transformer=transfactory.newTransformer(xslt);
  transformer.transform(source,result);
  DirectXmlRequest request=new DirectXmlRequest("/update",sw.toString());
  solr.request(request);
  solr.optimize();
  solr.commit();
}
 

Example 38

From project harmony, under directory /harmony.common.serviceinterface/src/main/java/org/opennaas/extensions/idb/serviceinterface/databinding/validator/.

Source file: SyntaxValidator.java

  31 
vote

/** 
 * Validates the xml string against a given scheme.
 * @param xml XML-Stringl
 * @throws InvalidRequestFaultException Error while parsing
 * @throws UnexpectedFaultException
 * @throws IOException A IOException
 */
public final void validate(final String xml) throws InvalidRequestFaultException, UnexpectedFaultException {
  final StringReader is=new StringReader(xml);
  final Source source=new StreamSource(is);
  try {
    this.validator.validate(source);
  }
 catch (  final SAXException e) {
    this.logger.debug(e.getMessage() + ":\n" + xml);
    throw new InvalidRequestFaultException(e);
  }
catch (  final IOException e) {
    throw new UnexpectedFaultException("Error during validation: " + e.getMessage());
  }
}
 

Example 39

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

Source file: SOAPresults.java

  31 
vote

private String useXslt(String xml,String xsltPath) throws TransformerException {
  InputStream soapStream=new ByteArrayInputStream(xml.getBytes());
  System.getProperty("javax.xml.parsers.DocumentBuilderFactory","net.sf.saxon.TransformerFactoryImpl");
  Source xmlSource=new StreamSource(soapStream);
  URL urlxsl=getClass().getResource(xsltPath);
  File xsltFile=new File(urlxsl.getFile());
  Source xsltSource=new StreamSource(xsltFile);
  TransformerFactory transFact=TransformerFactory.newInstance();
  Transformer trans=transFact.newTransformer(xsltSource);
  ByteArrayOutputStream htmlOut=new ByteArrayOutputStream();
  Result res=new StreamResult(htmlOut);
  trans.transform(xmlSource,res);
  return htmlOut.toString();
}
 

Example 40

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

Source file: HrestsImporter.java

  31 
vote

public HrestsImporter(ImporterConfig config,String xsltPath) throws RepositoryException, TransformerConfigurationException {
  super(config);
  parser=new Tidy();
  xsltFile=new File(xsltPath);
  TransformerFactory xformFactory=TransformerFactory.newInstance();
  transformer=xformFactory.newTransformer(new StreamSource(this.xsltFile));
}
 

Example 41

From project Ivory, under directory /oozie/src/test/java/org/apache/ivory/oozie/bundle/.

Source file: BundleUnmarshallingTest.java

  31 
vote

@Test public void testValidBundleUnamrashalling() throws Exception {
  Unmarshaller unmarshaller=JAXBContext.newInstance(org.apache.ivory.oozie.bundle.BUNDLEAPP.class).createUnmarshaller();
  SchemaFactory schemaFactory=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  Schema schema=schemaFactory.newSchema(this.getClass().getResource("/oozie-bundle-0.1.xsd"));
  unmarshaller.setSchema(schema);
  Object bundle=unmarshaller.unmarshal(new StreamSource(BundleUnmarshallingTest.class.getResourceAsStream("/oozie/xmls/bundle.xml")),BUNDLEAPP.class);
  BUNDLEAPP bundleApp=((JAXBElement<BUNDLEAPP>)bundle).getValue();
  Assert.assertEquals(bundleApp.getName(),"bundle-app");
  Assert.assertEquals(bundleApp.getCoordinator().get(0).getName(),"coord-1");
}
 

Example 42

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

Source file: Renderer.java

  31 
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 43

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

Source file: JbpmMigration.java

  31 
vote

/** 
 * Perform the transformation called from the main method.
 * @param xmlFileName The name of an XML input file.
 * @param xsltFileName The name of an XSLT stylesheet.
 * @param outputFileName The name of the file the result of the transformation is to be written to.
 */
private static void transform(final String xmlFileName,final String xsltFileName,final String outputFileName){
  Source xsltSource=null;
  if (StringUtils.isNotBlank(xsltFileName)) {
    xsltSource=new StreamSource(new File(xsltFileName));
  }
 else {
    xsltSource=new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_XSLT_SHEET));
  }
  final Source xmlSource=new StreamSource(new File(xmlFileName));
  final Result xmlResult=new StreamResult(new File(outputFileName));
  XmlUtils.transform(xmlSource,xsltSource,xmlResult);
}
 

Example 44

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

Source file: SpecdoxTransformer.java

  31 
vote

public void transform(String filename,String specXmlDir,String outputDir,File xref) throws TransformerException {
  Source xmlSource=new StreamSource(new StringReader("<?xml version=\"1.0\" ?><foo></foo>"));
  Source xsltSource=new StreamSource(Specdox.class.getResourceAsStream("/specdox.xsl"));
  xsltSource.setSystemId("/specdox.xsl");
  TransformerFactory transFact=new TransformerFactoryImpl();
  Transformer trans=transFact.newTransformer(xsltSource);
  trans.setParameter("spec-file-dir",specXmlDir);
  trans.setParameter("xref",xref.getName());
  trans.setParameter("output-dir",outputDir);
  trans.setParameter("frameset-index-filename",filename);
  trans.transform(xmlSource,new StreamResult(System.out));
}
 

Example 45

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 46

From project jentrata-msh, under directory /Plugins/CorvusEbMS/src/main/java/hk/hku/cecid/ebms/spa/handler/.

Source file: ValidationComponent.java

  31 
vote

public void validate(AttachmentPart attachment) throws SOAPException {
  try {
    Validator validator=xsdScheme.newValidator();
    Source source=new StreamSource(attachment.getRawContent());
    validator.validate(source);
  }
 catch (  SAXException e) {
    throw new InvalidAttachmentException(e);
  }
catch (  IOException e) {
    EbmsProcessor.core.log.error(e);
  }
}
 

Example 47

From project jPOS, under directory /jpos/src/main/java/org/jpos/iso/filter/.

Source file: XSLTFilter.java

  31 
vote

/** 
 * @param xsltfile XSL Transformation file
 * @param reread true if you want XSLT file re-read from disk
 * @throws ISOException
 */
public XSLTFilter(String xsltfile,boolean reread) throws ISOException {
  this();
  try {
    this.xsltfile=xsltfile;
    this.reread=reread;
    this.transformer=tfactory.newTransformer(new StreamSource(xsltfile));
  }
 catch (  TransformerConfigurationException e) {
    throw new ISOException(e);
  }
}
 

Example 48

From project karaf, under directory /features/core/src/main/java/org/apache/karaf/features/internal/.

Source file: FeatureValidationUtil.java

  31 
vote

private static void validate(Document doc,String schemaLocation) throws SAXException {
  SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Schema schema=factory.newSchema(new StreamSource(FeatureValidationUtil.class.getResourceAsStream(schemaLocation)));
  Validator validator=schema.newValidator();
  try {
    validator.validate(new DOMSource(doc));
  }
 catch (  Exception e) {
    throw new IllegalArgumentException("Unable to validate " + doc.getDocumentURI(),e);
  }
}
 

Example 49

From project knicker, under directory /src/main/java/net/jeremybrooks/knicker/.

Source file: Util.java

  31 
vote

/** 
 * Call the URI using an HTTP GET request, returning the response as an xml Document instance. <p/> This method accepts an AuthenticationToken, and will set the request header parameter 'auth_token' with the token. If the token is null, the header parameter will not be set.
 * @param uri   the URI to call.
 * @param token the authentication token.
 * @return server response as a Document instance, or null if the serverdid not return anything.
 * @throws KnickerException if the uri is invalid, or if there are any errors.
 */
static Document doGet(String uri,AuthenticationToken token) throws KnickerException {
  if (uri == null || uri.trim().isEmpty()) {
    throw new KnickerException("Parameter uri cannot be null or empty.");
  }
  if (!uri.startsWith("http://") && !uri.startsWith("https://")) {
    throw new KnickerException("Parameter uri must start with http:// or https://");
  }
  KnickerLogger.getLogger().log("GET URL: '" + uri + "'");
  CharArrayWriter writer;
  try {
    URL url=parseUrl(uri);
    URLConnection conn=url.openConnection();
    conn.setConnectTimeout(getConnTimeout());
    conn.setReadTimeout(getReadTimeout());
    conn.addRequestProperty("api_key",System.getProperty("WORDNIK_API_KEY"));
    if (token != null) {
      conn.addRequestProperty("auth_token",token.getToken());
    }
    StreamSource streamSource=new StreamSource(conn.getInputStream());
    writer=new CharArrayWriter();
    StreamResult streamResult=new StreamResult(writer);
    TransformerFactory factory=TransformerFactory.newInstance();
    Transformer transformer=factory.newTransformer();
    transformer.transform(streamSource,streamResult);
    KnickerLogger.getLogger().log("----------RESPONSE START----------");
    KnickerLogger.getLogger().log(writer.toString());
    KnickerLogger.getLogger().log("----------RESPONSE END----------");
  }
 catch (  Exception e) {
    throw new KnickerException("Error getting a response from the server.",e);
  }
  return getDocument(writer.toString());
}
 

Example 50

From project lenya, under directory /org.apache.lenya.module.editors/src/main/java/org/apache/lenya/cms/editors/forms/.

Source file: OneFormEditor.java

  31 
vote

protected void validate(String xmlString,String encoding) throws Exception {
  ResourceType resourceType=getSourceDocument().getResourceType();
  Schema schema=resourceType.getSchema();
  if (schema == null) {
    getLogger().info("No schema declared for resource type [" + resourceType.getName() + "], skipping validation.");
  }
 else {
    deleteParameter(PARAM_VALIDATION_ERRORS);
    byte bytes[]=xmlString.getBytes(encoding);
    ByteArrayInputStream stream=new ByteArrayInputStream(bytes);
    StreamSource source=new StreamSource(stream);
    ValidationUtil.validate(source,schema,this);
    if (!getValidationErrors().isEmpty()) {
      addErrorMessage("editors.validationFailed");
    }
  }
}
 

Example 51

From project Lily, under directory /cr/indexer/engine/src/test/resources/org/lilyproject/indexer/engine/test/.

Source file: SchemaTest.java

  31 
vote

@Test public void test() throws Exception {
  SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  URL url=getClass().getClassLoader().getResource("org/lilyproject/indexer/conf/indexerconf.xsd");
  Schema schema=factory.newSchema(url);
  Validator validator=schema.newValidator();
  InputStream is=getClass().getClassLoader().getResourceAsStream("org/lilyproject/indexer/test/indexerconf1.xml");
  validator.validate(new StreamSource(is));
}
 

Example 52

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/restful_dispatch/src/main/java/demo/restful/client/.

Source file: Client.java

  31 
vote

public static void main(String args[]) throws Exception {
  QName serviceName=new QName("http://apache.org/hello_world_xml_http/wrapped","cutomerservice");
  QName portName=new QName("http://apache.org/hello_world_xml_http/wrapped","RestProviderPort");
  String endpointAddress="http://localhost:9000/customerservice/customer";
  URL url=new URL(endpointAddress);
  System.out.println("Invoking server through HTTP GET to query all customer info");
  InputStream in=url.openStream();
  StreamSource source=new StreamSource(in);
  printSource(source);
  url=new URL(endpointAddress + "?id=1234");
  System.out.println("Invoking server through HTTP GET to query customer info");
  in=url.openStream();
  source=new StreamSource(in);
  printSource(source);
  URI endpointURI=new URI(endpointAddress.toString());
  String path=null;
  if (endpointURI != null) {
    path=endpointURI.getPath();
  }
  Service service=Service.create(serviceName);
  service.addPort(portName,HTTPBinding.HTTP_BINDING,endpointAddress);
  Dispatch<DOMSource> dispatcher=service.createDispatch(portName,DOMSource.class,Service.Mode.PAYLOAD);
  Map<String,Object> requestContext=dispatcher.getRequestContext();
  Client client=new Client();
  InputStream is=client.getClass().getResourceAsStream("CustomerJohnReq.xml");
  Document doc=XMLUtils.parse(is);
  DOMSource reqMsg=new DOMSource(doc);
  requestContext.put(MessageContext.HTTP_REQUEST_METHOD,"POST");
  System.out.println("Invoking through HTTP POST to update customer using JAX-WS Dispatch");
  DOMSource result=dispatcher.invoke(reqMsg);
  printSource(result);
  System.out.println("Client Invoking succeeded!");
  System.exit(0);
}
 

Example 53

From project mob, under directory /com.netappsid.mob/src/com/netappsid/mob/ejb3/xml/.

Source file: PersistenceUnitUtils.java

  31 
vote

public Document applyXslt(Document document,URL... xslt) throws IOException, TransformerException {
  Document temp=document;
  for (  URL url : xslt) {
    Transformer transformer=transformerFactory.newTransformer(new StreamSource(url.openStream()));
    DocumentSource source=new DocumentSource(temp);
    DocumentResult result=new DocumentResult();
    transformer.transform(source,result);
    temp=result.getDocument();
  }
  return temp;
}
 

Example 54

From project netty-xmpp, under directory /src/main/java/es/udc/pfc/xmpp/xml/.

Source file: XMLUtil.java

  31 
vote

/** 
 * Parses a String into a new Element.
 * @param element the String to parse
 * @return the parsed Element
 */
public static final Element fromString(final String element){
  try {
    final Document doc=newDocument();
    transformer.transform(new StreamSource(new StringReader(element)),new DOMResult(doc));
    return doc.getDocumentElement();
  }
 catch (  final TransformerException e) {
    throw new InternalError("Transformer error");
  }
}
 

Example 55

From project ODE-X, under directory /runtime/src/main/java/org/apache/ode/runtime/xsl/.

Source file: XSLDataContentHandler.java

  31 
vote

@Override public Object getContent(DataSource dataSource) throws IOException {
  try {
    TransformerFactory xformFactory=TransformerFactory.newInstance();
    Transformer transformer=xformFactory.newTransformer(new StreamSource(dataSource.getInputStream()));
    return transformer;
  }
 catch (  TransformerConfigurationException te) {
    throw new IOException(te);
  }
}
 

Example 56

From project openclaws, under directory /cat/WEB-INF/src/edu/rit/its/claws/cat/translate/.

Source file: XSLTranslator.java

  31 
vote

/** 
 * Creates a new transformer from the given URL
 * @throws TransformerException if the translator can not be loaded
 */
private javax.xml.transform.Transformer load() throws TransformerException {
  javax.xml.transform.Transformer transformer=null;
  try {
    URLConnection uc=url.openConnection();
    uc.setDefaultUseCaches(true);
synchronized (XSLTranslator.transFact) {
      StreamSource s=new StreamSource(uc.getInputStream());
      s.setSystemId(url.toString());
      transformer=XSLTranslator.transFact.newTransformer(s);
    }
    created++;
    lastdate=uc.getLastModified();
    transformer.setOutputProperty("method","xml");
    transformer.setErrorListener(this);
  }
 catch (  TransformerException e) {
    throw new TransformerException("Can't load translator " + url + " "+ e.getMessageAndLocation(),e);
  }
catch (  Exception e) {
    throw new TransformerException("Can't load translator " + url,e);
  }
  return transformer;
}
 

Example 57

From project pegadi, under directory /client/src/main/java/org/pegadi/publisher/.

Source file: StylesheetPublisher.java

  31 
vote

@Override public boolean doPublish(Article article,Stylesheet stylesheet) throws TransformerException, FileNotFoundException {
  setOutputMethod(OutputMethod.text);
  TransformerFactory tFactory=TransformerFactory.newInstance();
  Transformer transformer=tFactory.newTransformer(new StreamSource(getXmlPath() + "/" + stylesheet.getStylesheetURL()));
  transformer.setOutputProperties(getOutputProperties());
  transformer.transform(new DOMSource(article.getDocument()),new StreamResult(new CRLFFilterOutputStream(new FileOutputStream(getFile()),getMode())));
  log.info("Transformation done");
  return true;
}
 

Example 58

From project PID-webservice, under directory /server/src/main/java/org/socialhistoryservices/pid/database/dao/.

Source file: HandleDaoImpl.java

  31 
vote

public HandleDaoImpl(){
  try {
    final InputStream resourceAsStream=this.getClass().getResourceAsStream("/locations.remove.ns.xsl");
    transformer=TransformerFactory.newInstance().newTransformer(new StreamSource(resourceAsStream));
  }
 catch (  TransformerConfigurationException e) {
    e.printStackTrace();
  }
}
 

Example 59

From project preon, under directory /preon-emitter/src/main/java/org/codehaus/preon/emitter/.

Source file: Exporter.java

  31 
vote

private static void saveEmitted(byte[] bytes,File structure){
  ByteArrayInputStream in=new ByteArrayInputStream(bytes);
  OutputStream out=null;
  try {
    out=new FileOutputStream(structure);
    StreamSource xslt=new StreamSource(Exporter.class.getResourceAsStream("/structure-to-html.xsl"));
    Transformer transformer=TransformerFactory.newInstance().newTransformer(xslt);
    transformer.transform(new StreamSource(in),new StreamResult(out));
  }
 catch (  TransformerConfigurationException e) {
    e.printStackTrace();
  }
catch (  TransformerException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(out);
  }
}
 

Example 60

From project qcadoo, under directory /qcadoo-model/src/main/java/com/qcadoo/model/internal/hbmconverter/.

Source file: ModelXmlToHbmConverterImpl.java

  31 
vote

public ModelXmlToHbmConverterImpl(){
  if (!xsl.isReadable()) {
    throw new IllegalStateException("Failed to read " + xsl.getFilename());
  }
  try {
    transformer=TransformerFactory.newInstance().newTransformer(new StreamSource(xsl.getInputStream()));
  }
 catch (  TransformerConfigurationException e) {
    throw new IllegalStateException("Failed to initialize xsl transformer",e);
  }
catch (  IOException e) {
    throw new IllegalStateException("Failed to initialize xsl transformer",e);
  }
}
 

Example 61

From project quickstarts, under directory /bean-service/src/main/java/org/switchyard/quickstarts/bean/service/.

Source file: Transformers.java

  31 
vote

private Element toElement(String xml){
  DOMResult dom=new DOMResult();
  try {
    TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new StringReader(xml)),dom);
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return ((Document)dom.getNode()).getDocumentElement();
}
 

Example 62

From project RegexTagForMusic, under directory /src/org/essembeh/rtfm/core/configuration/io/.

Source file: CoreConfigurationLoaderV1.java

  31 
vote

@Inject public CoreConfigurationLoaderV1(@Named("configuration.core") InputStream source) throws ConfigurationException {
  try {
    JAXBContext context=JAXBContext.newInstance("org.essembeh.rtfm.model.configuration.core.version1");
    Unmarshaller unmarshaller=context.createUnmarshaller();
    unmarshaller.setEventHandler(new DefaultValidationEventHandler());
    JAXBElement<TCoreConfigurationV1> root=unmarshaller.unmarshal(new StreamSource(source),TCoreConfigurationV1.class);
    model=root.getValue();
  }
 catch (  JAXBException e) {
    logger.info("Cannot load core configuration version 1: " + e.getMessage());
    throw new ConfigurationException(e.getMessage());
  }
}
 

Example 63

From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/xml/.

Source file: Processor.java

  30 
vote

public static void main(final String[] args) throws Exception {
  if (args.length < 2) {
    showUsage();
    return;
  }
  int inRepresentation=getRepresentation(args[0]);
  int outRepresentation=getRepresentation(args[1]);
  InputStream is=System.in;
  OutputStream os=new BufferedOutputStream(System.out);
  Source xslt=null;
  for (int i=2; i < args.length; i++) {
    if ("-in".equals(args[i])) {
      is=new FileInputStream(args[++i]);
    }
 else     if ("-out".equals(args[i])) {
      os=new BufferedOutputStream(new FileOutputStream(args[++i]));
    }
 else     if ("-xslt".equals(args[i])) {
      xslt=new StreamSource(new FileInputStream(args[++i]));
    }
 else {
      showUsage();
      return;
    }
  }
  if (inRepresentation == 0 || outRepresentation == 0) {
    showUsage();
    return;
  }
  Processor m=new Processor(inRepresentation,outRepresentation,is,os,xslt);
  long l1=System.currentTimeMillis();
  int n=m.process();
  long l2=System.currentTimeMillis();
  System.err.println(n);
  System.err.println("" + (l2 - l1) + "ms  "+ 1000f * n / (l2 - l1) + " resources/sec");
}
 

Example 64

From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.

Source file: SvgServlet.java

  30 
vote

private byte[] doXsl(byte[] source){
  try {
    ByteArrayOutputStream os=new ByteArrayOutputStream();
    StreamResult result=new StreamResult(os);
    TransformerFactory factory=TransformerFactory.newInstance();
    DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
    Node doc=documentBuilder.parse(new ByteArrayInputStream(source));
    Transformer transformer=factory.newTransformer(new StreamSource(getClass().getResourceAsStream("dataToSvg.xsl")));
    transformer.transform(new DOMSource(doc),result);
    return os.toByteArray();
  }
 catch (  Throwable e) {
    _logger.warn("Unable to do XSL transformation",e);
    return source;
  }
}
 

Example 65

From project cpptasks-parallel, under directory /src/taskdocs/java/net/sf/antcontrib/taskdocs/.

Source file: TaskDoclet.java

  30 
vote

/** 
 * Process Javadoc content.
 * @param root root of javadoc content.
 * @return true if successful
 * @throws Exception IO exceptions and the like.
 */
public static boolean start(RootDoc root) throws Exception {
  SAXTransformerFactory tf=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
  Source typeStyle=new StreamSource(new File("src/taskdocs/resources/net/sf/antcontrib/taskdocs/element.xslt"));
  TransformerHandler typeHandler=tf.newTransformerHandler(typeStyle);
  Map referencedTypes=new HashMap();
  Map documentedTypes=new HashMap();
  ClassDoc[] classes=root.classes();
  for (int i=0; i < classes.length; ++i) {
    ClassDoc clazz=classes[i];
    if (clazz.isPublic() && !clazz.isAbstract()) {
      if (isTask(clazz) || isType(clazz)) {
        writeClass(typeHandler,clazz,referencedTypes);
        documentedTypes.put(clazz.qualifiedTypeName(),clazz);
      }
    }
  }
  Map additionalTypes=new HashMap();
  for (Iterator iter=referencedTypes.keySet().iterator(); iter.hasNext(); ) {
    String referencedName=(String)iter.next();
    if (documentedTypes.get(referencedName) == null) {
      ClassDoc referencedClass=root.classNamed(referencedName);
      if (referencedClass != null) {
        if (!referencedClass.qualifiedTypeName().startsWith("org.apache.tools.ant")) {
          writeClass(typeHandler,referencedClass,additionalTypes);
          documentedTypes.put(referencedClass.qualifiedTypeName(),referencedClass);
        }
      }
    }
  }
  return true;
}
 

Example 66

From project drools-chance, under directory /drools-shapes/drools-shapes-examples/conyard-example/src/test/java/.

Source file: FactTest.java

  30 
vote

@Test @Ignore public void validateXMLWithSchema() throws SAXException {
  StringWriter writer=new StringWriter();
  try {
    marshaller.marshal(painting,writer);
  }
 catch (  JAXBException e) {
    fail(e.getMessage());
  }
  String inXSD="conyard_$impl.xsd";
  String xml=writer.toString();
  System.out.println(xml);
  SchemaFactory factory=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  Source schemaFile=null;
  try {
    schemaFile=new StreamSource(new ClassPathResource(inXSD).getInputStream());
  }
 catch (  IOException e) {
    fail(e.getMessage());
  }
  Schema schema=factory.newSchema(schemaFile);
  Validator validator=schema.newValidator();
  Source source=new StreamSource(new ByteArrayInputStream(xml.getBytes()));
  try {
    validator.validate(source);
  }
 catch (  SAXException ex) {
    fail(ex.getMessage());
  }
catch (  IOException ex) {
    fail(ex.getMessage());
  }
}
 

Example 67

From project droolsjbpm-integration, under directory /drools-pipeline/src/main/java/org/drools/runtime/pipeline/impl/.

Source file: SmooksFromSourceTransformer.java

  30 
vote

public void receive(Object object,PipelineContext context){
  this.smooks.setClassLoader(context.getClassLoader());
  Object result=null;
  try {
    JavaResult javaResult=new JavaResult();
    ExecutionContext executionContext=this.smooks.createExecutionContext();
    Source source=null;
    if (object instanceof Source) {
      source=(Source)object;
    }
 else     if (object instanceof InputStream) {
      source=new StreamSource((InputStream)object);
    }
 else     if (object instanceof Reader) {
      source=new StreamSource((Reader)object);
    }
 else     if (object instanceof Resource) {
      source=new StreamSource(((Resource)object).getReader());
    }
 else     if (object instanceof String) {
      source=new StringSource((String)object);
    }
 else {
      throw new IllegalArgumentException("signal object must be instance of Source, InputStream, Reader, Resource or String");
    }
    this.smooks.filter(source,javaResult,executionContext);
    result=javaResult.getBean(this.configuration.getRootId());
  }
 catch (  Exception e) {
    handleException(this,object,e);
  }
  emit(result,context);
}
 

Example 68

From project enclojure, under directory /org-enclojure-ide/src/main/java/org/enclojure/ide/asm/xml/.

Source file: Processor.java

  30 
vote

public static void main(final String[] args) throws Exception {
  if (args.length < 2) {
    showUsage();
    return;
  }
  int inRepresentation=getRepresentation(args[0]);
  int outRepresentation=getRepresentation(args[1]);
  InputStream is=System.in;
  OutputStream os=new BufferedOutputStream(System.out);
  Source xslt=null;
  for (int i=2; i < args.length; i++) {
    if ("-in".equals(args[i])) {
      is=new FileInputStream(args[++i]);
    }
 else     if ("-out".equals(args[i])) {
      os=new BufferedOutputStream(new FileOutputStream(args[++i]));
    }
 else     if ("-xslt".equals(args[i])) {
      xslt=new StreamSource(new FileInputStream(args[++i]));
    }
 else {
      showUsage();
      return;
    }
  }
  if (inRepresentation == 0 || outRepresentation == 0) {
    showUsage();
    return;
  }
  Processor m=new Processor(inRepresentation,outRepresentation,is,os,xslt);
  long l1=System.currentTimeMillis();
  int n=m.process();
  long l2=System.currentTimeMillis();
  System.err.println(n);
  System.err.println((l2 - l1) + "ms  " + 1000f * n / (l2 - l1) + " resources/sec");
}
 

Example 69

From project entando-core-engine, under directory /src/main/java/com/agiletec/aps/system/common/entity/parse/.

Source file: AbstractAttributeSupportObjectDOM.java

  30 
vote

protected void validate(String xmlText,String definitionPath) throws ApsSystemException {
  SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  InputStream schemaIs=null;
  InputStream xmlIs=null;
  try {
    schemaIs=this.getClass().getResourceAsStream(this.getSchemaFileName());
    Source schemaSource=new StreamSource(schemaIs);
    Schema schema=factory.newSchema(schemaSource);
    Validator validator=schema.newValidator();
    xmlIs=new ByteArrayInputStream(xmlText.getBytes("UTF-8"));
    Source source=new StreamSource(xmlIs);
    validator.validate(source);
    ApsSystemUtils.getLogger().info("Valid definition : " + definitionPath);
  }
 catch (  Throwable t) {
    String message="Error validating definition : " + definitionPath;
    ApsSystemUtils.logThrowable(t,this,"this",message);
    throw new ApsSystemException(message,t);
  }
 finally {
    try {
      if (null != schemaIs)       schemaIs.close();
      if (null != xmlIs)       xmlIs.close();
    }
 catch (    IOException e) {
      ApsSystemUtils.logThrowable(e,this,"this");
    }
  }
}
 

Example 70

From project fits_1, under directory /src/edu/harvard/hul/ois/fits/.

Source file: Fits.java

  30 
vote

public static void outputStandardSchemaXml(FitsOutput fitsOutput,OutputStream out) throws XMLStreamException, IOException {
  XmlContent xml=fitsOutput.getStandardXmlContent();
  XMLOutputFactory xmlOutputFactory=XMLOutputFactory.newInstance();
  Transformer transformer=null;
  TransformerFactory tFactory=TransformerFactory.newInstance();
  String prettyPrintXslt=FITS_XML + "prettyprint.xslt";
  try {
    Templates template=tFactory.newTemplates(new StreamSource(prettyPrintXslt));
    transformer=template.newTransformer();
  }
 catch (  Exception e) {
    transformer=null;
  }
  if (xml != null && transformer != null) {
    xml.setRoot(true);
    ByteArrayOutputStream xmlOutStream=new ByteArrayOutputStream();
    OutputStream xsltOutStream=new ByteArrayOutputStream();
    try {
      XMLStreamWriter sw=xmlOutputFactory.createXMLStreamWriter(xmlOutStream);
      xml.output(sw);
      Source source=new StreamSource(new ByteArrayInputStream(xmlOutStream.toByteArray()));
      Result rstream=new StreamResult(xsltOutStream);
      transformer.transform(source,rstream);
      out.write(xsltOutStream.toString().getBytes("UTF-8"));
      out.flush();
    }
 catch (    Exception e) {
      System.err.println("error converting output to a standard schema format");
    }
 finally {
      xmlOutStream.close();
      xsltOutStream.close();
    }
  }
 else {
    System.err.println("Error: output cannot be converted to a standard schema format for this file");
  }
}
 

Example 71

From project GeoBI, under directory /print/src/main/java/org/mapfish/print/map/renderers/.

Source file: SVGTileRenderer.java

  30 
vote

private TranscoderInput getTranscoderInput(URL url,Transformer transformer,RenderingContext context){
  final float zoomFactor=transformer.getSvgFactor() * context.getStyleFactor();
  if (svgZoomOut != null && zoomFactor != 1.0f) {
    try {
      DOMResult transformedSvg=new DOMResult();
      final TransformerFactory factory=TransformerFactory.newInstance();
      javax.xml.transform.Transformer xslt=factory.newTransformer(new DOMSource(svgZoomOut));
      xslt.setParameter("zoomFactor",zoomFactor);
      final URLConnection urlConnection=url.openConnection();
      if (context.getReferer() != null) {
        urlConnection.setRequestProperty("Referer",context.getReferer());
      }
      final InputStream inputStream=urlConnection.getInputStream();
      Document doc;
      try {
        xslt.transform(new StreamSource(inputStream),transformedSvg);
        doc=(Document)transformedSvg.getNode();
        if (LOGGER.isDebugEnabled()) {
          printDom(doc);
        }
      }
  finally {
        inputStream.close();
      }
      return new TranscoderInput(doc);
    }
 catch (    Exception e) {
      context.addError(e);
      return null;
    }
  }
 else {
    return new TranscoderInput(url.toString());
  }
}
 

Example 72

From project GNDMS, under directory /taskflows/publishing/server/src/de/zib/gndms/taskflows/publishing/server/.

Source file: PublishingTFAction.java

  30 
vote

@Override protected void onInProgress(@NotNull String wid,@NotNull TaskState state,boolean isRestartedTask,boolean altTaskState) throws Exception {
  ensureOrder();
  PublishingOrder order=getOrderBean();
  final Slice slice=this.findSlice(order.getSliceId());
  if (null == slice)   throw new NoSuchResourceException("Could not find slice with id " + order.getSliceId());
{
    Specifier<Void> sliceSpecifier=UriFactory.createSliceSpecifier(getGridConfig().getBaseUrl(),slice.getSubspace().getId(),slice.getKind().getId(),order.getSliceId());
    setSliceSpecifier(sliceSpecifier);
  }
  if (null == slice) {
    throw new IllegalArgumentException("No Slice set in Order!");
  }
  final MapConfig config=new MapConfig(getConfigMapData());
  final String slicePath=slice.getSubspace().getPathForSlice(slice);
  final String oldMetaFile=slicePath + File.separatorChar + order.getMetadataFile();
  final String newMetaFile=slicePath + "." + order.getMetadataFile();
  final String oidPrefix=config.hasOption("oidPrefix") ? config.getOption("oidPrefix") : "";
  final String newOid=oidPrefix + "." + slice.getId()+ "."+ order.getMetadataFile().substring(0,order.getMetadataFile().length() - 4);
  try {
    Source xsltSource=new StreamSource(this.getClass().getResourceAsStream(PublishingTaskFlowMeta.XSLT_FILE));
    Transformer transformer=transformerFactory.newTransformer(xsltSource);
    transformer.setParameter("identifier",newOid);
    transformer.transform(new StreamSource(new FileInputStream(oldMetaFile)),new StreamResult(new FileOutputStream(newMetaFile)));
  }
 catch (  RuntimeException e) {
    transit(TaskState.FAILED);
  }
  slice.setPublished(true);
  updateSlice(slice);
  getSliceProvider().invalidate(slice.getId());
  setProgress(1);
  transitWithPayload(new PublishingTaskFlowResult(),TaskState.FINISHED);
  super.onInProgress(wid,state,isRestartedTask,altTaskState);
}
 

Example 73

From project jAPS2, under directory /src/com/agiletec/aps/system/common/entity/parse/.

Source file: AbstractAttributeSupportObjectDOM.java

  30 
vote

protected void validate(String xmlText,String definitionPath) throws ApsSystemException {
  SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  InputStream schemaIs=null;
  InputStream xmlIs=null;
  try {
    schemaIs=this.getClass().getResourceAsStream(this.getSchemaFileName());
    Source schemaSource=new StreamSource(schemaIs);
    Schema schema=factory.newSchema(schemaSource);
    Validator validator=schema.newValidator();
    xmlIs=new ByteArrayInputStream(xmlText.getBytes("UTF-8"));
    Source source=new StreamSource(xmlIs);
    validator.validate(source);
    ApsSystemUtils.getLogger().info("Valid definition : " + definitionPath);
  }
 catch (  Throwable t) {
    String message="Error validating definition : " + definitionPath;
    ApsSystemUtils.logThrowable(t,this,"this",message);
    throw new ApsSystemException(message,t);
  }
 finally {
    try {
      if (null != schemaIs)       schemaIs.close();
      if (null != xmlIs)       xmlIs.close();
    }
 catch (    IOException e) {
      ApsSystemUtils.logThrowable(e,this,"this");
    }
  }
}
 

Example 74

From project jboss-as-quickstart, under directory /xml-dom4j/src/main/java/org/jboss/as/quickstart/xml/.

Source file: XMLParser.java

  30 
vote

public List<Book> parse(InputStream is) throws Exception {
  StringBuffer xmlFile=new StringBuffer();
  BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
  String line=null;
  while ((line=bufferedReader.readLine()) != null) {
    xmlFile.append(line);
  }
  String xml=xmlFile.toString();
  try {
    URL schema=Resources.getResource("/catalog.xsd");
    Validator validator=SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(schema).newValidator();
    Source source=new StreamSource(new CharArrayReader(xml.toCharArray()));
    validator.validate(source);
  }
 catch (  Exception e) {
    this.errorHolder.addErrorMessage("Validation Error",e);
    return null;
  }
  ByteArrayInputStream bais=new ByteArrayInputStream(xml.getBytes());
  return parseInternal(bais);
}
 

Example 75

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 76

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

Source file: TransformingSAXEventProvider.java

  30 
vote

/** 
 * Compile the XSL or retrieve it from the cache
 * @throws IOException
 */
private TemplateInfo getTemplateInfo() throws TransformerConfigurationException, IOException {
  TemplateInfo tinfo=txers.get(xsluri);
  long modtime=-1;
  if (TransformingSAXEventProvider.developmentMode) {
    if (tinfo != null) {
      modtime=NetUtil.getLastModified(xsluri);
      if (modtime > tinfo.getModtime()) {
        txers.remove(xsluri);
        tinfo=null;
        log.debug("updated style, re-caching. xsl=" + xsluri);
      }
    }
  }
  if (tinfo == null) {
    log.debug("generating templates for " + xsluri);
    InputStream xslStream=null;
    try {
      xslStream=NetUtil.getInputStream(xsluri);
      if (transfact == null) {
        transfact=TransformerFactory.newInstance();
      }
      Templates templates=transfact.newTemplates(new StreamSource(xslStream));
      if (modtime == -1) {
        modtime=NetUtil.getLastModified(xsluri);
      }
      tinfo=new TemplateInfo(templates,modtime);
      txers.put(xsluri,tinfo);
    }
  finally {
      IOUtil.close(xslStream);
    }
  }
  return tinfo;
}
 

Example 77

From project Kayak, under directory /Kayak-kcd/src/main/java/com/github/kayak/canio/kcd/loader/.

Source file: KCDLoader.java

  30 
vote

public KCDLoader(){
  SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  InputStream resourceAsStream=KCDLoader.class.getResourceAsStream("Definition.xsd");
  Source s=new StreamSource(resourceAsStream);
  try {
    schema=schemaFactory.newSchema(s);
  }
 catch (  SAXException ex) {
    logger.log(Level.SEVERE,"Could not load schema: ",ex);
  }
  try {
    context=JAXBContext.newInstance(new Class[]{com.github.kayak.canio.kcd.NetworkDefinition.class});
  }
 catch (  JAXBException ex) {
    logger.log(Level.SEVERE,"Could not create JAXB context: ",ex);
  }
}
 

Example 78

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

Source file: ConfigurationFlowTest.java

  30 
vote

/** 
 * Tests the flow 
 */
@Test public void testFlow(){
  final Source xsltSource=new StreamSource(getClass().getClassLoader().getResourceAsStream("com/zaubersoftware/leviathan/api/engine/stylesheet/html.xsl"));
  final Action<Link,String> action=new Action<Link,String>(){
    @Override public String execute(    final Link t){
      return t.getTitle();
    }
  }
;
  final Closure<String> assertClosure=new Closure<String>(){
    @Override public void execute(    final String input){
      assertEquals("MercadoLibre Argentina - Donde comprar y vender de todo.",input);
    }
  }
;
  final Collection<Pipe<?,?>> pipes=Arrays.asList(new Pipe<?,?>[]{new HTMLSanitizerPipe(),new XMLPipe(xsltSource),new ToJavaObjectPipe<Link>(Link.class),new ActionPipe<Link,String>(action),new ClosureAdapterPipe<String>(assertClosure)});
  doFetch(pipes);
}
 

Example 79

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

Source file: CustomXPathTest.java

  30 
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 80

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

Source file: CustomXPathTest.java

  30 
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 81

From project maven-doxia, under directory /doxia-modules/doxia-module-fo/src/main/java/org/apache/maven/doxia/module/fo/.

Source file: FoUtils.java

  30 
vote

/** 
 * Converts an FO file to a PDF file using FOP.
 * @param fo the FO file, not null.
 * @param pdf the target PDF file, not null.
 * @param resourceDir The base directory for relative path resolution, could be null.If null, defaults to the parent directory of fo.
 * @param foUserAgent the FOUserAgent to use.May be null, in which case a default user agent will be used.
 * @throws javax.xml.transform.TransformerException In case of a conversion problem.
 * @since 1.1.1
 */
public static void convertFO2PDF(File fo,File pdf,String resourceDir,FOUserAgent foUserAgent) throws TransformerException {
  FOUserAgent userAgent=(foUserAgent == null ? getDefaultUserAgent(fo,resourceDir) : foUserAgent);
  OutputStream out=null;
  try {
    try {
      out=new BufferedOutputStream(new FileOutputStream(pdf));
    }
 catch (    IOException e) {
      throw new TransformerException(e);
    }
    Result res=null;
    try {
      Fop fop=FOP_FACTORY.newFop(MimeConstants.MIME_PDF,userAgent,out);
      res=new SAXResult(fop.getDefaultHandler());
    }
 catch (    FOPException e) {
      throw new TransformerException(e);
    }
    Transformer transformer=null;
    try {
      transformer=TRANSFORMER_FACTORY.newTransformer();
    }
 catch (    TransformerConfigurationException e) {
      throw new TransformerException(e);
    }
    transformer.transform(new StreamSource(fo),res);
  }
  finally {
    IOUtil.close(out);
  }
}
 

Example 82

From project mobilis, under directory /MobilisServer/src/de/tudresden/inf/rn/mobilis/server/deployment/helper/.

Source file: MSDLValidator.java

  30 
vote

/** 
 * Validate a msdl against the schema.
 * @param inMsdlStream the msdl as input stream
 * @param inMsdlSchemaStream the schema as input stream
 * @return true, if msdl is valid
 */
public boolean validateSchema(InputStream inMsdlStream,InputStream inMsdlSchemaStream){
  boolean isValid=false;
  try {
    SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema=schemaFactory.newSchema(new StreamSource(inMsdlSchemaStream));
    Validator validator=schema.newValidator();
    validator.validate(new StreamSource(inMsdlStream));
    isValid=true;
  }
 catch (  SAXException ex) {
    _lastValidationErrorMessage=ex.getMessage();
  }
catch (  Exception ex) {
    ex.printStackTrace();
  }
  return isValid;
}
 

Example 83

From project modello, under directory /modello-plugins/modello-plugin-xsd/src/test/java/org/codehaus/modello/plugin/xsd/.

Source file: FeaturesXsdGeneratorTest.java

  30 
vote

public void testXsdGenerator() throws Throwable {
  ModelloCore modello=(ModelloCore)lookup(ModelloCore.ROLE);
  Model model=modello.loadModel(getXmlResourceReader("/features.mdo"));
  Properties parameters=getModelloParameters("1.0.0");
  modello.generate(model,"xsd",parameters);
  SchemaFactory sf=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  Schema schema=sf.newSchema(new StreamSource(new File(getOutputDirectory(),"features-1.0.0.xsd")));
  Validator validator=schema.newValidator();
  try {
    validator.validate(new StreamSource(getClass().getResourceAsStream("/features.xml")));
  }
 catch (  SAXParseException e) {
    throw new ModelloException("line " + e.getLineNumber() + " column "+ e.getColumnNumber(),e);
  }
  try {
    validator.validate(new StreamSource(getClass().getResourceAsStream("/features-invalid.xml")));
    fail("parsing of features-invalid.xml should have failed");
  }
 catch (  SAXParseException e) {
    assertTrue(String.valueOf(e.getMessage()).indexOf("invalidElement") >= 0);
  }
  try {
    validator.validate(new StreamSource(getClass().getResourceAsStream("/features-invalid-transient.xml")));
    fail("XSD did not prohibit appearance of transient fields");
  }
 catch (  SAXParseException e) {
    assertTrue(String.valueOf(e.getMessage()).indexOf("transientString") >= 0);
  }
}
 

Example 84

From project nuxeo-platform-rendering-templates, under directory /src/main/java/org/nuxeo/ecm/platform/template/processors/xslt/.

Source file: XSLTProcessor.java

  30 
vote

@Override public Blob renderTemplate(TemplateBasedDocument templateBasedDocument,String templateName) throws Exception {
  BlobHolder bh=templateBasedDocument.getAdaptedDoc().getAdapter(BlobHolder.class);
  if (bh == null) {
    return null;
  }
  Blob xmlContent=bh.getBlob();
  if (xmlContent == null) {
    return null;
  }
  Blob sourceTemplateBlob=getSourceTemplateBlob(templateBasedDocument,templateName);
  TransformerFactory tFactory=TransformerFactory.newInstance();
  Transformer transformer=tFactory.newTransformer(new StreamSource(sourceTemplateBlob.getStream()));
  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);
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  transformer.transform(new StreamSource(xmlContent.getStream()),new StreamResult(out));
  Blob result=new ByteArrayBlob(out.toByteArray(),"text/xml");
  String targetFileName=FileUtils.getFileNameNoExt(templateBasedDocument.getAdaptedDoc().getTitle());
  result.setFilename(targetFileName + ".html");
  return result;
}
 

Example 85

From project org.openscada.external, under directory /org.openscada.external.jOpenDocument/src/org/jopendocument/util/.

Source file: JDOMUtils.java

  30 
vote

/** 
 * Validate a document using JAXP.
 * @param doc the document to validate
 * @param schemaLanguage the language see {@linkplain SchemaFactory the list}.
 * @param schemaLocation the schema.
 * @return <code>null</code> if <code>doc</code> is valid, a String describing the pb otherwise.
 * @throws SAXException If a SAX error occurs during parsing of schemas.
 * @see SchemaFactory
 */
public static String isValid(final Document doc,final String schemaLanguage,final URL schemaLocation) throws SAXException {
  ByteArrayInputStream ins;
  try {
    ins=new ByteArrayInputStream(output(doc).getBytes("UTF8"));
  }
 catch (  UnsupportedEncodingException e) {
    throw new IllegalStateException("unicode not found ",e);
  }
  final Schema schema=SchemaFactory.newInstance(schemaLanguage).newSchema(schemaLocation);
  try {
    schema.newValidator().validate(new StreamSource(ins));
    return null;
  }
 catch (  Exception e) {
    return ExceptionUtils.getStackTrace(e);
  }
}
 

Example 86

From project pepe, under directory /pepe/src/edu/stanford/pepe/org/objectweb/asm/xml/.

Source file: Processor.java

  30 
vote

public static void main(final String[] args) throws Exception {
  if (args.length < 2) {
    showUsage();
    return;
  }
  int inRepresentation=getRepresentation(args[0]);
  int outRepresentation=getRepresentation(args[1]);
  InputStream is=System.in;
  OutputStream os=new BufferedOutputStream(System.out);
  Source xslt=null;
  for (int i=2; i < args.length; i++) {
    if ("-in".equals(args[i])) {
      is=new FileInputStream(args[++i]);
    }
 else     if ("-out".equals(args[i])) {
      os=new BufferedOutputStream(new FileOutputStream(args[++i]));
    }
 else     if ("-xslt".equals(args[i])) {
      xslt=new StreamSource(new FileInputStream(args[++i]));
    }
 else {
      showUsage();
      return;
    }
  }
  if (inRepresentation == 0 || outRepresentation == 0) {
    showUsage();
    return;
  }
  Processor m=new Processor(inRepresentation,outRepresentation,is,os,xslt);
  long l1=System.currentTimeMillis();
  int n=m.process();
  long l2=System.currentTimeMillis();
  System.err.println(n);
  System.err.println((l2 - l1) + "ms  " + 1000f * n / (l2 - l1) + " resources/sec");
}
 

Example 87

From project processFlowProvision, under directory /osProvision/src/main/java/org/jboss/processFlow/openshift/.

Source file: ShifterProvisioner.java

  30 
vote

private static void validateAccountDetailsXmlFile() throws Exception {
  SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  InputStream xsdStream=null;
  InputStream xmlStream=null;
  try {
    xsdStream=ShifterProvisioner.class.getResourceAsStream(OPENSHIFT_ACCOUNT_DETAILS_SCHEMA_FILE);
    if (xsdStream == null)     throw new RuntimeException("validateAccountDetails() can't find schema: " + OPENSHIFT_ACCOUNT_DETAILS_SCHEMA_FILE);
    Schema schemaObj=schemaFactory.newSchema(new StreamSource(xsdStream));
    File xmlFile=new File(openshiftAccountDetailsFile);
    if (!xmlFile.exists())     throw new RuntimeException("validateAccountDetails() can't find xml file: " + openshiftAccountDetailsFile);
    xmlStream=new FileInputStream(xmlFile);
    Validator v=schemaObj.newValidator();
    v.validate(new StreamSource(xmlStream));
  }
  finally {
    if (xsdStream != null)     xsdStream.close();
    if (xmlStream != null)     xmlStream.close();
  }
}