Java Code Examples for javax.xml.transform.Source

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 Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.

Source file: AlfrescoKickstartServiceImpl.java

  21 
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 2

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

Source file: SuiteCotroller.java

  18 
vote

@RequestMapping(method=RequestMethod.POST,value="/suite") String addSuite(Model model,@RequestBody String body){
  Source source=new StreamSource(new StringReader(body));
  Suite suite=(Suite)jaxb2Mashaller.unmarshal(source);
  suite.setId(1L);
  model.addAttribute(suite);
  return view;
}
 

Example 3

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

Source file: XsltTask.java

  18 
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 4

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

Source file: XMLImporter.java

  18 
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 5

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

Source file: ModsXmlHelper.java

  18 
vote

public static Document transform(Element mods) throws TransformerException {
  Source modsSrc=new JDOMSource(mods);
  JDOMResult dcResult=new JDOMResult();
  Transformer t=null;
  try {
    t=mods2dc.newTransformer();
  }
 catch (  TransformerConfigurationException e) {
    throw new Error("There was a problem configuring the transformer.",e);
  }
  t.transform(modsSrc,dcResult);
  return dcResult.getDocument();
}
 

Example 6

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

Source file: XPathOperation.java

  18 
vote

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

Example 7

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

Source file: CCRV1SchemaValidator.java

  18 
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 8

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

Source file: XMLHelpers.java

  18 
vote

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

Example 9

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

Source file: XSLT1.java

  18 
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 10

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

Source file: XSDChecker.java

  18 
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 11

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

Source file: Utilities.java

  18 
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 12

From project farebot, under directory /src/com/codebutler/farebot/.

Source file: Utils.java

  18 
vote

public static String xmlNodeToString(Node node) throws Exception {
  Source source=new DOMSource(node);
  StringWriter stringWriter=new StringWriter();
  Result result=new StreamResult(stringWriter);
  TransformerFactory factory=TransformerFactory.newInstance();
  Transformer transformer=factory.newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT,"yes");
  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
  transformer.transform(source,result);
  return stringWriter.getBuffer().toString();
}
 

Example 13

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

Source file: XMLTools.java

  18 
vote

/** 
 * Converts an document to a String representation. 
 */
private static String toString(Document doc,Properties format) throws TransformerException {
  Transformer transformer=TransformerFactory.newInstance().newTransformer();
  transformer.setOutputProperties(format);
  StringWriter writer=new StringWriter();
  Source source=new DOMSource(doc);
  Result result=new StreamResult(writer);
  transformer.transform(source,result);
  return writer.toString();
}
 

Example 14

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

Source file: SyntaxValidator.java

  18 
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 15

From project integration-tests, under directory /picketlink-openid-tests/src/test/java/org/picketlink/test/integration/openid/.

Source file: OpenIDConsumerUnitTestCase.java

  18 
vote

protected void write(HtmlPage page) throws Exception {
  Document doc=page;
  Source source=new DOMSource(doc);
  StringWriter sw=new StringWriter();
  Result streamResult=new StreamResult(sw);
  Transformer transformer=TransformerFactory.newInstance().newTransformer();
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
  transformer.setOutputProperty(OutputKeys.INDENT,"no");
  transformer.transform(source,streamResult);
  System.out.println(sw.toString());
}
 

Example 16

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

Source file: SOAPresults.java

  18 
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 17

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

Source file: ProjectConfiguration.java

  18 
vote

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

Example 18

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

Source file: JbpmMigration.java

  18 
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 19

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

Source file: SpecdoxTransformer.java

  18 
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 20

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

Source file: ResolverChain.java

  18 
vote

/** 
 * Here we iterate over all the chained resolvers and delegate to them until we find one which can handle the resolve request (if any). {@inheritDoc}
 */
public Source resolve(String href,String base) throws TransformerException {
  Source result=null;
  for (  URIResolver resolver : resolvers) {
    result=resolver.resolve(href,base);
    if (result != null) {
      break;
    }
  }
  return result;
}
 

Example 21

From project jentrata-msh, under directory /Plugins/Corvus.Admin/src/main/java/hk/hku/cecid/piazza/corvus/admin/listener/.

Source file: AdminPageletAdaptor.java

  18 
vote

/** 
 * Gets the transformation source of the specified menu type.
 * @param request the servlet request.
 * @param type the menu type.
 * @return the transformation source of the specified menu type.
 */
