Regarding XML Schema on Linux
Amisha Popat <amisha.popat <at> gmail.com>
2007-11-01 21:07:28 GMT
Hi,
I have an xml for which I have written the XSD. The validation code is my servlet. My XML is not able to locate my XSD. They both are in the same directory.
The servlet contains the method name validateCurrenciesXML which contains the validation code.
The app server is weblogic. My classpath contains xerces.jar. JDK version is j2sdk1.4.2_13
Please find attached all the requried files.
Please help
Thanks & Regards,
Amisha
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!--
Currencies.xml
This is the XML Schema used by Currencies.xml
Author: Amisha Popat
-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ups.com/CurrenciesSchema"
xmlns:tns="http://www.ups.com/CurrenciesSchema">
<xs:element name="currencies" type="Currencies"/>
<xs:complexType name="Currencies" >
<xs:sequence>
<xs:element name="currency" type="CurrencyType" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="CurrencyType" >
<xs:attribute name="description" type="xs:string" use="required"/>
<xs:attribute name="alpha" type="xs:string" use="required"/>
<xs:attribute name="numeric" type="xs:string" use="required"/>
<xs:attribute name="decimalPlaces" type="xs:integer" use="required"/>
</xs:complexType>
</xs:schema>
package com.ups.paymentcomponent;
import javax.servlet.http.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.*;
import java.util.*;
import com.ups.webappcommon.logging.log4jcompatible.*;
import com.ups.paymentcomponent.fdmspaymancassette.PCSConfigurator;
import org.apache.commons.digester.*;
import org.apache.commons.collections.*;
import com.ups.paymentcomponent.fdmspaymancassette.Client;
import com.ups.paymentcomponent.fdmspaymancassette.ClientCurrency;
import com.ups.paymentcomponent.fdmspaymancassette.ClientCard;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.SAXParseException;
public class PCSCurrencyServlet extends HttpServlet
{
public static final Logger logger = Logger.getLogger
("com.ups.paymentcomponent.PCSCurrencyServlet");
private static HashMap cardAllow = new HashMap();
private static HashMap cardDeny = new HashMap();
private static Enumeration enumAllow;
PCSConfigurator clientConfigurations = null;
String clientConfigDir = null;
String currenciesConfigFile = null;
String currenciesXsdFile = null;
//Variables added for validating the XML through Schema
String parserClass = "org.apache.xerces.parsers.SAXParser";
String validationFeature
= "http://xml.org/sax/features/validation";
String schemaFeature
= "http://apache.org/xml/features/validation/schema";
public void init(ServletConfig sc) throws ServletException
{
try
{
logger.log(UPSLevel.INFO,"Begin CurrencyServlet Initializing Payment Server");
Properties props = new Properties();
props.load(new FileInputStream(System.getProperty(("pcs.currencyservlet.config.file"))));
clientConfigDir = props.getProperty("clientConfigDir");
currenciesConfigFile = props.getProperty("currenciesConfigFile");
currenciesXsdFile = props.getProperty("currenciesXsdFile");
logger.log(UPSLevel.INFO, "testing the schema validation");
//Method invoked to validate the currecies.xml file.
validateCurrenciesXML(currenciesConfigFile);
//Method invoked to validate the client Config xml files.
validateClientXML();
readClientConfigData();
readCurrencies();
clientConfigurations.setFast();
Properties propAllow = new Properties();
Enumeration enumAllow = propAllow.keys();
List allowList;
propAllow.load(new FileInputStream(System.getProperty("pcs.cards.allow.file")));
while (enumAllow.hasMoreElements()) {
String propName = (String) enumAllow.nextElement();
String tmp = (String)propAllow.getProperty(propName);
allowList = new ArrayList();
StringTokenizer st = new StringTokenizer(tmp, ":");
cardAllow.put(propName, allowList);
while (st.hasMoreTokens()) allowList.add(st.nextToken());
}
Properties propDeny = new Properties();
Enumeration enumDeny = propDeny.keys();
List denyList;
propDeny.load(new FileInputStream(System.getProperty("pcs.cards.deny.file")));
while (enumDeny.hasMoreElements()) {
String propName = (String) enumDeny.nextElement();
String tmp = (String)propDeny.getProperty(propName);
denyList = new ArrayList();
StringTokenizer st = new StringTokenizer(tmp, ":");
cardDeny.put(propName, denyList);
while (st.hasMoreTokens()) denyList.add(st.nextToken());
}
logger.log(UPSLevel.INFO,"End Servlet Initializing Payment Server");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void doGet(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,java.io.IOException
{
PrintWriter out = null;
String cr = "\r\n";
StringBuffer dtd = new StringBuffer();
try
{
out = resp.getWriter();
dtd.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + cr);
dtd.append("<!DOCTYPE merchantdata [<!ELEMENT merchantdata (currency)*>" + cr);
dtd.append("<!ELEMENT currency (code,codeAlpha,floorlimit,decimalPlaces,cards)*>" + cr);
dtd.append("<!ELEMENT code (#PCDATA)>" + cr);
dtd.append("<!ELEMENT codeAlpha (#PCDATA)>" + cr);
dtd.append("<!ELEMENT floorlimit (#PCDATA)>" + cr);
dtd.append("<!ELEMENT decimalPlaces (#PCDATA)>" + cr);
dtd.append("<!ELEMENT cards (cardtype+)>" + cr);
dtd.append("<!ELEMENT cardtype (#PCDATA)>" + cr);
dtd.append("<!ATTLIST cardtype" + cr);
dtd.append(" merchantid CDATA #REQUIRED" + cr);
dtd.append(">" + cr);
dtd.append("]>" + cr);
Client c = clientConfigurations.getClient(req.getParameter("applicationId"));
if (c == null)
{
throw new Exception("Invalid Client");
}
String country = req.getParameter("country");
StringBuffer sb = new StringBuffer();
Vector clientCurrs = c.getCurrencies();
int cSize = clientCurrs.size();
sb.append("<merchantdata>" + cr);
for (int j=0;j<cSize;j++)
{
sb.append("<currency>" + cr);
ClientCurrency curr =
(ClientCurrency)clientCurrs.elementAt(j);
sb.append
("<code>" +
clientConfigurations.getCurrencyNumeric
(curr.getAlphaCode())
+ "</code>" + cr);
sb.append("<codeAlpha>" + curr.getAlphaCode() +
"</codeAlpha>" + cr);
sb.append("<floorlimit>" + curr.getFloorLimit() +
"</floorlimit>" + cr);
sb.append("<decimalPlaces>" +
clientConfigurations.getCurrencyDecimalPlaces
(curr.getAlphaCode()) +
"</decimalPlaces>" + cr);
Vector cards = curr.getCards();
Vector temp = new Vector();
int cardsSize = cards.size();
sb.append("<cards>" + cr);
for (int x=0;x<cardsSize;x++)
{
ClientCard cc = (ClientCard)cards.elementAt(x);
//RFC 3259 - Added Country
boolean allowCard = false;
if (country == null) {
allowCard = true;
}
else {
List allow = (List)cardAllow.get(cc.getName());
List deny = (List)cardDeny.get(cc.getName());
/*
* Filter the card list by country.
* If there is NOT an allow list for the card, or there is an allow list for the card and the country
* matches then return the card.
* However, if there is NOT a deny list for the card, or there is a deny list for the card,
* and the country matches then do NOT return the card.
*/
if (((allow == null) || allow.contains(country) )
&& ((deny == null) || !(deny.contains(country))) ) {
allowCard = true;
}
}
sb.append("<cardtype>");
sb.append(cc.getName() + " merchantid=");
if (!allowCard) {
sb.append("XXXXXXXXXXX");
}
else if (cc.getEnabled())
{
sb.append("00000000000");
}
else
{
sb.append("ZZZZZZZZZZZ");
}
sb.append("</cardtype>" + cr);
}
sb.append("</cards>" + cr);
sb.append("</currency>" + cr);
}
sb.append("</merchantdata>" + cr);
out.print(dtd.toString());
out.print(sb.toString());
out.close();
}
catch(Exception e)
{
StringBuffer sb = new StringBuffer();
sb.append("<merchantdata>" + cr);
sb.append("</merchantdata>" + cr);
out.print(dtd.toString());
out.print(sb.toString());
logger.log
(UPSLevel.SEVERE,"doGet() Error: " + e.toString());
}
}
void readClientConfigData() throws Exception
{
try
{
clientConfigurations = new PCSConfigurator();
File configDir = new File(clientConfigDir);
if (configDir.isDirectory())
{
String [] clientConfigFiles = configDir.list();
for (int i=0;i<clientConfigFiles.length;i++)
{
File temp = new File
(clientConfigDir,clientConfigFiles[i]);
if (temp.isFile() && temp.getName().endsWith(".xml"))
{
Digester digester = new Digester();
digester.push(clientConfigurations);
digester.addObjectCreate("clientdata/client",
"com.ups.paymentcomponent.fdmspaymancassette.Client");
digester.addSetProperties("clientdata/client");
digester.addSetNext
("clientdata/client","addClient",
"com.ups.paymentcomponent.fdmspaymancassette.Client");
digester.addObjectCreate("clientdata/client/currency",
"com.ups.paymentcomponent.fdmspaymancassette.ClientCurrency");
digester.addSetProperties("clientdata/client/currency");
digester.addSetNext
("clientdata/client/currency","addClientCurrency",
"com.ups.paymentcomponent.fdmspaymancassette.ClientCurrency");
digester.addCallMethod("clientdata/client/currency/floorLimit","setFloorLimit", 1);
digester.addCallParam("clientdata/client/currency/floorLimit",
0);
digester.addCallMethod("clientdata/client/currency/divisionNumber","setDivisionNumber", 1);
digester.addCallParam("clientdata/client/currency/divisionNumber", 0);
digester.addObjectCreate("clientdata/client/currency/cards/cardType",
"com.ups.paymentcomponent.fdmspaymancassette.ClientCard");
digester.addSetProperties("clientdata/client/currency/cards/cardType");
digester.addSetNext
("clientdata/client/currency/cards/cardType","addClientCard",
"com.ups.paymentcomponent.fdmspaymancassette.ClientCard");
logger.log(UPSLevel.INFO,"Digesting " + temp);
digester.parse(new FileInputStream(temp));
}
}
clientConfigurations.setFast();
}
}
catch(Exception e)
{
logger.log
(UPSLevel.SEVERE,"Error retrieving client config data: " + e.toString());
}
}
void readCurrencies() throws CCAuthorizationException
{
try
{
Digester digester = new Digester();
digester.push(clientConfigurations);
digester.addCallMethod("currencies/currency","addCurrency", 4);
digester.addCallParam("currencies/currency", 0,"description");
digester.addCallParam("currencies/currency", 1,"alpha");
digester.addCallParam("currencies/currency", 2,"numeric");
digester.addCallParam("currencies/currency", 3,"decimalPlaces");
digester.parse(new FileInputStream(currenciesConfigFile));
}
catch(Exception e)
{
e.printStackTrace();
logger.log
(UPSLevel.SEVERE,"Error retrieving currency data: " + e.toString());
}
}
//Method added for validating currecies.XML file with schema
private void validateCurrenciesXML(String currencyFile) throws Exception
{
logger.log(UPSLevel.INFO,"validateCurrenciesXML method is invoked:");
try {
XMLReader r = XMLReaderFactory.createXMLReader(parserClass);
r.setFeature(validationFeature,true);
r.setFeature(schemaFeature,true);
//r.setErrorHandler(new XmlErrorHandlerException());
logger.log(UPSLevel.INFO,"properties are to be set");
// r.setProperty("http://apache.org/xml/properties/external-NamespaceScemaLocation",
// "http://www.ups.com http://www.ups.com/currenciesXsdFile");
logger.log(UPSLevel.INFO,"properties are set");
r.parse(currencyFile);
logger.info("Currencies File"+ currencyFile.toString());
logger.log(UPSLevel.INFO, "Parse of the Currencies file is completed");
} catch (SAXParseException e) {
logger.log(UPSLevel.INFO, "SaxException thrown for currency file");
logger.log(UPSLevel.INFO," Public ID: "+e.getPublicId());
logger.log(UPSLevel.INFO," System ID: "+e.getSystemId());
logger.log(UPSLevel.INFO," Line number: "+e.getLineNumber());
logger.log(UPSLevel.INFO," Column number: "+e.getColumnNumber());
logger.log(UPSLevel.INFO," Message: "+e.getMessage());;
} catch (IOException e) {
logger.log(UPSLevel.INFO, "IOException thrown for currency file");
logger.log(UPSLevel.SEVERE,e.toString());
}
}
//Method added for validating client config XML files with schema
private void validateClientXML() throws Exception
{
logger.log(UPSLevel.INFO,"validateClientXML method is invoked:");
File SingleXmlFile = null;
try {
File configDir = new File(clientConfigDir);
if (configDir.isDirectory())
{
String [] clientConfigFiles = configDir.list();
for (int i=0;i<clientConfigFiles.length;i++)
{
SingleXmlFile = new File
(clientConfigDir,clientConfigFiles[i]);
if (SingleXmlFile.isFile() && SingleXmlFile.getName().endsWith(".xml"))
{
XMLReader r = XMLReaderFactory.createXMLReader(parserClass);
r.setFeature(validationFeature,true);
r.setFeature(schemaFeature,true);
//r.setErrorHandler(new XmlErrorHandlerException());
r.parse(SingleXmlFile.toString());
logger.log(UPSLevel.INFO,"Parsing of " + SingleXmlFile.getName()+ " file is completed");
}
}
}
} catch (SAXParseException e) {
logger.log(UPSLevel.INFO, "SaxException thrown for " + SingleXmlFile.getName()+ "client file");
logger.log(UPSLevel.INFO," Public ID: "+e.getPublicId());
logger.log(UPSLevel.INFO," System ID: "+e.getSystemId());
logger.log(UPSLevel.INFO," Line number: "+e.getLineNumber());
logger.log(UPSLevel.INFO," Column number: "+e.getColumnNumber());
logger.log(UPSLevel.INFO," Message: "+e.getMessage());
} catch (IOException e) {
logger.log(UPSLevel.INFO, "IOException thrown for client file");
logger.log(UPSLevel.SEVERE,e.toString());
}
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: j-users-unsubscribe <at> xerces.apache.org
For additional commands, e-mail: j-users-help <at> xerces.apache.org