001 package org.mactor.extensions.xml; 002 003 import java.io.File; 004 import java.io.IOException; 005 import java.io.StringReader; 006 import java.util.List; 007 008 import javax.xml.XMLConstants; 009 import javax.xml.transform.stream.StreamSource; 010 import javax.xml.validation.Schema; 011 import javax.xml.validation.SchemaFactory; 012 import javax.xml.validation.Validator; 013 014 import org.apache.log4j.Logger; 015 import org.mactor.brokers.Message; 016 import org.mactor.framework.ConfigException; 017 import org.mactor.framework.MactorException; 018 import org.mactor.framework.TestContext; 019 import org.mactor.framework.extensioninterface.ActionCommand; 020 import org.mactor.framework.spec.ProjectContext; 021 import org.xml.sax.SAXException; 022 023 public class AssertXmlValid implements ActionCommand { 024 private static Logger log = Logger.getLogger(AssertXmlValid.class); 025 public void perform(TestContext context, List<String> params) throws MactorException { 026 if (params.size() != 1) 027 throw new ConfigException("Invalid testspec. One parameter expected: [<the relative path to the XML schema that should be used to validate the last received message>]>"); 028 Message last = context.getLastIncomingMessage(); 029 if (last == null) 030 throw new MactorException("There is no incoming message to validate"); 031 log.debug("AssertXmlValid:'" + params.get(0) + "'"); 032 validateMessage(last, params.get(0)); 033 } 034 public void validateMessage(Message message, String schemaPath) throws MactorException { 035 Validator v = getSchema(schemaPath).newValidator(); 036 try { 037 v.validate(new StreamSource(new StringReader(message.getContent()))); 038 } catch (IOException ioe) { 039 throw new RuntimeException("Unable to read the last received message. Error:" + ioe.getMessage(), ioe); 040 } catch (SAXException se) { 041 throw new MactorException("The message is not valid according to the '" + schemaPath + "' schema. Details:" + se.getMessage(), se); 042 } 043 } 044 private Schema getSchema(String schemaPath) throws MactorException { 045 File absoluteShemaPath = ProjectContext.getGlobalInstance().getAbsolutePath(schemaPath); 046 if (!absoluteShemaPath.exists()) 047 throw new ConfigException("The specifed XML schema '" + absoluteShemaPath.getAbsolutePath() + "' does not exist"); 048 final String sl = XMLConstants.W3C_XML_SCHEMA_NS_URI; 049 SchemaFactory factory = SchemaFactory.newInstance(sl); 050 try { 051 return factory.newSchema(absoluteShemaPath); 052 } catch (SAXException se) { 053 throw new ConfigException("The specifed XML schema '" + absoluteShemaPath.getAbsolutePath() + "' could not be loaded. Problem:" + se.getMessage(), se); 054 } 055 } 056 }