private Source getMenuComponentSource(HttpServletRequest request,String type){
  Source componentSource=(Source)request.getAttribute(ATTR_PREFIX + type);
  if (componentSource == null) {
    Collection tabs=generateMenuComponentSource(request,modules,getModuleId(request),-1,MENU_TYPE_MODULE);
    generateMenuComponentSource(request,tabs,getTabId(request),12,MENU_TYPE_TAB);
    componentSource=(Source)request.getAttribute(ATTR_PREFIX + type);
  }
  return componentSource;
}
 

Example 22

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

Source file: Util.java

  18 
vote

/** 
 * Transform an  {@link Element} into a <code>String</code>.
 */
static final String toString(Element element){
  try {
    ByteArrayOutputStream out=new ByteArrayOutputStream();
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
    Source source=new DOMSource(element);
    Result target=new StreamResult(out);
    transformer.transform(source,target);
    return out.toString();
  }
 catch (  Exception e) {
    return "[ ERROR IN toString() : " + e.getMessage() + " ]";
  }
}
 

Example 23

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

Source file: TransformingSAXEventProvider.java

  18 
vote

public void provideSAXEvents(ContentHandler handler) throws SAXException {
  try {
    Source xmlSource=new SAXSource(new SAXEventProviderXMLReader(xmlsep),new SAXEventProviderInputSource());
    SAXResult outputTarget=new SAXResult(handler);
    transform(xmlSource,outputTarget);
  }
 catch (  TransformerException ex) {
    throw new SAXException(ex);
  }
}
 

Example 24

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/plugin/saml/.

Source file: SamlHTTPClient.java

  18 
vote

private String outputDocument(Document document) throws TransformerConfigurationException, TransformerException {
  ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  Result result=new StreamResult(outputStream);
  Transformer xformer=TransformerFactory.newInstance().newTransformer();
  Source source=new DOMSource(document);
  xformer.transform(source,result);
  String encodedChangedSamlResponse=Base64.encode(outputStream.toByteArray());
  return Encoding.urlEncode(encodedChangedSamlResponse);
}
 

Example 25

From project picketlink-idm, under directory /picketlink-idm-testsuite/common/src/test/java/org/picketlink/idm/test/support/.

Source file: XMLTools.java

  18 
vote

/** 
 * Converts an document to a String representation. 
 */
private static String toString(Document doc,Properties format) throws TransformerException {
  Transformer transformer=transformerFactory.newTransformer();
  transformer.setOutputProperties(format);
  StringWriter writer=new StringWriter();
  Source source=new DOMSource(doc);
  Result result=new StreamResult(writer);
  transformer.transform(source,result);
  return writer.toString();
}
 

Example 26

From project replication-benchmarker, under directory /src/main/java/jbenchmarker/trace/.

Source file: Trace2XML.java

  18 
vote

/** 
 * @param args
 */
public static void transformerXml(Document document,String fichier) throws TransformerConfigurationException, TransformerException {
  Source source=new DOMSource(document);
  File file=new File(fichier);
  Result resultat=new StreamResult(fichier);
  TransformerFactory fabrique=TransformerFactory.newInstance();
  Transformer transformer=fabrique.newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT,"yes");
  transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
  transformer.transform(source,resultat);
}
 

Example 27

From project repose, under directory /project-set/components/translation/src/main/java/com/rackspace/papi/components/translation/resolvers/.

Source file: SourceUriResolverChain.java

  18 
vote

@Override public Source resolve(String href,String base) throws TransformerException {
  for (  URIResolver resolver : resolvers) {
    Source source=resolver.resolve(href,base);
    if (source != null) {
      return source;
    }
  }
  return super.resolve(href,base);
}
 

Example 28

From project riftsaw-ode, under directory /bpel-runtime/src/test/java/org/apache/ode/bpel/elang/.

Source file: URIResolverTest.java

  18 
vote

@Test public void testResolveExistingFile() throws Exception {
  OXPath10Expression expr=new OXPath10Expression(null,null,null,null);
  URI baseResourceURI=getClass().getResource("/xpath20/").toURI();
  XslRuntimeUriResolver resolver=new XslRuntimeUriResolver(expr,baseResourceURI);
  Source source=resolver.resolve("variables.xml",null);
  Document doc=DOMUtils.sourceToDOM(source);
  assertThat(DOMUtils.domToString(doc),containsString("<variables>"));
}
 

Example 29

From project scoutdoc, under directory /main/src/scoutdoc/main/fetch/.

Source file: ScoutDocFetch.java

  18 
vote

