/** * Performs the XSLT transformation. */ private String doTransform(final Transformer transformer, final Source input, final URIResolver resolver) { final StringWriter writer = new StringWriter(); final StreamResult output = new StreamResult(writer); if( resolver != null ) { transformer.setURIResolver(resolver); } try { transformer.transform(input, output); } catch( final TransformerException ex ) { throw new RuntimeException("Error transforming XSLT", ex); } return writer.toString(); }
/** * Overrides the default readObject implementation since we decided * it would be cleaner not to serialize the entire tranformer * factory. [ ref bugzilla 12317 ] * We need to check if the user defined class for URIResolver also * implemented Serializable * if yes then we need to deserialize the URIResolver * Fix for bugzilla bug 22438 */ private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException { SecurityManager security = System.getSecurityManager(); if (security != null){ String temp = SecuritySupport.getSystemProperty(DESERIALIZE_TRANSLET); if (temp == null || !(temp.length()==0 || temp.equalsIgnoreCase("true"))) { ErrorMsg err = new ErrorMsg(ErrorMsg.DESERIALIZE_TRANSLET_ERR); throw new UnsupportedOperationException(err.toString()); } } is.defaultReadObject(); if (is.readBoolean()) { _uriResolver = (URIResolver) is.readObject(); } _tfactory = new TransformerFactoryImpl(); }
public void initialize(String pipelineURI, String uriResolverClassName, String entityResolverClassName) { try{ if (uriResolverClassName != null && uriResolverClassName.trim().length()!=0) theURIResolver = (URIResolver) getClass().getClassLoader().loadClass(uriResolverClassName).newInstance(); else theURIResolver = null; if (entityResolverClassName != null && entityResolverClassName.trim().length()!=0) theEntityResolver = (EntityResolver) getClass().getClassLoader().loadClass(entityResolverClassName).newInstance(); else theEntityResolver = null; if (pipelineURI != null && pipelineURI.trim().length()!=0) thePipelineURI = pipelineURI; else thePipelineURI = null; } catch (Throwable t){ compilationErrors.clear(); compilationErrors.add(new DocumentPositionedInfo(DocumentPositionedInfo.SEVERITY_ERROR, "Error initializing adapter: "+t.getMessage())); dumpStackTrace(t); } }
TransformerFactory getFactory() throws Exception { if (fac == null) { fac = TransformerFactory.newInstance(); fac.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { try { return new StreamSource(asl2xml.class.getResource("/xml/" + href).openStream()); } catch (Exception e) { System.err.println("Error - " + href + "-" + base); e.printStackTrace(); return null; } } }); } return fac; }
/** * Returns an instance of TransformerFactory with either a custom URIResolver * or Catalog. * * @param setUseCatalog a flag indicates whether USE_CATALOG shall be set * through the factory * @param useCatalog the value of USE_CATALOG * @param catalog a catalog * @param resolver a custom resolver * @return an instance of TransformerFactory * @throws Exception */ TransformerFactory getTransformerFactory(boolean setUseCatalog, boolean useCatalog, String catalog, URIResolver resolver) throws Exception { TransformerFactory factory = TransformerFactory.newInstance(); if (setUseCatalog) { factory.setFeature(XMLConstants.USE_CATALOG, useCatalog); } if (catalog != null) { factory.setAttribute(CatalogFeatures.Feature.FILES.getPropertyName(), catalog); } // use resolver or catalog if resolver = null if (resolver != null) { factory.setURIResolver(resolver); } return factory; }
private URIResolver getCustomURIResolver() { return new URIResolver() { @Override public Source resolve(String href, String base) throws TransformerException { if (href.equals("org/apache/camel/component/xslt/include_not_existing_resource.xsl")) { try { InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(context, href); return new StreamSource(is); } catch (Exception e) { throw new TransformerException(e); } } Source constantResult = new StreamSource(new ByteArrayInputStream(EXPECTED_XML_CONSTANT.getBytes())); return constantResult; } }; }
public Map<String, URIResolver> getURIResolverMapping() { Map<String, String> props = MCRConfiguration.instance().getPropertiesMap(CONFIG_PREFIX + "ModuleResolver."); if (props.isEmpty()) { return new HashMap<>(); } Map<String, URIResolver> map = new HashMap<>(); for (Entry<String, String> entry : props.entrySet()) { try { String scheme = entry.getKey(); scheme = scheme.substring(scheme.lastIndexOf('.') + 1); LOGGER.debug("Adding Resolver {} for URI scheme {}", entry.getValue(), scheme); map.put(scheme, MCRConfiguration.instance().getInstanceOf(entry.getKey())); } catch (Exception e) { LOGGER.error("Cannot instantiate {} for URI scheme {}", entry.getValue(), entry.getKey()); throw new MCRException( "Cannot instantiate " + entry.getValue() + " for URI scheme " + entry.getKey(), e); } } return map; }
@Override public String extractFactModel(String document, String enforcementPolicies) { try { final String xslUrl = Thread.currentThread().getContextClassLoader() .getResource(EXTRACT_CLINICAL_FACTS_XSL).toString(); final String xacmlResult = enforcementPolicies.replace("<xacmlReslt>", "<xacmlReslt xmlns:\"urn:hl7-org:v3\">"); final Optional<URIResolver> uriResolver = Optional .of(new StringURIResolver() .put(PARAM_XACML_RESULT, xacmlResult)); String factModel = xmlTransformer.transform(document, xslUrl, Optional.empty(), uriResolver); factModel = factModel .replace( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""); logger.debug("FactModel:"); logger.debug(factModel); return factModel; } catch (final Exception e) { throw new DocumentSegmentationException(e.getMessage(), e); } }
@Override public String tagDocument(String document, String executionResponseContainer) { try { executionResponseContainer = executionResponseContainer.replace( "<ruleExecutionContainer>", "<ruleExecutionContainer xmlns=\"urn:hl7-org:v3\">"); final String xslUrl = Thread.currentThread().getContextClassLoader() .getResource(TAG_XSL).toString(); final StringURIResolver stringURIResolver = new StringURIResolver(); stringURIResolver.put( URI_RESOLVER_HREF_RULE_EXECUTION_RESPONSE_CONTAINER, executionResponseContainer); final String additionalCustomSections = marshaller.marshal(documentTaggerConfig.getAdditionalSectionsAsCustomSectionList()); stringURIResolver.put("customSectionList", additionalCustomSections); final Optional<URIResolver> uriResolver = Optional .of(stringURIResolver); final String taggedDocument = xmlTransformer.transform(document, xslUrl, Optional.empty(), uriResolver); logger.debug("Tagged Document:"); logger.debug(taggedDocument); return taggedDocument; } catch (final Exception e) { throw new DocumentSegmentationException(e.getMessage(), e); } }
public static TransformerFactory getTransformerFactory() { if (tFactory == null) { tFactory = TransformerFactory.newInstance(); tFactory.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { try { return DOMUtils.getXSL(href); } catch (Exception e) { e.printStackTrace(); return null; } } }); } return tFactory; }
public TransformerHandler resolve (final String method, final String href, final String base, final URIResolver uriResolver, final ErrorListener errorListener, final Hashtable <String, Object> params) throws SAXException { if (METHOD.equals (method)) { if (href != null) throw new SAXException ("Specification of an external source '" + href + "' not allowed for " + method); skipUri = String.valueOf (params.get ("uri")); return this; } return null; }
@Override public String transform(final FileHandle handle, final String xslt, final Reader input, final URIResolver resolver) { StreamSource source = null; try { source = getSource(input); return transformFromFileHandle(handle, xslt, source, resolver, false); } finally { closeSource(source); } }
/** * Overrides the default readObject implementation since we decided * it would be cleaner not to serialize the entire tranformer * factory. [ ref bugzilla 12317 ] * We need to check if the user defined class for URIResolver also * implemented Serializable * if yes then we need to deserialize the URIResolver * Fix for bugzilla bug 22438 */ @SuppressWarnings("unchecked") private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException { SecurityManager security = System.getSecurityManager(); if (security != null){ String temp = SecuritySupport.getSystemProperty(DESERIALIZE_TRANSLET); if (temp == null || !(temp.length()==0 || temp.equalsIgnoreCase("true"))) { ErrorMsg err = new ErrorMsg(ErrorMsg.DESERIALIZE_TRANSLET_ERR); throw new UnsupportedOperationException(err.toString()); } } // We have to read serialized fields first. ObjectInputStream.GetField gf = is.readFields(); _name = (String)gf.get("_name", null); _bytecodes = (byte[][])gf.get("_bytecodes", null); _class = (Class[])gf.get("_class", null); _transletIndex = gf.get("_transletIndex", -1); _outputProperties = (Properties)gf.get("_outputProperties", null); _indentNumber = gf.get("_indentNumber", 0); if (is.readBoolean()) { _uriResolver = (URIResolver) is.readObject(); } _tfactory = new TransformerFactoryImpl(); }
@Test(dataProvider = "data_XSLA") public void testXSLImportA(boolean setUseCatalog, boolean useCatalog, String catalog, SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception { testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected); }
@DataProvider(name = "data_XSLA") public Object[][] getDataXSL() { // XSLInclude.xsl has one import XSLImport_html.xsl and two includes, // XSLInclude_header.xsl and XSLInclude_footer.xsl; String[] hrefs = {"XSLImport_html.xsl", "XSLInclude_header.xsl", "XSLInclude_footer.xsl"}; Source[] returnValues = {new StreamSource(xsl_import_html), new StreamSource(xsl_include_header), new StreamSource(xsl_include_footer)}; URIResolver resolver = new XslResolver(hrefs, returnValues); SAXSource xslSourceDTD = new SAXSource(new InputSource(new StringReader(xsl_includeDTD))); StreamSource xmlSourceDTD = new StreamSource(new StringReader(xml_xslDTD)); String[] hrefs1 = {"pathto/DocFunc2.xml"}; Source[] returnValues1 = {new StreamSource(xml_doc2)}; URIResolver docResolver = new XslResolver(hrefs1, returnValues1); SAXSource xslDocSource = new SAXSource(new InputSource(new File(xsl_doc).toURI().toASCIIString())); StreamSource xmlDocSource = new StreamSource(new File(xml_doc)); return new Object[][]{ // for resolving DTD, import and include in xsl {false, true, xml_catalog, xslSourceDTD, xmlSourceDTD, null, ""}, {false, true, xml_bogus_catalog, new SAXSource(new InputSource(new StringReader(xsl_include))), new StreamSource(new StringReader(xml_xsl)), resolver, ""}, {true, true, xml_bogus_catalog, new SAXSource(new InputSource(new StringReader(xsl_include))), new StreamSource(new StringReader(xml_xsl)), resolver, ""}, // for resolving reference by the document function {false, true, xml_catalog, xslDocSource, xmlDocSource, null, "Resolved by a catalog"}, {false, true, xml_bogus_catalog, xslDocSource, xmlDocSource, docResolver, "Resolved by a resolver"}, {true, true, xml_bogus_catalog, xslDocSource, xmlDocSource, docResolver, "Resolved by a resolver"} }; }
public void testXSLImport(boolean setUseCatalog, boolean useCatalog, String catalog, SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception { TransformerFactory factory = getTransformerFactory(setUseCatalog, useCatalog, catalog, resolver); Transformer transformer = factory.newTransformer(xsl); StringWriter out = new StringWriter(); transformer.transform(xml, new StreamResult(out)); debugPrint("out:\n" + out.toString()); Assert.assertTrue(out.toString().contains(expected), "testXSLImport"); }
public void testXSLImportWTemplates(boolean setUseCatalog, boolean useCatalog, String catalog, SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception { TransformerFactory factory = getTransformerFactory(setUseCatalog, useCatalog, catalog, resolver); Transformer transformer = factory.newTemplates(xsl).newTransformer(); StringWriter out = new StringWriter(); transformer.transform(xml, new StreamResult(out)); Assert.assertTrue(out.toString().contains(expected), "testXSLImportWTemplates"); }
/** * Act with XSL transformation of response body. * * @param act origin. must provide xml with stylesheet. * @param resolver uri resolver to resolve stylesheets in xml. * @return Act with XSL transformation. */ static Act xslt(Act act, URIResolver resolver) { return request -> unchecked(() -> { Response response = act.on(request); return response.body(transform(transformerFactory(resolver), response.body)) .header(Headers.CONTENT_TYPE, "application/xml"); }); }
private HashMap<String, URIResolver> getResolverMapping() { final Map<String, URIResolver> extResolverMapping = EXT_RESOLVER.getURIResolverMapping(); extResolverMapping.putAll(new MCRModuleResolverProvider().getURIResolverMapping()); // set Map to final size with loadfactor: full HashMap<String, URIResolver> supportedSchemes = new HashMap<>(10 + extResolverMapping.size(), 1); // don't let interal mapping be overwritten supportedSchemes.putAll(extResolverMapping); supportedSchemes.put("webapp", new MCRWebAppResolver()); supportedSchemes.put("ifs", new MCRIFSResolver()); supportedSchemes.put("mcrfile", new MCRMCRFileResolver()); supportedSchemes.put("mcrobject", new MCRObjectResolver()); supportedSchemes.put("session", new MCRSessionResolver()); supportedSchemes.put("access", new MCRACLResolver()); supportedSchemes.put("resource", new MCRResourceResolver()); supportedSchemes.put("localclass", new MCRLocalClassResolver()); supportedSchemes.put("classification", new MCRClassificationResolver()); supportedSchemes.put("buildxml", new MCRBuildXMLResolver()); supportedSchemes.put("catchEx", new MCRExceptionAsXMLResolver()); supportedSchemes.put("notnull", new MCRNotNullResolver()); supportedSchemes.put("xslStyle", new MCRXslStyleResolver()); supportedSchemes.put("xslTransform", new MCRLayoutTransformerResolver()); supportedSchemes.put("xslInclude", new MCRXslIncludeResolver()); supportedSchemes.put("xslImport", new MCRXslImportResolver()); supportedSchemes.put("versioninfo", new MCRVersionInfoResolver()); supportedSchemes.put("deletedMcrObject", new MCRDeletedObjectResolver()); supportedSchemes.put("fileMeta", new MCRFileMetadataResolver()); supportedSchemes.put("basket", new org.mycore.frontend.basket.MCRBasketResolver()); supportedSchemes.put("language", new org.mycore.datamodel.language.MCRLanguageResolver()); supportedSchemes.put("chooseTemplate", new MCRChooseTemplateResolver()); supportedSchemes.put("redirect", new MCRRedirectResolver()); supportedSchemes.put("data", new MCRDataURLResolver()); MCRRESTResolver restResolver = new MCRRESTResolver(); supportedSchemes.put("http", restResolver); supportedSchemes.put("https", restResolver); supportedSchemes.put("file", new MCRFileResolver()); return supportedSchemes; }
URIResolver getResolver(String scheme) { if (SUPPORTED_SCHEMES.containsKey(scheme)) { return SUPPORTED_SCHEMES.get(scheme); } String msg = "Unsupported scheme type: " + scheme; throw new MCRUsageException(msg); }
@Override public Source resolve(String href, String base) throws TransformerException { String classname = href.substring(href.indexOf(":") + 1, href.indexOf("?")); Class<?> cl = null; LogManager.getLogger(this.getClass()).debug("Loading Class: {}", classname); Object o; try { cl = Class.forName(classname); o = cl.newInstance(); } catch (Exception e) { throw new TransformerException(e); } URIResolver resolver = (URIResolver) o; return resolver.resolve(href, base); }
private JDOMResult xslTransformation(InputStream testXMLAsStream, String styleSheetPath) throws TransformerFactoryConfigurationError, TransformerException { InputStream stylesheetAsStream = getClass().getResourceAsStream(styleSheetPath); TransformerFactory transformerFactory = TransformerFactory.newInstance(); URIResolver mockIncludeResolver = new MockURIResolver(); transformerFactory.setURIResolver(mockIncludeResolver); Templates templates = transformerFactory.newTemplates(new StreamSource(stylesheetAsStream)); Transformer transformer = templates.newTransformer(); URIResolver resolver = new MockResolver(); transformer.setURIResolver(resolver); JDOMResult jdomResult = new JDOMResult(); transformer.transform(new StreamSource(testXMLAsStream), jdomResult); return jdomResult; }
@Override public String generateMetadataXml(String document, String executionResponseContainer, String homeCommunityId, String senderEmailAddress, String recipientEmailAddress) { try { final Params params = ParamsBuilder .withParam(PARAM_NAME_HOME_COMMUNITY_ID, homeCommunityId) .and(PARAM_NAME_AUTHOR_TELECOMMUNICATION, senderEmailAddress) .and(PARAM_NAME_INTENDED_RECIPIENT, recipientEmailAddress); final String xslUrl = Thread.currentThread().getContextClassLoader() .getResource(METADATA_XSL).toString(); // add namespace execution response container for transformation executionResponseContainer = executionResponseContainer.replace( "<ruleExecutionContainer>", "<ruleExecutionContainer xmlns=\"urn:hl7-org:v3\">"); final Optional<URIResolver> uriResolver = Optional .of(new StringURIResolver().put( URI_RESOLVER_HREF_RULE_EXECUTION_RESPONSE_CONTAINER, executionResponseContainer)); final String metadataXml = xmlTransformer.transform(document, xslUrl, Optional.of(params), uriResolver); logger.debug("Metadata:"); logger.debug(metadataXml); return metadataXml; } catch (final Exception e) { throw new MetadataGeneratorException(e.getMessage(), e); } }
@Override public String generateMetadataXml(String messageId, String document, String ruleExecutionResponseContainer, String senderEmailAddress, String recipientEmailAddress, String purposeOfUse, String xdsDocumentEntryUniqueId) { try { final Params params = ParamsBuilder .withParam(PARAM_NAME_AUTHOR_TELECOMMUNICATION, senderEmailAddress) .and(PARAM_NAME_INTENDED_RECIPIENT, recipientEmailAddress) .and(PARAM_NAME_PURPOSE_OF_USE, purposeOfUse) .and(PARAM_NAME_PRIVACY_POLICIES_EXTERNAL_DOC_URL, messageId) .and(PARAM_NAME_XDS_DOCUMENT_ENTRY_UNIQUE_ID, xdsDocumentEntryUniqueId); final String xslUrl = Thread .currentThread() .getContextClassLoader() .getResource( AdditonalMetadataStylesheetForProcessedC32_Xsl_File_Name) .toString(); final Optional<URIResolver> uriResolver = Optional .of(new StringURIResolver() .put(URI_RESOLVER_HREF_RULE_EXECUTION_RESPONSE_CONTAINER, ruleExecutionResponseContainer)); final String output = xmlTrasformer.transform(document, xslUrl, Optional.of(params), uriResolver); Assert.hasText(output, "Cannot generate additional metadata!"); logger.debug("AdditionalMetadata:"); logger.debug(output); return output; } catch (final Exception e) { throw new AdditionalMetadataGeneratorException(e.getMessage(), e); } }
public SimOEFrame(SimOE ag, boolean addSim) { super("Moise ("+ag.getName()+")"); this.ag = ag; this.hasSim = addSim; // to load .xsl from the moise.jar tFactory.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { return getXSL(href); } }); initComponents(addSim); }
/** * This is essentially same method as common resolve but it assumes that * params are already "parsed" via * {@link #createExternalParameters(Hashtable)} */ public TransformerHandler resolve (final String method, final XMLReader reader, final URIResolver uriResolver, final ErrorListener errorListener, final Hashtable <String, Value> params) throws SAXException { final Hashtable <String, Object> externalParams = createExternalParameters (params); if (customResolver != null) { final TransformerHandler handler = customResolver.resolve (method, reader, uriResolver, errorListener, externalParams); if (handler != null) return handler; } if (notInitializedYet) init (); final ITransformerHandlerResolver impl = plugins.get (method); if (impl == null) throw new SAXException ("Undefined filter implementation for method '" + method + "'"); return impl.resolve (method, reader, uriResolver, errorListener, externalParams); }
/** * Setter for {@link #m_aURIResolver} * * @param resolver * The <code>URIResolver</code> object. */ @Override public void setURIResolver (final URIResolver resolver) { synchronized (m_aReentryGuard) { this.m_aURIResolver = resolver; } }
/** * Setter for {@link #uriRes} * * @param resolver * A <code>URIResolver</code> object. */ @Override public void setURIResolver (final URIResolver resolver) { synchronized (reentryGuard) { uriRes = resolver; m_aProcessor.setURIResolver (resolver); } }
@Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry registry = super.createRegistry(); URIResolver customURIResolver = getCustomURIResolver(); registry.bind("customURIResolver", customURIResolver); return registry; }
/** * If given method is {@link #SAX_METHOD} return cached (or new) Trax * compatible instance. otherwise return <code>null</code>. */ public TransformerHandler resolve (final String method, final XMLReader reader, final URIResolver uriResolver, final ErrorListener errorListener, final Hashtable <String, Object> params) throws SAXException { return _resolve (method, null, reader); }
/** * If given method is {@link #HTTP_POST_METHOD} return cached (or new) Trax * compatible instance. otherwise return <code>null</code>. */ public TransformerHandler resolve (final String method, final String href, final String base, final URIResolver uriResolver, final ErrorListener errorListener, final Hashtable <String, Object> params) throws SAXException { return _resolve (method, href, null, params); }
public TransformerHandler resolve (final String method, final XMLReader reader, final URIResolver uriResolver, final ErrorListener errorListener, final Hashtable <String, Object> params) throws SAXException { return _resolve (method, null, reader, params); }
public TransformerHandler resolve (final String method, final XMLReader reader, final URIResolver uriResolver, final ErrorListener errorListener, final Hashtable <String, Object> params) throws SAXException { if (!available (method)) throw new SAXException ("Not supported filter-method:" + method); if (CSTX.DEBUG) log.debug ("resolve(buffer)"); if (reader == null) throw new SAXException ("method-src must be url() or buffer()"); setFilterAttributes (params); TransformerHandler th = null; // reuse th if available th = getReusableXmlReaderTH (method); // new transformer if non available if (th == null) { // prepare the source if (CSTX.DEBUG) log.debug ("resolve(buffer): new source out of buffer"); final Source source = new SAXSource (reader, new InputSource ()); th = newTHOutOfTrAX (method, source, params, errorListener, uriResolver); // cache the instance if required cacheBufferTH (method, th); } prepareTh (th, params); return th; }
private void setupTransformerFactory (final TransformerFactory factory, final ErrorListener errorListener, final URIResolver uriResolver) { if (errorListener != null) factory.setErrorListener (errorListener); if (uriResolver != null) factory.setURIResolver (uriResolver); }
private void setupTransformer (final Transformer transformer, final ErrorListener errorListener, final URIResolver uriResolver) { if (errorListener != null) transformer.setErrorListener (errorListener); if (uriResolver != null) transformer.setURIResolver (uriResolver); }
public TransformerHandler resolve (final String method, final XMLReader reader, final URIResolver uriResolver, final ErrorListener errorListener, final Hashtable <String, Object> params) throws SAXException { if (METHOD.equals (method)) throw new SAXException ("Provision of internal code not allowed for " + method); return null; }