@Override public Source resolve(String href, String base) throws TransformerException { String id = href.substring(href.indexOf(":") + 1); LOGGER.debug("Reading METS for ID {}", id); MCRObjectID objId = MCRObjectID.getInstance(id); if (!objId.getTypeId().equals("derivate")) { String derivateID = getDerivateFromObject(id); if (derivateID == null) { return new JDOMSource(new Element("mets", Namespace.getNamespace("mets", "http://www.loc.gov/METS/"))); } id = derivateID; } MCRPath metsPath = MCRPath.getPath(id, "/mets.xml"); try { if (Files.exists(metsPath)) { //TODO: generate new METS Output //ignoreNodes.add(metsFile); return new MCRPathContent(metsPath).getSource(); } Document mets = MCRMETSGeneratorFactory.create(MCRPath.getPath(id, "/")).generate().asDocument(); return new JDOMSource(mets); } catch (Exception e) { throw new TransformerException(e); } }
@Override public Source resolve(String href, String base) throws TransformerException { String type = href.substring(href.indexOf(":") + 1); String path = "/templates/" + type + "/"; LOGGER.debug("Reading templates from {}", path); Set<String> resourcePaths = context.getResourcePaths(path); ArrayList<String> templates = new ArrayList<>(); if (resourcePaths != null) { for (String resourcePath : resourcePaths) { if (!resourcePath.endsWith("/")) { //only handle directories continue; } String templateName = resourcePath.substring(path.length(), resourcePath.length() - 1); LOGGER.debug("Checking if template: {}", templateName); if (templateName.contains("/")) { continue; } templates.add(templateName); } Collections.sort(templates); } LOGGER.info("Found theses templates: {}", templates); return new JDOMSource(getStylesheets(templates)); }
/** * Reads XML from a http or https URL. * * @param href * the URL of the xml document * @return the root element of the xml document */ @Override public Source resolve(String href, String base) throws TransformerException { LOGGER.debug("Reading xml from url {}", href); String path = href.substring(href.indexOf(":") + 1); int i = path.indexOf("?host"); if (i > 0) { path = path.substring(0, i); } StringTokenizer st = new StringTokenizer(path, "/"); String ownerID = st.nextToken(); try { String aPath = MCRXMLFunctions.decodeURIPath(path.substring(ownerID.length() + 1)); // TODO: make this more pretty if (ownerID.endsWith(":")) { ownerID = ownerID.substring(0, ownerID.length() - 1); } LOGGER.debug("Get {} path: {}", ownerID, aPath); return new JDOMSource(MCRPathXML.getDirectoryXML(MCRPath.getPath(ownerID, aPath))); } catch (IOException | URISyntaxException e) { throw new TransformerException(e); } }
@Override public Source resolve(String href, String base) throws TransformerException { String target = href.substring(href.indexOf(":") + 1); // fixes exceptions if suburi is empty like "mcrobject:" String subUri = target.substring(target.indexOf(":") + 1); if (subUri.length() == 0) { return new JDOMSource(new Element("null")); } // end fix LOGGER.debug("Ensuring xml is not null: {}", target); try { Source result = MCRURIResolver.instance().resolve(target, base); if (result != null) { return result; } else { LOGGER.debug("MCRNotNullResolver returning empty xml"); return new JDOMSource(new Element("null")); } } catch (Exception ex) { LOGGER.info("MCRNotNullResolver caught exception: {}", ex.getLocalizedMessage()); LOGGER.debug(ex.getStackTrace()); LOGGER.debug("MCRNotNullResolver returning empty xml"); return new JDOMSource(new Element("null")); } }
/** * Builds a simple xml node tree on basis of name value pair */ public Source resolve(String href, String base) throws TransformerException { String key = href.substring(href.indexOf(":") + 1); LOGGER.debug("Building xml from {}", key); Hashtable<String, String> params = getParameterMap(key); Element defaultRoot = new Element("root"); Element root = defaultRoot; String rootName = params.get("_rootName_"); if (rootName != null) { root = new Element(getLocalName(rootName), getNamespace(rootName)); params.remove("_rootName_"); } for (Map.Entry<String, String> entry : params.entrySet()) { constructElement(root, entry.getKey(), entry.getValue()); } if (root == defaultRoot && root.getChildren().size() > 1) { LOGGER.warn("More than 1 root node defined, returning first"); return new JDOMSource(root.getChildren().get(0).detach()); } return new JDOMSource(root); }
/** * Returns a deleted mcr object xml for the given id. If there is no such object a dummy object with an empty * metadata element is returned. * * @param href * an uri starting with <code>deletedMcrObject:</code> * @param base * may be null */ @Override public Source resolve(String href, String base) throws TransformerException { String[] parts = href.split(":"); MCRObjectID mcrId = MCRObjectID.getInstance(parts[parts.length - 1]); LOGGER.info("Resolving deleted object {}", mcrId); try { MCRContent lastPresentVersion = MCRXMLMetadataManager.instance().retrieveContent(mcrId, -1); if (lastPresentVersion == null) { LOGGER.warn("Could not resolve deleted object {}", mcrId); return new JDOMSource(MCRObjectFactory.getSampleObject(mcrId)); } return lastPresentVersion.getSource(); } catch (IOException e) { throw new TransformerException(e); } }
@Override public Source resolve(String href, String base) throws TransformerException { String[] parts = href.split(":"); String completePath = parts[1]; String[] pathParts = completePath.split("/", 2); MCRObjectID derivateID = MCRObjectID.getInstance(pathParts[0]); MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID); MCRObjectDerivate objectDerivate = derivate.getDerivate(); if (pathParts.length == 1) { //only derivate is given; Element fileset = new Element("fileset"); if (objectDerivate.getURN() != null) { fileset.setAttribute("urn", objectDerivate.getURN()); for (MCRFileMetadata fileMeta : objectDerivate.getFileMetadata()) { fileset.addContent(fileMeta.createXML()); } } return new JDOMSource(fileset); } MCRFileMetadata fileMetadata = objectDerivate.getOrCreateFileMetadata("/" + pathParts[1]); return new JDOMSource(fileMetadata.createXML()); }
/** * validates <code>doc</code> using XML Schema defined <code>schemaURI</code> * @param doc document to be validated * @param schemaURI URI of XML Schema document * @throws SAXException if validation fails * @throws IOException if resolving resources fails */ public static void validate(Document doc, String schemaURI) throws SAXException, IOException { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); sf.setResourceResolver(MCREntityResolver.instance()); Schema schema; try { schema = sf.newSchema(MCRURIResolver.instance().resolve(schemaURI, null)); } catch (TransformerException e) { Throwable cause = e.getCause(); if (cause == null) { throw new IOException(e); } if (cause instanceof SAXException) { throw (SAXException) cause; } if (cause instanceof IOException) { throw (IOException) cause; } throw new IOException(e); } Validator validator = schema.newValidator(); validator.setResourceResolver(MCREntityResolver.instance()); validator.validate(new JDOMSource(doc)); }
/** * This routine is sued to generate files that have no .xml file, but only a .xsl file. * It is used for files included by other html files to avoid repreating the contents; * - header.html * - generated.html */ public static void generateIncludedHtml(Document document, File outputPath, String xslname) throws IOException { if (ConfigurationManager.getCurrentProfile().getGenerateHtml()) { FileOutputStream fos = null; try { JDOMSource source = new JDOMSource(document); File htmlFile = new File(outputPath,getHtmlFilename(xslname)); fos = new FileOutputStream(htmlFile); StreamResult streamResult = new StreamResult(fos); try { Transformer transformer; transformer = JDOMManager.getIncludeTransformer(xslname); transformer.transform(source, streamResult); } catch (TransformerException e) { logger.error(Localization.Main.getText("error.cannotTransform", xslname), e); } } finally { if (fos != null) fos.close(); } } }
@Override public Source resolve(String href, String base) throws TransformerException { href = href.substring(href.indexOf(":") + 1); Element mods = MCRURIResolver.instance().resolve(href); MCRMODSSorter.sort(mods); return new JDOMSource(mods); }
@Override public Source resolve(String href, String base) throws TransformerException { href = href.substring(href.indexOf(":") + 1); String configID = href.substring(0, href.indexOf(':')); href = href.substring(href.indexOf(":") + 1); Element mods = MCRURIResolver.instance().resolve(href); enrichPublication(mods, configID); return new JDOMSource(mods); }
@Override public Source resolve(final String href, final String base) throws TransformerException { String realmID = href.split(":")[1]; if ("all".equals(realmID)) { return MCRRealmFactory.getRealmsSource(); } else if ("local".equals(realmID)) { realmID = MCRRealmFactory.getLocalRealm().getID(); } return new JDOMSource(getElement(MCRRealmFactory.getRealm(realmID).getID())); }
@Override public Source resolve(final String href, final String base) throws TransformerException { final String target = href.substring(href.indexOf(":") + 1); final String[] part = target.split(":"); final String method = part[0]; try { if ("getAssignableGroupsForUser".equals(method)) { return new JDOMSource(getAssignableGroupsForUser()); } } catch (final MCRAccessException exc) { throw new TransformerException(exc); } throw new TransformerException(new IllegalArgumentException("Unknown method " + method + " in uri " + href)); }
/** * Builds an MCRUser instance from the given element. * @param element as generated by {@link #buildExportableXML(MCRUser)}. */ public static MCRUser buildMCRUser(Element element) { if (!element.getName().equals(USER_ELEMENT_NAME)) { throw new IllegalArgumentException("Element is not a mycore user element."); } try { Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); return (MCRUser) unmarshaller.unmarshal(new JDOMSource(element)); } catch (JAXBException e) { throw new MCRException("Exception while transforming Element to MCRUser.", e); } }
/** * Builds an MCRRole instance from the given element. * @param element as generated by {@link #buildExportableXML(MCRRole)}. */ public static MCRRole buildMCRRole(Element element) { if (!element.getName().equals(ROLE_ELEMENT_NAME)) { throw new IllegalArgumentException("Element is not a mycore role element."); } try { Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); return (MCRRole) unmarshaller.unmarshal(new JDOMSource(element)); } catch (JAXBException e) { throw new MCRException("Exception while transforming Element to MCRUser.", e); } }
public static MCRUserAttributeMapper instance(Element attributeMapping) { try { JAXBContext jaxb = JAXBContext.newInstance(Mappings.class.getPackage().getName(), Mappings.class.getClassLoader()); Unmarshaller unmarshaller = jaxb.createUnmarshaller(); Mappings mappings = (Mappings) unmarshaller.unmarshal(new JDOMSource(attributeMapping)); MCRUserAttributeMapper uam = new MCRUserAttributeMapper(); uam.attributeMapping.putAll(mappings.getAttributeMap()); return uam; } catch (Exception e) { return null; } }
public Source resolve(String href, String base) throws TransformerException { try { String code = href.split(":")[1]; MCRLanguage language = MCRLanguageFactory.instance().getLanguage(code); Document doc = new Document(buildXML(language)); return new JDOMSource(doc); } catch (Exception ex) { throw new TransformerException(ex); } }
/** * Parse a email from given {@link Element}. * * @param xml the email * @return the {@link EMail} object */ public static EMail parseXML(final Element xml) { try { final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); return (EMail) unmarshaller.unmarshal(new JDOMSource(xml)); } catch (final JAXBException e) { throw new MCRException("Exception while transforming Element to EMail.", e); } }
/** * Returns access controll rules as XML */ public Source resolve(String href, String base) throws TransformerException { String key = href.substring(href.indexOf(":") + 1); LOGGER.debug("Reading xml from query result using key :{}", key); String[] param; StringTokenizer tok = new StringTokenizer(key, "&"); Hashtable<String, String> params = new Hashtable<>(); while (tok.hasMoreTokens()) { param = tok.nextToken().split("="); params.put(param[0], param[1]); } String action = params.get(ACTION_PARAM); String objId = params.get(OBJECT_ID_PARAM); if (action == null || objId == null) { return null; } Element container = new Element("servacls").setAttribute("class", "MCRMetaAccessRule"); if (action.equals("all")) { for (String permission : MCRAccessManager.getPermissionsForID(objId)) { // one pool Element under access per defined AccessRule in // Pool // for (Object-)ID addRule(container, permission, MCRAccessManager.getAccessImpl().getRule(objId, permission)); } } else { addRule(container, action, MCRAccessManager.getAccessImpl().getRule(objId, action)); } return new JDOMSource(container); }
/** * returns a classification in a specific format. Syntax: * <code>classification:{editor[Complete]['['formatAlias']']|metadata}:{Levels}[:noEmptyLeaves]:{parents| * children}:{ClassID}[:CategID] formatAlias: MCRConfiguration property * MCR.UURResolver.Classification.Format.FormatAlias * * @param href * URI in the syntax above * @return the root element of the XML document * @see MCRCategoryTransformer */ public Source resolve(String href, String base) throws TransformerException { LOGGER.debug("start resolving {}", href); String cacheKey = getCacheKey(href); Element returns = categoryCache.getIfUpToDate(cacheKey, getSystemLastModified()); if (returns == null) { returns = getClassElement(href); if (returns != null) { categoryCache.put(cacheKey, returns); } } return new JDOMSource(returns); }
@Override public Source resolve(String href, String base) throws TransformerException { String target = href.substring(href.indexOf(":") + 1); try { return MCRURIResolver.instance().resolve(target, base); } catch (Exception ex) { LOGGER.debug("Caught {}. Put it into XML to process in XSL!", ex.getClass().getName()); Element exception = new Element("exception"); Element message = new Element("message"); Element stacktraceElement = new Element("stacktrace"); stacktraceElement.setAttribute("space", "preserve", Namespace.XML_NAMESPACE); exception.addContent(message); exception.addContent(stacktraceElement); message.setText(ex.getMessage()); try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { ex.printStackTrace(pw); stacktraceElement.setText(pw.toString()); } catch (IOException e) { throw new MCRException("Error while writing Exception to String!", e); } return new JDOMSource(exception); } }
@Override public Source resolve(String href, String base) throws TransformerException { String includePart = href.substring(href.indexOf(":") + 1); Namespace xslNamespace = Namespace.getNamespace("xsl", "http://www.w3.org/1999/XSL/Transform"); Element root = new Element("stylesheet", xslNamespace); root.setAttribute("version", "1.0"); // get the parameters from mycore.properties String propertyName = "MCR.URIResolver.xslIncludes." + includePart; List<String> propValue = Collections.emptyList(); if (includePart.startsWith("class.")) { MCRXslIncludeHrefs incHrefClass = MCRConfiguration.instance() .getInstanceOf(propertyName); propValue = incHrefClass.getHrefs(); } else { propValue = MCRConfiguration.instance().getStrings(propertyName, propValue); } for (String include : propValue) { // create a new include element Element includeElement = new Element("include", xslNamespace); includeElement.setAttribute("href", include); root.addContent(includeElement); LOGGER.info("Resolved XSL include: {}", include); } return new JDOMSource(root); }
@Override public Source resolve(String href, String base) throws TransformerException { String importXSL = MCRXMLFunctions.nextImportStep(href.substring(href.indexOf(':') + 1)); if (importXSL.isEmpty()) { LOGGER.info("End of import queue: {}", href); Namespace xslNamespace = Namespace.getNamespace("xsl", "http://www.w3.org/1999/XSL/Transform"); Element root = new Element("stylesheet", xslNamespace); root.setAttribute("version", "1.0"); return new JDOMSource(root); } LOGGER.info("xslImport importing {}", importXSL); return fallback.resolve("resource:xsl/" + importXSL, base); }
private Source getSource(MCRStoredMetadata retrieve) throws IOException { Element e = new Element("versions"); Element v = new Element("version"); e.addContent(v); v.setAttribute("date", MCRXMLFunctions.getISODate(retrieve.getLastModified(), null)); return new JDOMSource(e); }
private Source getSource(List<MCRMetadataVersion> versions) { Element e = new Element("versions"); for (MCRMetadataVersion version : versions) { Element v = new Element("version"); v.setAttribute("user", version.getUser()); v.setAttribute("date", MCRXMLFunctions.getISODate(version.getDate(), null)); v.setAttribute("r", Long.toString(version.getRevision())); v.setAttribute("action", Character.toString(version.getType())); e.addContent(v); } return new JDOMSource(e); }
public static String xmlOutputter(Document doc, String xslt, HashMap<String,String> params) throws IOException { String result = null; try { Processor processor = new Processor(false); XdmNode source = processor.newDocumentBuilder().build(new JDOMSource( doc )); Serializer out = new Serializer(); out.setOutputProperty(Serializer.Property.METHOD, "xml"); out.setOutputProperty(Serializer.Property.INDENT, "yes"); StringWriter buffer = new StringWriter(); out.setOutputWriter(new PrintWriter( buffer )); XsltCompiler xsltCompiler = processor.newXsltCompiler(); XsltExecutable exp = xsltCompiler.compile(new StreamSource(xslt)); XsltTransformer trans = exp.load(); trans.setInitialContextNode(source); trans.setDestination(out); if (params != null) { for (String p : params.keySet()) { trans.setParameter(new QName(p), new XdmAtomicValue(params.get(p))); } } trans.transform(); result = buffer.toString(); } catch (SaxonApiException e) { e.printStackTrace(); } return result; }
@Test public void test() throws Exception { WebServiceTemplate template = new WebServiceTemplate(); SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory(); messageFactory.setSoapVersion(SoapVersion.SOAP_12); messageFactory.afterPropertiesSet(); template.setMessageFactory(messageFactory); CryptoFactoryBean cryptoFactory = new CryptoFactoryBean(); cryptoFactory.setKeyStoreLocation(new ClassPathResource("keystore.jks")); cryptoFactory.setKeyStorePassword("password"); cryptoFactory.afterPropertiesSet(); Crypto crypto = cryptoFactory.getObject(); SAML2CallbackHandler samlCallbackHandler = new SAML2CallbackHandler(crypto, "selfsigned"); SAMLIssuerImpl issuer = new SAMLIssuerImpl(); issuer.setIssuerCrypto(crypto); issuer.setIssuerKeyName("selfsigned"); issuer.setIssuerKeyPassword("password"); issuer.setIssuerName("selfsigned"); issuer.setSendKeyValue(false); issuer.setSignAssertion(true); issuer.setCallbackHandler(samlCallbackHandler); Wss4jSecurityInterceptor securityInterceptor = new Wss4jSecurityInterceptor(); securityInterceptor.setSecurementActions("Timestamp SAMLTokenSigned"); securityInterceptor.setSecurementSignatureCrypto(crypto); securityInterceptor.setSecurementUsername("selfsigned"); securityInterceptor.setSecurementPassword("password"); securityInterceptor.setSamlIssuer(issuer); securityInterceptor.afterPropertiesSet(); template.setInterceptors(new ClientInterceptor[] {securityInterceptor}); template.afterPropertiesSet(); Element hello = new Element("Hello", "urn:jaminh:example"); template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult()); template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult()); template.sendSourceAndReceiveToResult("http://localhost:8080/spring-saml-example-war", new JDOMSource(hello), new JDOMResult()); }
@Override public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { sessionHolder.addSessionIdToSoapMessage((SoapMessage) message); transformer.transform(new JDOMSource(request), message.getPayloadResult()); }
/** * Returns the Realms JDOM document as a {@link Source} useful for transformation processes. */ static Source getRealmsSource() { reInitIfNeeded(); return new JDOMSource(realmsDocument); }
/** * The method read a MCRObject and use the transformer to write the data to a file. They are any steps to handel * errors and save the damaged data. * <ul> * <li>Read data for object ID in the MCRObject, add ACL's and store it as checked and transformed XML. Return true. * </li> * <li>If it can't find a transformer instance (no script file found) it store the checked data with ACL's native in * the file. Warning and return true.</li> * <li>If it get an exception while build the MCRObject, it try to read the XML blob and stor it without check and * ACL's to the file. Warning and return true.</li> * <li>If it get an exception while store the native data without check, ACÖ's and transformation it return a * warning and false.</li> * </ul> * * @param dir * the file instance to store * @param trans * the XML transformer * @param nid * the MCRObjectID * @return true if the store was okay (see description), else return false * @throws TransformerException * @throws IOException * @throws MCRException * @throws SAXParseException */ private static boolean exportMCRObject(File dir, Transformer trans, String nid) throws TransformerException, IOException, MCRException, SAXParseException { MCRContent content; try { // if object do'snt exist - no exception is catched! content = MCRXMLMetadataManager.instance().retrieveContent(MCRObjectID.getInstance(nid)); } catch (MCRException ex) { return false; } File xmlOutput = new File(dir, nid + ".xml"); if (trans != null) { FileOutputStream out = new FileOutputStream(xmlOutput); StreamResult sr = new StreamResult(out); Document doc = MCRXMLParserFactory.getNonValidatingParser().parseXML(content); trans.transform(new org.jdom2.transform.JDOMSource(doc), sr); } else { content.sendTo(xmlOutput); } LOGGER.info("Object {} saved to {}.", nid, xmlOutput.getCanonicalPath()); return true; }
private static void xslt(String objectId, String xslFilePath, boolean force) throws IOException, JDOMException, SAXException, URISyntaxException, TransformerException, MCRPersistenceException, MCRAccessException { File xslFile = new File(xslFilePath); URL xslURL; if (!xslFile.exists()) { try { xslURL = new URL(xslFilePath); } catch (MalformedURLException e) { LOGGER.error("XSL parameter is not a file or URL: {}", xslFilePath); return; } } else { xslURL = xslFile.toURI().toURL(); } MCRObjectID mcrId = MCRObjectID.getInstance(objectId); Document document = MCRXMLMetadataManager.instance().retrieveXML(mcrId); // do XSL transform TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setErrorListener(MCRErrorListener.getInstance()); transformerFactory.setURIResolver(MCRURIResolver.instance()); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(MCREntityResolver.instance()); SAXSource styleSource = new SAXSource(xmlReader, new InputSource(xslURL.toURI().toString())); Transformer transformer = transformerFactory.newTransformer(styleSource); for (Entry<String, String> property : MCRConfiguration.instance().getPropertiesMap().entrySet()) { transformer.setParameter(property.getKey(), property.getValue()); } transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); JDOMResult result = new JDOMResult(); transformer.transform(new JDOMSource(document), result); Document resultDocument = Objects.requireNonNull(result.getDocument(), "Could not get transformation result"); String originalName = document.getRootElement().getName(); String resultName = resultDocument.getRootElement().getName(); if (!force && !originalName.equals(resultName)) { LOGGER.error("{}: root name '{}' does not match result name '{}'.", objectId, originalName, resultName); return; } // update on diff if (MCRXMLHelper.deepEqual(document, resultDocument)) { return; } if(resultName.equals(MCRObject.ROOT_NAME)) { MCRMetadataManager.update(new MCRObject(resultDocument)); } else if(resultName.equals(MCRDerivate.ROOT_NAME)) { MCRMetadataManager.update(new MCRDerivate(resultDocument)); } else { LOGGER.error("Unable to transform '{}' because unknown result root name '{}'.", objectId, resultName); } }
@Override public Source getSource() { JDOMSource source = new JDOMSource(jdom); source.setSystemId(systemId); return source; }
@Override public Source resolve(String href, String base) throws TransformerException { String help = href.substring(href.indexOf(":") + 1); String stylesheets = new StringTokenizer(help, ":").nextToken(); String target = help.substring(help.indexOf(":") + 1); String subUri = target.substring(target.indexOf(":") + 1); if (subUri.length() == 0) { return new JDOMSource(new Element("null")); } Map<String, String> params; StringTokenizer tok = new StringTokenizer(stylesheets, "?"); stylesheets = tok.nextToken(); if (tok.hasMoreTokens()) { params = getParameterMap(tok.nextToken()); } else { params = Collections.emptyMap(); } Source resolved = MCRURIResolver.instance().resolve(target, base); try { if (resolved != null) { if (resolved.getSystemId() == null) { resolved.setSystemId(target); } MCRSourceContent content = new MCRSourceContent(resolved); MCRXSLTransformer transformer = getTransformer(stylesheets.split(",")); MCRParameterCollector paramcollector = MCRParameterCollector.getInstanceFromUserSession(); paramcollector.setParameters(params); MCRContent result = transformer.transform(content, paramcollector); return result.getSource(); } else { LOGGER.debug("MCRXslStyleResolver returning empty xml"); return new JDOMSource(new Element("null")); } } catch (IOException e) { Throwable cause = e.getCause(); while (cause != null) { if (cause instanceof TransformerException) { throw (TransformerException) cause; } cause = cause.getCause(); } throw new TransformerException(e); } }
@Override public Source resolve(String href, String base) throws TransformerException { String help = href.substring(href.indexOf(":") + 1); String transformerId = new StringTokenizer(help, ":").nextToken(); String target = help.substring(help.indexOf(":") + 1); String subUri = target.substring(target.indexOf(":") + 1); if (subUri.length() == 0) { return new JDOMSource(new Element("null")); } Map<String, String> params; StringTokenizer tok = new StringTokenizer(transformerId, "?"); transformerId = tok.nextToken(); if (tok.hasMoreTokens()) { params = getParameterMap(tok.nextToken()); } else { params = Collections.emptyMap(); } Source resolved = MCRURIResolver.instance().resolve(target, base); try { if (resolved != null) { MCRSourceContent content = new MCRSourceContent(resolved); MCRContentTransformer transformer = MCRLayoutTransformerFactory.getTransformer(transformerId); MCRContent result; if (transformer instanceof MCRParameterizedTransformer) { MCRParameterCollector paramcollector = MCRParameterCollector.getInstanceFromUserSession(); paramcollector.setParameters(params); result = ((MCRParameterizedTransformer) transformer).transform(content, paramcollector); } else { result = transformer.transform(content); } return result.getSource(); } else { LOGGER.debug("MCRLayoutStyleResolver returning empty xml"); return new JDOMSource(new Element("null")); } } catch (Exception e) { if (e instanceof TransformerException) { throw (TransformerException) e; } Throwable cause = e.getCause(); while (cause != null) { if (cause instanceof TransformerException) { throw (TransformerException) cause; } cause = cause.getCause(); } throw new TransformerException(e); } }
@Override public Source resolve(String arg0, String arg1) throws TransformerException { return new JDOMSource(new Element("empty")); }
/** * Do the xsl transformation * * @param p_KNXProjectPath * The path to the unzipped project * @param p_TransformFile * The stream to the xsl file * @param p_OutputFilePath * The path where the xml file has to be written * @throws Exception */ private static void generateXML(String p_KNXProjectPath, InputStream p_TransformFile, String p_OutputFilePath) throws Exception { // Find the P-**** directory File l_path = new File(p_KNXProjectPath); File[] l_dirs = l_path.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.isDirectory() && pathname.getName().startsWith("P-")) return true; return false; } }); if (l_dirs.length == 0) throw new Exception("Config file 0.xml not found"); JDOMResult l_documentResult = new JDOMResult(); Document l_document = null; long first = System.currentTimeMillis(); // Copy the xsl file into the KNX project directory copyfile(p_TransformFile, p_KNXProjectPath + "/KNXTransformer.xsl"); // Load the xsl file to create a transformer TransformerFactory l_factory = TransformerFactory.newInstance(); Transformer l_transformer = l_factory.newTransformer(new StreamSource( p_KNXProjectPath + "/KNXTransformer.xsl")); long second = System.currentTimeMillis(); logger.debug("Load xsl " + (second - first)); // Load the source xml document SAXBuilder l_sax = new SAXBuilder(); Document l_input = l_sax.build(new File(l_dirs[0].getAbsolutePath() + "/0.xml")); long third = System.currentTimeMillis(); logger.debug("Load xml " + (third - second)); l_transformer.transform(new JDOMSource(l_input), l_documentResult); long fourth = System.currentTimeMillis(); logger.debug("Transform xsl " + (fourth - third)); // Write the result into the destination file l_document = l_documentResult.getDocument(); XMLOutputter l_outputter = new XMLOutputter(Format.getPrettyFormat()); l_outputter.output(l_document, new FileOutputStream(p_OutputFilePath)); long fifth = System.currentTimeMillis(); logger.debug("Write output " + (fifth - fourth)); }
/** * Reads XML from URIs of type session:key. The method MCRSession.get( key ) is called and must return a JDOM * element. * * @see org.mycore.common.MCRSession#get(Object) * @param href * the URI in the format session:key * @return the root element of the xml document */ @Override public Source resolve(String href, String base) throws TransformerException { String key = href.substring(href.indexOf(":") + 1); LOGGER.debug("Reading xml from session using key {}", key); Element value = (Element) MCRSessionMgr.getCurrentSession().get(key); return new JDOMSource(value.clone()); }
/** * Sets the name space on xml stream. * * @param in * the in * @param nameSpace * the name space * @return the source * @throws Exception * the exception */ private static Source setNameSpaceOnXmlStream(final InputStream in, final String nameSpace) throws Exception { final SAXBuilder sb = new SAXBuilder(new XMLReaderSAX2Factory(false)); final Document doc = sb.build(in); doc.getRootElement().setNamespace(Namespace.getNamespace(nameSpace)); return new JDOMSource(doc); }
/** * transforms a jdom Document via XSLT. * * @param in Document input * @param transformer Transformer handling the transformation process * @return the transformation result as jdom Document * @throws TransformerException if transformation fails */ public static Document transform(Document in, Transformer transformer) throws TransformerException { JDOMResult out = new JDOMResult(); transformer.transform(new JDOMSource(in), out); return out.getDocument(); }