public static String prettyFormat(String input) throws TransformerException {
  Source xmlInput=new StreamSource(new StringReader(input));
  StringWriter stringWriter=new StringWriter();
  StreamResult xmlOutput=new StreamResult(stringWriter);
  TransformerFactory transformerFactory=TransformerFactory.newInstance();
  transformerFactory.setAttribute("indent-number",2);
  Transformer transformer=transformerFactory.newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT,"yes");
  transformer.transform(xmlInput,xmlOutput);
  return xmlOutput.getWriter().toString();
}
 

Example 30

From project scufl2, under directory /scufl2-t2flow/src/main/java/uk/org/taverna/scufl2/translator/t2flow/defaultactivities/.

Source file: AbstractActivityParser.java

  18 
vote

public <ConfigType>ConfigType unmarshallXml(T2FlowParser t2FlowParser,String xml,Class<ConfigType> configType) throws ReaderException {
  Unmarshaller unmarshaller2=t2FlowParser.getUnmarshaller();
  unmarshaller2.setSchema(null);
  JAXBElement<ConfigType> configElemElem;
  Source source=new StreamSource(new StringReader(xml));
  try {
    configElemElem=unmarshaller2.unmarshal(source,configType);
  }
 catch (  JAXBException e) {
    throw new ReaderException("Can't parse xml " + xml,e);
  }
  return configElemElem.getValue();
}
 

Example 31

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

Source file: Processor.java

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

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

Source file: ExchangeCalendarAdapterTest.java

  17 
vote

@Before public void setUp() throws IOException {
  MockitoAnnotations.initMocks(this);
  sampleExchangeResponse=applicationContext.getResource("classpath:/sampleExchangeResponse.xml");
  adapter.setWebServiceOperations(webService);
  adapter.setCache(cache);
  when(keyGenerator.getKey(any(CalendarConfiguration.class),any(Interval.class),any(PortletRequest.class),anyString())).thenReturn("key");
  adapter.setCacheKeyGenerator(keyGenerator);
  adapter.setEmailAttribute("email");
  when(request.getAttribute(PortletRequest.USER_INFO)).thenReturn(Collections.singletonMap("email",emailAddress));
  DateTime start=new DateTime(2010,10,1,0,0,DateTimeZone.UTC);
  interval=new Interval(start,start.plusMonths(1));
  Source source=new StreamSource(sampleExchangeResponse.getInputStream());
  GetUserAvailabilityResponse response=(GetUserAvailabilityResponse)marshaller.unmarshal(source);
  when(webService.marshalSendAndReceive(any(),any(WebServiceMessageCallback.class))).thenReturn(response);
}
 

Example 33

From project cidb, under directory /ncbieutils-access-service/src/main/java/edu/toronto/cs/cidb/ncbieutils/.

Source file: NCBIEUtilsAccessService.java

  17 
vote

protected String getSummariesXML(List<String> idList){
  String queryList=getSerializedList(idList);
  String url=composeURL(TERM_SUMMARY_QUERY_SCRIPT,TERM_SUMMARY_PARAM_NAME,queryList);
  try {
    Document response=readXML(url);
    NodeList nodes=response.getElementsByTagName("Item");
    for (int i=0; i < nodes.getLength(); ++i) {
      Node n=nodes.item(i);
      if (n.getNodeType() == Node.ELEMENT_NODE) {
        if (n.getFirstChild() != null) {
          n.replaceChild(response.createTextNode(fixCase(n.getTextContent())),n.getFirstChild());
        }
      }
    }
    Source source=new DOMSource(response);
    StringWriter stringWriter=new StringWriter();
    Result result=new StreamResult(stringWriter);
    TransformerFactory factory=TransformerFactory.newInstance();
    Transformer transformer=factory.newTransformer();
    transformer.transform(source,result);
    return stringWriter.getBuffer().toString();
  }
 catch (  Exception ex) {
    this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "+ ex.getClass().getName()+ " "+ ex.getMessage(),ex);
  }
  return "";
}
 

Example 34

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

Source file: XmlTools.java

  17 
vote

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

Example 35

From project core_1, under directory /config/src/main/java/org/switchyard/config/model/.

Source file: BaseModel.java

  17 
vote

/** 
 * {@inheritDoc}
 */
@Override public Validation validateModel(){
  Validator validator=_desc.getValidator(_config);
  if (validator != null) {
    Source source=_config.getSource();
    try {
      validator.validate(source);
    }
 catch (    Throwable t) {
      return new Validation(getClass(),t);
    }
  }
 else {
    return new Validation(getClass(),false,"validator == null");
  }
  return new Validation(getClass(),true);
}
 

Example 36

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

Source file: TestPipe.java

  17 
vote

public void setUp() throws Exception {
  StandaloneContainer.setConfigurationPath(Thread.currentThread().getContextClassLoader().getResource("conf/standalone/test-configuration.xml").getPath());
  StandaloneContainer container=StandaloneContainer.getInstance();
  TRAXTransformerService traxService=(TRAXTransformerService)container.getComponentInstanceOfType(TRAXTransformerService.class);
  assertNotNull("traxService",traxService);
  HTMLTransformerService htmlService=(HTMLTransformerService)container.getComponentInstanceOfType(HTMLTransformerService.class);
  assertNotNull("htmlService",htmlService);
  htmlTransformer=htmlService.getTransformer();
  assertNotNull("get html transformer",htmlTransformer);
  InputStream xslInputStream=resourceStream("html-url-rewite.xsl");
  assertNotNull("empty xsl",xslInputStream);
  Source xslSource=new StreamSource(xslInputStream);
  assertNotNull("get xsl source",xslSource);
  traxTemplates=traxService.getTemplates(xslSource);
  assertNotNull("get trax Templates",traxTemplates);
}
 

Example 37

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

Source file: TaskDoclet.java

  17 
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 38

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

Source file: FactTest.java

  17 
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 39

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

Source file: SmooksFromSourceTransformer.java

  17 
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 40

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

Source file: Processor.java

  17 
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 41

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

Source file: AbstractAttributeSupportObjectDOM.java

  17 
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 42

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

Source file: SaveProjectCommand.java

  17 
vote

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

Example 43

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

Source file: XmlSerializer.java

  17 
vote

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

Example 44

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

Source file: Fits.java

  17 
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 45

From project flyingsaucer, under directory /flying-saucer-core/src/main/java/org/xhtmlrenderer/resource/.

Source file: XMLResource.java

  17 
vote

XMLResource createXMLResource(XMLResource target){
  Source input=null;
  DOMResult output=null;
  TransformerFactory xformFactory=null;
  Transformer idTransform=null;
  XMLReader xmlReader=null;
  long st=0L;
  xmlReader=XMLResource.newXMLReader();
  addHandlers(xmlReader);
  setParserFeatures(xmlReader);
  st=System.currentTimeMillis();
  try {
    input=new SAXSource(xmlReader,target.getResourceInputSource());
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    output=new DOMResult(dbf.newDocumentBuilder().newDocument());
    xformFactory=TransformerFactory.newInstance();
    idTransform=xformFactory.newTransformer();
  }
 catch (  Exception ex) {
    throw new XRRuntimeException("Failed on configuring SAX to DOM transformer.",ex);
  }
  try {
    idTransform.transform(input,output);
  }
 catch (  Exception ex) {
    throw new XRRuntimeException("Can't load the XML resource (using TRaX transformer). " + ex.getMessage(),ex);
  }
  long end=System.currentTimeMillis();
  target.setElapsedLoadTime(end - st);
  XRLog.load("Loaded document in ~" + target.getElapsedLoadTime() + "ms");
  target.setDocument((Document)output.getNode());
  return target;
}
 

Example 46

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

Source file: ExportToImage.java

  17 
vote

public void transForm(Source xmlSource,InputStream xsltStream,File resultFile,String areaCode){
  Source xsltSource=new StreamSource(xsltStream);
  Result result=new StreamResult(resultFile);
  try {
    TransformerFactory transFact=TransformerFactory.newInstance();
    Transformer trans=transFact.newTransformer(xsltSource);
    trans.setParameter("destination_dir",resultFile.getName() + "_files/");
    trans.setParameter("area_code",areaCode);
    trans.setParameter("folding_type",getController().getFrame().getProperty("html_export_folding"));
    trans.transform(xmlSource,result);
  }
 catch (  Exception e) {
    freemind.main.Resources.getInstance().logException(e);
  }
  ;
  return;
}
 

Example 47

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

Source file: DOMElementProprtyEditor.java

  17 
vote

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

Example 48

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

Source file: PublishingTFAction.java

  17 
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 49

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

Source file: AbstractAttributeSupportObjectDOM.java

  17 
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 50

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

Source file: XMLParser.java

  17 
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 51

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

Source file: TransformSupport.java

  17 
vote

public int doStartTag() throws JspException {
  try {
    if (dbf == null) {
      dbf=DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      dbf.setValidating(false);
    }
    if (db == null)     db=dbf.newDocumentBuilder();
    if (tf == null)     tf=TransformerFactory.newInstance();
    Source s;
    if (xslt != null) {
      if (!(xslt instanceof String) && !(xslt instanceof Reader) && !(xslt instanceof javax.xml.transform.Source))       throw new JspTagException(Resources.getMessage("TRANSFORM_XSLT_UNRECOGNIZED"));
      s=getSource(xslt,xsltSystemId);
    }
 else {
      throw new JspTagException(Resources.getMessage("TRANSFORM_NO_TRANSFORMER"));
    }
    tf.setURIResolver(new JstlUriResolver(pageContext));
    t=tf.newTransformer(s);
    return EVAL_BODY_BUFFERED;
  }
 catch (  SAXException ex) {
    throw new JspException(ex);
  }
catch (  ParserConfigurationException ex) {
    throw new JspException(ex);
  }
catch (  IOException ex) {
    throw new JspException(ex);
  }
catch (  TransformerConfigurationException ex) {
    throw new JspException(ex);
  }
}
 

Example 52

From project karaf, under directory /deployer/blueprint/src/main/java/org/apache/karaf/deployer/blueprint/.

Source file: BlueprintTransformer.java

  17 
vote

public static Set<String> analyze(Source source) throws Exception {
  if (transformer == null) {
    if (tf == null) {
      tf=TransformerFactory.newInstance();
    }
    Source s=new StreamSource(BlueprintTransformer.class.getResourceAsStream("extract.xsl"));
    transformer=tf.newTransformer(s);
  }
  Set<String> refers=new TreeSet<String>();
  ByteArrayOutputStream bout=new ByteArrayOutputStream();
  Result r=new StreamResult(bout);
  transformer.transform(source,r);
  ByteArrayInputStream bin=new ByteArrayInputStream(bout.toByteArray());
  bout.close();
  BufferedReader br=new BufferedReader(new InputStreamReader(bin));
  String line=br.readLine();
  while (line != null) {
    line=line.trim();
    if (line.length() > 0) {
      String parts[]=line.split("\\s*,\\s*");
      for (int i=0; i < parts.length; i++) {
        int n=parts[i].lastIndexOf('.');
        if (n > 0) {
          String pkg=parts[i].substring(0,n);
          if (!pkg.startsWith("java.")) {
            refers.add(pkg);
          }
        }
      }
    }
    line=br.readLine();
  }
  br.close();
  return refers;
}
 

Example 53

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

Source file: KCDLoader.java

  17 
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 54

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

Source file: ConfigurationFlowTest.java

  17 
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 55

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

Source file: DispatchSourceClient.java

  17 
vote

public static void main(String args[]) throws Exception {
  Server.main(new String[]{"inProcess"});
  Service service=Service.create(SERVICE_NAME);
  service.addPort(PORT_NAME,SOAPBinding.SOAP11HTTP_BINDING,ADDRESS);
  Dispatch<Source> dispatch=service.createDispatch(PORT_NAME,Source.class,Service.Mode.PAYLOAD);
  String resp;
  Source response;
  System.out.println("Invoking sayHi...");
  setOperation(dispatch,SAYHI_OPERATION_NAME);
  response=dispatch.invoke(encodeSource(SAYHI_REQUEST_TEMPLATE,null));
  resp=decodeSource(response,PAYLOAD_NAMESPACE_URI,"responseType");
  System.out.println("Server responded with: " + resp);
  System.out.println();
  System.out.println("Invoking greetMe...");
  setOperation(dispatch,GREETME_OPERATION_NAME);
  response=dispatch.invoke(encodeSource(GREETME_REQUEST_TEMPLATE,System.getProperty("user.name")));
  resp=decodeSource(response,PAYLOAD_NAMESPACE_URI,"responseType");
  System.out.println("Server responded with: " + resp);
  System.out.println();
  try {
    System.out.println("Invoking pingMe, expecting exception...");
    setOperation(dispatch,PINGME_OPERATION_NAME);
    response=dispatch.invoke(encodeSource(PINGME_REQUEST_TEMPLATE,null));
  }
 catch (  SOAPFaultException ex) {
    System.out.println("Expected exception: SoapFault has occurred: " + ex.getMessage());
  }
  System.exit(0);
}
 

Example 56

From project maven-android-plugin, under directory /src/main/java/com/jayway/maven/plugins/android/.

Source file: AbstractInstrumentationMojo.java

  17 
vote

/** 
 * Write the junit report xml file.
 */
private void writeJunitReportToFile(){
  TransformerFactory xfactory=TransformerFactory.newInstance();
  Transformer xformer=null;
  try {
    xformer=xfactory.newTransformer();
  }
 catch (  TransformerConfigurationException e) {
    e.printStackTrace();
  }
  Source source=new DOMSource(junitReport);
  FileWriter writer=null;
  try {
    String directory=new StringBuilder().append(project.getBuild().getDirectory()).append("/surefire-reports").toString();
    FileUtils.forceMkdir(new File(directory));
    String fileName=new StringBuilder().append(directory).append("/TEST-").append(DeviceHelper.getDescriptiveName(device)).append(".xml").toString();
    File reportFile=new File(fileName);
    writer=new FileWriter(reportFile);
    Result result=new StreamResult(writer);
    xformer.transform(source,result);
    getLog().info("Report file written to " + reportFile.getAbsolutePath());
  }
 catch (  IOException e) {
    threwException=true;
    exceptionMessages.append("Failed to write test report file");
    exceptionMessages.append(e.getMessage());
  }
catch (  TransformerException e) {
    threwException=true;
    exceptionMessages.append("Failed to transform document to write to test report file");
    exceptionMessages.append(e.getMessage());
  }
 finally {
    IOUtils.closeQuietly(writer);
  }
}
 

Example 57

From project mylyn.context, under directory /org.eclipse.mylyn.context.tests/src/org/eclipse/mylyn/context/tests/support/.

Source file: DomContextWriter.java

  17 
vote

private void writeDOMtoStream(Document document){
  Source source=new DOMSource(document);
  result=new StreamResult(outputStream);
  Transformer xformer=null;
  try {
    xformer=TransformerFactory.newInstance().newTransformer();
    xformer.transform(source,result);
  }
 catch (  TransformerConfigurationException e) {
    e.printStackTrace();
  }
catch (  TransformerFactoryConfigurationError e) {
    e.printStackTrace();
  }
catch (  TransformerException e1) {
    e1.printStackTrace();
  }
}
 

Example 58

From project ndg, under directory /ndg-commons-core/src/main/java/br/org/indt/ndg/common/.

Source file: CreateXml.java

  17 
vote

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

Example 59

From project OpenEMRConnect, under directory /oeclib/src/main/java/ke/go/moh/oec/lib/.

Source file: XmlPacker.java

  17 
vote

/** 
 * Packs a DOM Document structure into an XML string.
 * @param doc the DOM Document structure to pack
 * @return the packed XML string
 */
String packDocument(Document doc){
  StringWriter stringWriter=new StringWriter();
  try {
    Transformer t=TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.INDENT,"yes");
    t.setOutputProperty(OutputKeys.STANDALONE,"yes");
    Source source=new DOMSource(doc);
    t.transform(source,new StreamResult(stringWriter));
  }
 catch (  TransformerConfigurationException ex) {
    Logger.getLogger(XmlPacker.class.getName()).log(Level.SEVERE,null,ex);
  }
catch (  TransformerException ex) {
    Logger.getLogger(XmlPacker.class.getName()).log(Level.SEVERE,null,ex);
  }
  String returnString=stringWriter.toString();
  try {
    stringWriter.close();
  }
 catch (  IOException ex) {
  }
  return returnString;
}
 

Example 60

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

Source file: Processor.java

  17 
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 61

From project PIE, under directory /R2/pie-model/src/main/java/com/pieframework/model/repository/.

Source file: ModelStore.java

  17 
vote

/** 
 * @param xmlFile
 * @param writer
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws TransformerException
 */
protected static void processXIncludes(File xmlFile,Writer writer) throws ParserConfigurationException, SAXException, IOException, TransformerException {
  final InputStream xml=new FileInputStream(xmlFile);
  InputSource i=new InputSource(xml);
  i.setSystemId(xmlFile.toURI().toString());
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setXIncludeAware(true);
  factory.setNamespaceAware(true);
  factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris",false);
  DocumentBuilder docBuilder=factory.newDocumentBuilder();
  if (!docBuilder.isXIncludeAware()) {
    throw new IllegalStateException();
  }
  Document doc=docBuilder.parse(i);
  Source source=new DOMSource(doc);
  Result result=new StreamResult(writer);
  TransformerFactory transformerFactory=TransformerFactory.newInstance();
  Transformer transformer=transformerFactory.newTransformer();
  transformer.transform(source,result);
}
 

Example 62

From project remitt, under directory /src/main/java/org/remitt/plugin/render/.

Source file: XsltPlugin.java

  17 
vote

@Override public byte[] render(Integer jobId,byte[] input,String option) throws Exception {
  log.info("Entered Render for job #" + jobId.toString());
  TransformerFactory tFactory=TransformerFactory.newInstance();
  String transformedOption=DbPlugin.resolvePluginOption("org.remitt.plugin.render.XsltPlugin",option);
  log.info("Original plugin option = " + option + ", transformed to "+ transformedOption);
  String xsltPath=Configuration.getServletContext().getServletContext().getRealPath("/WEB-INF/xsl/" + transformedOption + ".xsl");
  Source xmlInput=new StreamSource(new StringReader(new String(input)));
  log.debug("Loading xsl into transformer");
  Transformer transformer;
  try {
    transformer=tFactory.newTransformer(new StreamSource(xsltPath));
  }
 catch (  TransformerConfigurationException e) {
    log.error(e);
    throw new Exception(e);
  }
  log.debug("Passing parameters to transform");
  transformer.setParameter("currentTime",new Long(System.currentTimeMillis()).toString());
  transformer.setParameter("jobId",jobId == 0 ? new Long(System.currentTimeMillis()).toString() : jobId.toString());
  StreamResult xmlOutput=new StreamResult(new ByteArrayOutputStream());
  log.debug("Performing transformation");
  transformer.transform(xmlInput,xmlOutput);
  log.info("Leaving Render for job #" + jobId.toString());
  return xmlOutput.getOutputStream().toString().getBytes("UTF-8");
}
 

Example 63

From project riftsaw, under directory /console/integration/src/main/java/org/jboss/soa/bpel/console/json/.

Source file: XmlToJson.java

  17 
vote

public static String parse(InputStream in){
  try {
    DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc=builder.parse(in);
    Element root=doc.getDocumentElement();
    normalize(root);
    log.debug("The xml message is: " + DOMUtils.domToString(root));
    ByteArrayOutputStream bout=new ByteArrayOutputStream();
    Writer writer=new PrintWriter(bout);
    Configuration configuration=new Configuration();
    configuration.setIgnoreNamespaces(true);
    MappedNamespaceConvention con=new MappedNamespaceConvention(configuration);
    XMLStreamWriter streamWriter=new ResultAdapter(con,writer);
    Source source=new DOMSource(root);
    Result output=new SAXResult((ContentHandler)streamWriter);
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.transform(source,output);
    streamWriter.flush();
    writer.flush();
    return new String(bout.toByteArray());
  }
 catch (  Exception e) {
    throw new RuntimeException("XMLToJson failed",e);
  }
}
 

Example 64

From project riot, under directory /common/src/org/riotfamily/common/xml/.

Source file: XmlUtils.java

  17 
vote

public static String serialize(Node node){
  try {
    TransformerFactory tf=TransformerFactory.newInstance();
    Transformer transformer=tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
    Source source=new DOMSource(node);
    StringWriter sw=new StringWriter();
    Result result=new StreamResult(sw);
    transformer.transform(source,result);
    return sw.toString();
  }
 catch (  TransformerException e) {
    throw new RuntimeException(e);
  }
}
 

Example 65

From project scape, under directory /xa-toolwrapper/src/main/java/eu/scape_project/xa/tw/gen/.

Source file: ToolspecValidator.java

  17 
vote

/** 
 * @throws GeneratorException
 */
public void validateWithXMLSchema() throws GeneratorException {
  try {
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder=factory.newDocumentBuilder();
    Document doc=builder.parse(new File(ioc.getXmlConf()));
    SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source schemaFile=new StreamSource(ClassLoader.getSystemResourceAsStream(Constants.TOOLSPEC_SCHEMA_RESOURCE_PATH));
    Schema schema=schemaFactory.newSchema(schemaFile);
    Validator validator=schema.newValidator();
    validator.validate(new DOMSource(doc));
    logger.info("XML tool specification file successfully validated.");
  }
 catch (  SAXException ex) {
    org.xml.sax.SAXParseException saxex=null;
    if (ex instanceof org.xml.sax.SAXParseException) {
      saxex=(org.xml.sax.SAXParseException)ex;
      logger.error("SAX parse error: " + saxex.getLocalizedMessage());
    }
 else {
      logger.error("SAXException:",ex);
    }
    throw new GeneratorException("SAXException occurred while validating instance.");
  }
catch (  IOException ex) {
    throw new GeneratorException("IOException occurred while validating instance.");
  }
catch (  ParserConfigurationException ex) {
    throw new GeneratorException("ParserConfigurationException occurred while validating instance.");
  }
}
 

Example 66

From project c24-spring, under directory /c24-spring-core/src/main/java/biz/c24/io/spring/oxm/.

Source file: C24Marshaller.java

  15 
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 67

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/xmlconfig/.

Source file: JAXBBinding.java

  15 
vote

/** 
 * <p class="changed_added_4_0"> Close input source after parsing. </p>
 * @param source
 */
private void closeSource(Source source){
  if (source instanceof SAXSource) {
    SAXSource saxSource=(SAXSource)source;
    InputSource inputSource=saxSource.getInputSource();
    try {
      Reader stream=inputSource.getCharacterStream();
      if (null != stream) {
        stream.close();
      }
 else {
        InputStream byteStream=inputSource.getByteStream();
        if (null != byteStream) {
          byteStream.close();
        }
      }
    }
 catch (    IOException e) {
    }
  }
}
 

Example 68

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

Source file: JAXWSEndpointPublisher.java

  15 
vote

/** 
 * {@inheritDoc}
 */
public synchronized WSEndpoint publish(final SOAPBindingModel config,final String bindingId,final InboundHandler handler){
  JAXWSEndpoint wsEndpoint=null;
  try {
    initialize(config);
    List<Source> metadata=new ArrayList<Source>();
    StreamSource source=WSDLUtil.getStream(config.getWsdl());
    metadata.add(source);
    Map<String,Object> properties=new HashMap<String,Object>();
    properties.put(Endpoint.WSDL_SERVICE,config.getPort().getServiceQName());
    properties.put(Endpoint.WSDL_PORT,config.getPort().getPortQName());
    properties.put(MessageContext.WSDL_DESCRIPTION,getWsdlLocation());
    String publishUrl=HTTP_SCHEME + "://" + config.getSocketAddr().getHost()+ ":"+ config.getSocketAddr().getPort()+ "/"+ getContextPath();
    LOGGER.info("Publishing WebService at " + publishUrl);
    wsEndpoint=new JAXWSEndpoint(bindingId,handler);
    wsEndpoint.getEndpoint().setMetadata(metadata);
    wsEndpoint.getEndpoint().setProperties(properties);
    wsEndpoint.getEndpoint().publish(publishUrl);
  }
 catch (  MalformedURLException e) {
    throw new WebServicePublishException(e);
  }
catch (  WSDLException e) {
    throw new WebServicePublishException(e);
  }
  return wsEndpoint;
}
 

Example 69

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

Source file: CTDNodeConfigurationReader.java

  15 
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 70

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

Source file: StAXUtils.java

  15 
vote

public static XMLStreamReader staxReader(Source source) throws FactoryConfigurationError, XMLStreamException {
  XMLInputFactory inf=XMLInputFactory.newFactory();
  inf.setProperty("javax.xml.stream.isCoalescing",true);
  inf.setProperty("javax.xml.stream.supportDTD",false);
  XMLStreamReader sr=inf.createXMLStreamReader(source);
  return sr;
}
 

Example 71

From project lenya, under directory /org.apache.lenya.core.impl/src/main/java/org/apache/lenya/xml/.

Source file: ValidationUtil.java

  15 
vote

/** 
 * @param source The source to validate.
 * @param schema The schema to use.
 * @param handler The SAX error handler.
 * @throws Exception if an error occurs.
 */
public static void validate(Source source,Schema schema,ErrorHandler handler) throws Exception {
  Validator validator=getValidator();
  ContentHandler validatorHandler=validator.getValidationHandler(schema.getURI(),handler);
  Transformer transformer=TransformerFactory.newInstance().newTransformer();
  SAXResult result=new SAXResult(validatorHandler);
  transformer.transform(source,result);
}
 

Example 72

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

Source file: XSD.java

  15 
vote

@PostConstruct public void init(){
  log.fine("Initializing XSD support");
  repository.registerFileExtension("xsd",XSD_MIMETYPE);
  repository.registerNamespace(XSD_NAMESPACE,XSD_MIMETYPE);
  xmlValidate.registerSchemaSource(XSD_MIMETYPE,new SchemaSource(){
    @Override public Source[] getSchemaSource(){
      try {
        return new Source[]{new StreamSource(getClass().getResourceAsStream("/META-INF/xsd/wsdl.xsd"))};
      }
 catch (      Exception e) {
        log.log(Level.SEVERE,"",e);
        return null;
      }
    }
  }
);
  repository.registerCommandInfo(XSD_MIMETYPE,Validate.VALIDATE_CMD,true,xmlValidate.getProvider());
  repository.registerHandler(XSD_MIMETYPE,new XMLDataContentHandler());
  XSDCompiler schemaCompiler=new XSDCompiler();
  schemaCompiler.addSubContext(XSDContext.ID,schemaProvider);
  XSDCompilerPass compiler=new XSDCompilerPass();
  schemaCompiler.addCompilerPass(CompilerPhase.DISCOVERY,compiler);
  compilers.register(schemaCompiler,XSD_MIMETYPE);
  log.fine("XSD support Initialized");
}