Merge remote-tracking branch 'origin/main' into USRE-139

This commit is contained in:
YuCheng Hu 2024-02-02 22:50:52 -05:00
commit 1cd4b1a009
Signed by: honeymoose
GPG Key ID: D74AE0B33A8002EC
52 changed files with 4502 additions and 0 deletions

View File

@ -5,6 +5,7 @@
The Rets-Io RETS Client - Java is a library used to access data on RETS compliant servers.
## Links and related projects
| Project | URL | NOTE |

1
validation/README.md Normal file
View File

@ -0,0 +1 @@
# rets-io-validation

158
validation/pom.xml Normal file
View File

@ -0,0 +1,158 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ossez.usreio</groupId>
<artifactId>rets-io-validation</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.usreio</groupId>
<artifactId>rets-io</artifactId>
<version>0.0.2-SNAPSHOT</version>
</parent>
<name>Rets-Io-Validation</name>
<description>Demo for Framework Orm Factory Query Data</description>
<url>https://github.com/USRealEstate/rets-io-validation.git</url>
<developers>
<developer>
<name>YuCheng Hu</name>
<id>honeymoose</id>
<email>huyuchengus@gmail.com</email>
<timezone>-5</timezone>
<organization>Open Source</organization>
<roles>
<role>Sr. Java Developer</role>
</roles>
</developer>
</developers>
<dependencies>
<dependency>
<groupId>com.ossez.usreio</groupId>
<artifactId>rets-io-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<version>2.7.2</version>
</dependency>
<!-- TESTS -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.ossez.usreio</groupId>
<artifactId>rets-io-common</artifactId>
<version>0.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.ossez.usreio</groupId>
<artifactId>rets-io-common</artifactId>
<version>0.0.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>package</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<release>${java.version}</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<!-- Generic properties -->
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Logging -->
<slf4j.version>1.7.30</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<log4j2.version>2.2</log4j2.version>
<!-- APACHE COMMONS-->
<commons-io.version>2.11.0</commons-io.version>
<commons-lang.version>2.6</commons-lang.version>
<commons-lang3.version>3.11</commons-lang3.version>
<commons-cli.version>1.4</commons-cli.version>
<maven-war-plugin.version>3.0.0</maven-war-plugin.version>
<!-- UTILS -->
<guava.version>30.1.1-jre</guava.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.3.5.Final</hibernate.version>
<!-- Bean validation -->
<hibernate-validator.version>4.3.1.Final</hibernate-validator.version>
<!-- Database access -->
<tomcat-jdbc.version>7.0.42</tomcat-jdbc.version>
<ehcache.version>2.6.8</ehcache.version>
<hsqldb.version>2.3.2</hsqldb.version>
<!-- DATA STRUCTURES -->
<jackson.version>2.12.4</jackson.version>
<!-- Test -->
<hamcrest.version>2.2</hamcrest.version>
<hamcrest-all.version>1.3</hamcrest-all.version>
<!-- CDN & CLOUD -->
<jclouds.version>1.9.0</jclouds.version>
<modelmapper.version>2.4.4</modelmapper.version>
<lombok.version>1.18.20</lombok.version>
<moneta.version>1.3</moneta.version>
<jmh-core.version>1.33</jmh-core.version>
<exec-maven-plugin.version>3.0.0</exec-maven-plugin.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,142 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/OperatorMap.java,v 1.3 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation;
import org.realtor.rets.validation.operators.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.reflect.Modifier;
import java.net.*;
import java.util.*;
import java.util.Hashtable;
import java.util.jar.*;
import java.util.zip.*;
/**
* OperatorMap.java Created Aug 25, 2003
* <p>
* <p>
* Copyright 2003, Avantia inc.
*
* @author scohen
* @version $Revision: 1.3 $
*/
public class OperatorMap {
private final static Logger logger = LoggerFactory.getLogger(OperatorMap.class);
private static Hashtable map;
private static String packageName = "org.realtor.rets.validation.operators";
static {
map = new Hashtable();
getAllOperators();
}
/*
* Loads all operators in the org.realtor.rets.validation.operators package
*/
private synchronized static void getAllOperators() {
ClassLoader loader = OperatorMap.class.getClassLoader();
URL pkg = loader.getResource(packageName.replace('.', '/'));
File directory = new File(pkg.getFile());
String[] files = null;
if (directory.exists()) {
files = getClassListFromDirectory(directory);
} else {
files = getClassListFromJar(pkg);
}
for (int i = 0; i < files.length; i++) {
// removes the .class extension
String classname = files[i].substring(0, files[i].length() - 6);
try {
// Try to create an instance of the object
logger.debug("getAllOperators instantiating class= " + classname);
Object o = Class.forName(classname).newInstance();
if (o instanceof Operator) {
Operator oper = (Operator) o;
map.put(oper.getSymbol(), oper);
}
} catch (ClassNotFoundException cnfex) {
logger.error("error:" + classname, cnfex);
} catch (InstantiationException iex) {
logger.error("error: " + classname +
" We try to instantiate an interface or an object that does not have a default constructor ",
iex);
// We try to instantiate an interface
// or an object that does not have a
// default constructor
} catch (IllegalAccessException iaex) {
logger.error("error: " + classname + " The class is not public ",
iaex);
// The class is not public
}
}
}
public static Operator map(String operator) {
return (Operator) map.get(operator);
}
public static void main(String[] args) {
System.out.println(OperatorMap.map("+"));
}
private static String[] getClassListFromJar(URL pkg) {
String[] files = null;
try {
JarURLConnection conn = (JarURLConnection) pkg.openConnection();
JarFile file = conn.getJarFile();
Enumeration entries = file.entries();
ArrayList classList = new ArrayList();
while (entries.hasMoreElements()) {
JarEntry entry = (JarEntry) entries.nextElement();
String entryName = entry.getName().replace('/', '.');
logger.debug("entryName prior to add" + entryName);
logger.debug("packageName" + packageName);
if (entryName.startsWith(packageName) &&
entryName.endsWith("class")) {
logger.debug("adding entryName " + entryName);
classList.add(entryName);
}
}
files = (String[]) classList.toArray(new String[classList.size()]);
} catch (IOException io) {
logger.error("error creating jarfile ", io);
}
return files;
}
private static String[] getClassListFromDirectory(File directory) {
String[] files = directory.list();
for (int i = 0; i < files.length; i++) {
// we are only interested in .class files
if (files[i].endsWith(".class")) {
files[i] = packageName + "." + files[i];
logger.debug("getClassListFromDirectory file is " + files[i]);
}
}
return files;
}
}

View File

@ -0,0 +1,224 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/ParseTree.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation;
import org.realtor.rets.validation.operators.*;
import org.realtor.rets.validation.terms.*;
/**
* ParseTree.java Created Aug 22, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class ParseTree {
private ParseTree left = null;
private Operator operator = null;
private ParseTree right = null;
private Term term;
private ParseTree parent;
public ParseTree() {
}
public ParseTree(Term t) {
term = t;
}
public ParseTree(ParseTree l, ParseTree r) {
left = l;
right = r;
}
public ParseTree(ParseTree l, ParseTree r, Operator oper) {
left = l;
right = r;
operator = oper;
}
/**
* @return
*/
public ParseTree getLeft() {
return left;
}
/**
* @return
*/
public Operator getOperator() {
return operator;
}
/**
* @return
*/
public ParseTree getRight() {
return right;
}
/**
* @param tree
*/
public void setLeft(ParseTree tree) {
left = tree;
tree.setParent(this);
}
/**
* @param operator
*/
public void setOperator(Operator operator) {
this.operator = operator;
}
/**
* @param tree
*/
public void setRight(ParseTree tree) {
right = tree;
tree.setParent(this);
}
/**
* @return
*/
public Term getTerm() {
return term;
}
/**
* @param term
*/
public void setTerm(Term term) {
this.term = term;
}
public boolean isLeaf() {
return (left == null) && (right == null);
}
/**
* @return
*/
public ParseTree getParent() {
return parent;
}
/**
* @param tree
*/
public void setParent(ParseTree tree) {
parent = tree;
}
public Term execute() {
Term leftSide;
Term rightSide;
if (!left.isLeaf()) {
leftSide = left.execute();
} else {
leftSide = left.getTerm();
}
// our left is a leaf.
if (!right.isLeaf()) {
rightSide = right.execute();
} else {
rightSide = right.getTerm();
}
try {
return operator.apply(leftSide, rightSide);
} catch (InvalidTermException ite) {
System.out.println("Could not execute: " + ite.getMessage());
return null;
}
}
public String getExpression() {
StringBuffer expr = new StringBuffer();
printExpression(expr);
return expr.toString();
}
private void printExpression(StringBuffer sb) {
if (left != null) {
sb.append("( ");
left.printExpression(sb);
}
if (getOperator() != null) {
sb.append(getOperator().getSymbol());
} else {
if (getTerm() != null) {
sb.append(getTerm().getValue());
}
}
sb.append(" ");
if (right != null) {
right.printExpression(sb);
sb.append(" ) ");
}
}
public void print(int level, String side) {
if (left != null) {
left.print(level + 1, "left");
}
if (right != null) {
right.print(level + 1, "right");
}
System.out.println();
System.out.print("level: " + level + " ");
if (side.length() > 0) {
System.out.print(side + " side ");
}
if (getOperator() != null) {
System.out.print(getOperator());
} else {
System.out.print("Term:" + getTerm().getValue().toString());
}
}
public static void main(String[] args) throws Exception {
ParseTree root;
ParseTree valueOne = new ParseTree();
ParseTree valueTwo = new ParseTree();
ParseTree valueThree = new ParseTree();
ParseTree valueFour = new ParseTree();
ParseTree leftEquals;
ParseTree rightEquals;
valueOne.setTerm(new StringTerm("ListAgent"));
valueTwo.setTerm(new StringTerm("ListRecord"));
valueThree.setTerm(new DateTerm("2003-04-07"));
valueFour.setTerm(new DateTerm("2003-08-12"));
leftEquals = new ParseTree(valueOne, valueTwo, new EqualsOperator());
rightEquals = new ParseTree(valueThree, valueFour,
new LessThanOperator());
root = new ParseTree(leftEquals, rightEquals, new OrOperator());
System.out.println(rightEquals.execute());
root.print(0, "");
System.out.println();
System.out.println(root.getExpression());
//System.out.println(root.execute());
}
}

View File

@ -0,0 +1,335 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/RETSUpdateValidator.java,v 1.4 2005/03/30 21:41:53 ekovach Exp $ */
package org.realtor.rets.validation;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.transform.TransformerException;
import com.ossez.usreio.common.util.XMLUtils;
import org.apache.xpath.XPathAPI;
import org.realtor.rets.validation.terms.AbstractTerm;
import org.realtor.rets.validation.terms.DateTerm;
import org.realtor.rets.validation.terms.NumericTerm;
import org.realtor.rets.validation.terms.StringTerm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* RETSUpdateValidator.java Created Sep 26, 2003
* <p>
* <p>
* Copyright 2003, Avantia inc.
*
* @author scohen
* @version $Revision: 1.4 $
*/
public class RETSUpdateValidator {
// log4j category
private final static Logger logger = LoggerFactory.getLogger(RETSUpdateValidator.class);
protected static final String AGENT_CODE_KEY = "AGENT-CODE";
protected static final String USER_CLASS_KEY = "USER-CLASS";
protected static final String USER_LEVEL_KEY = "USER-LEVEL";
protected static final String USER_ID_KEY = "USER-ID";
private Document metaData;
private Hashtable validationExpressions;
private String updateResource;
private String updateClass;
private String updateType;
private Map oldValues;
private Map newValues;
private List fieldList = null;
private List errors;
private Map userInfo;
private Map symbolTable;
/**
* A HashMap of field types to Term class types.
*/
private static HashMap termTypeMap = new HashMap();
static {
// initialize the termTypeMap
termTypeMap.put("Date", DateTerm.class);
termTypeMap.put("Int", NumericTerm.class);
termTypeMap.put("Decimal", NumericTerm.class);
termTypeMap.put("Small", NumericTerm.class);
termTypeMap.put("Long", NumericTerm.class);
termTypeMap.put("Tiny", NumericTerm.class);
}
public RETSUpdateValidator() {
validationExpressions = new Hashtable();
userInfo = new Hashtable();
}
public RETSUpdateValidator(String resource,
String className, String type) {
this();
updateResource = resource;
updateClass = className;
updateType = type;
}
public List getUpdateFieldList() {
return fieldList;
}
public boolean hasErrors() {
return (errors != null) && (errors.size() > 0);
}
public void validate() {
ValidationExpressionEvaluator evaluator = new ValidationExpressionEvaluator();
Iterator iter = fieldList.iterator();
errors = new ArrayList();
Boolean correct = new Boolean(true);
while (iter.hasNext()) {
UpdateField field = (UpdateField) iter.next();
field.validate(symbolTable);
if (field.getError() != null) {
errors.add(field.getError());
}
}
}
public void setSymbolTable(Map table) {
// call parseEntries first because there aren't names like .TODAY. in the metadata.
Map symbols = parseEntries(table);
symbols.put(".TODAY.", new DateTerm());
symbols.put(".NOW.", new DateTerm(new Date()));
symbols.put(".EMPTY.", new StringTerm(""));
symbols.put(".USERCLASS.", userInfo.get(USER_CLASS_KEY));
symbols.put(".USERLEVEL.", userInfo.get(USER_LEVEL_KEY));
symbols.put(".USERID.", userInfo.get(USER_ID_KEY));
symbols.put(".AGENTCODE.", userInfo.get(AGENT_CODE_KEY));
symbolTable = symbols;
}
private Map parseEntries(Map table) {
HashMap rv = new HashMap();
RetsTokenParser parser = new RetsTokenParser();
for (Iterator iter = table.keySet().iterator(); iter.hasNext(); ) {
String key = (String) iter.next();
Object value = table.get(key);
String entry = null;
String fieldType = getFieldTypeBySystemName(key);
if (value instanceof String) {
entry = (String) value;
} else if (value instanceof String[]) {
entry = ((String[]) value)[0];
}
if ((entry != null) && (entry.length() > 0)) {
// get the term type class for the field type; assume StringTerm
// if it's not specifically mapped
Class termTypeClass = (Class) termTypeMap.get(fieldType);
if (termTypeClass == null) {
termTypeClass = StringTerm.class;
}
try {
Constructor constructor = termTypeClass.getConstructor(new Class[]{String.class});
AbstractTerm term = (AbstractTerm) constructor.newInstance(new Object[]{entry});
rv.put(key, term);
logger.debug("Added value: " + key + " = " + term);
} catch (Exception e) {
logger.error("Exception", e);
}
}
}
return rv;
}
/**
* Get the field type from the system name.
*
* @param systemName
* @return The field type from the system name.
*/
private String getFieldTypeBySystemName(String systemName) {
String fieldType = null;
String query = "//METADATA-RESOURCE/Resource[ResourceID=\"" +
updateResource + "\"]/METADATA-CLASS/Class[ClassName=\"" +
updateClass + "\"]/METADATA-TABLE[@Resource=\"" + updateResource +
"\" and @Class=\"" + updateClass + "\"]/Field[SystemName=\"" +
systemName + "\"]/DataType";
try {
Node dataType = XPathAPI.selectSingleNode(metaData.getFirstChild(),
query);
if (dataType != null) {
fieldType = dataType.getFirstChild().getNodeValue();
logger.debug("SystemName [" + systemName + "] type [" + fieldType + "]");
}
} catch (DOMException e) {
// TODO Auto-generated catch block
logger.error("error: ", e);
} catch (TransformerException e) {
// TODO Auto-generated catch block
logger.error("error: ", e);
}
return fieldType;
}
/**
* Sets the user information. This takes a comma delimited string
* of the type set by the login transaction. This string takes the following form
* user-id, user-level, user-class, agent-code.
*
* @param info
*/
public void setUserInfo(String info) {
String[] infoArr = info.split(",");
setUserInfoField(USER_ID_KEY, infoArr[0]);
setUserInfoField(USER_LEVEL_KEY, infoArr[1]);
setUserInfoField(USER_CLASS_KEY, infoArr[2]);
setUserInfoField(AGENT_CODE_KEY, infoArr[3]);
}
private void setUserInfoField(String fieldName, String fieldValue) {
if ("NULL".equals(fieldValue)) {
fieldValue = "";
}
userInfo.put(fieldName, fieldValue);
}
private void getFields() {
try {
String query = "//METADATA-RESOURCE/Resource[ResourceID=\"" +
updateResource + "\"]/METADATA-CLASS/Class[ClassName=\"" +
updateClass + "\"]/METADATA-UPDATE/UpdateType[UpdateName=\"" +
updateType + "\"]/METADATA-UPDATE_TYPE[@Resource=\"" +
updateResource + "\" and @Class=\"" + updateClass +
"\" and @Update=\"" + updateType + "\"]/UpdateField";
NodeList updateFields = XMLUtils.executeXpathQuery(metaData.getFirstChild(),
query);
fieldList = new ArrayList(updateFields.getLength());
for (int i = 0; i < updateFields.getLength(); i++) {
logger.debug("Update field# :" + i + "=" + updateFields.item(i));
UpdateField uf = new UpdateField(updateFields.item(i));
populateValidationExpression(uf, metaData.getFirstChild());
fieldList.add(uf);
}
// this sorts the update fields by sequence number.
Collections.sort(fieldList);
} catch (TransformerException e) {
logger.error("error: ", e);
}
}
/**
* @param uf
* @param root
*/
private void populateValidationExpression(UpdateField uf, Node root) {
if (uf.getValidationExpressions() != null) {
List expressions = uf.getValidationExpressions();
for (int j = 0; j < expressions.size(); j++) {
ValidationExpression expr = (ValidationExpression) expressions.get(j);
String query = "//METADATA-RESOURCE/Resource[ResourceID=\"" +
updateResource +
"\"]/METADATA-VALIDATION_EXPRESSION[@Resource=\"" +
updateResource +
"\"]/ValidationExpression[ValidationExpressionID=\"" +
expr.getID() + "\"]";
try {
Node validation = XPathAPI.selectSingleNode(root, query);
if (validation != null) {
NodeList subnodes = validation.getChildNodes();
String expressionType = null;
String expression = null;
for (int i = 0; i < subnodes.getLength(); i++) {
Node current = subnodes.item(i);
String nodeName = current.getNodeName();
if ("ValidationExpressionType".equals(nodeName)) {
expressionType = current.getChildNodes().item(0)
.getNodeValue();
} else if ("Value".equals(nodeName)) {
expression = current.getChildNodes().item(0)
.getNodeValue();
}
}
expr.setExpression(expression);
expr.setType(expressionType);
}
} catch (DOMException e) {
// TODO Auto-generated catch block
logger.error("error: ", e);
} catch (TransformerException e) {
// TODO Auto-generated catch block
logger.error("error: ", e);
}
//expressions.add(expr);
}
//uf.setValidationExpressions(expressions);
}
}
/**
* @return
*/
public Document getMetaData() {
return metaData;
}
/**
* @param document
*/
public void setMetaData(Document document) {
metaData = document;
getFields();
}
public void setMetaData(String xml) {
Document doc = XMLUtils.stringToDocument(xml);
setMetaData(doc);
}
/**
* @return
*/
public List getErrors() {
return errors;
}
/**
* @param list
*/
public void setErrors(List list) {
errors = list;
}
}

View File

@ -0,0 +1,299 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/RetsTokenParser.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation;
import org.realtor.rets.validation.operators.*;
import org.realtor.rets.validation.terms.*;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.util.Map;
import java.util.StringTokenizer;
/**
* RetsValidationTokenizer.java Created Sep 10, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class RetsTokenParser {
private StringReader expression;
private StringTokenizer st;
private String lookAheadToken = null;
private String singleOperators = "+-*/><=()!";
private TermFactory termFactory;
public RetsTokenParser() {
}
public RetsTokenParser(String expr) {
this();
setExpression(expr);
}
/**
* @param expr
*/
public void setExpression(String expr) {
expression = new StringReader(expr);
}
public Object nextToken() {
Object token = null;
int nextChar;
try {
if ((nextChar = expression.read()) >= 0) {
char next = (char) nextChar;
while (Character.isWhitespace(next)) {
nextChar = expression.read();
if (nextChar < 0) {
return null;
}
next = (char) nextChar;
}
if (singleOperators.indexOf(next) >= 0) {
token = getNextOperator(next);
} else if (next == '.') {
token = getDottedToken();
} else if (next == '"') {
token = readString();
} else if (next == 'P') {
// could be a date interval
token = readDateInterval();
if (token == null) {
token = readVariableTerm(next);
}
} else if (Character.isDigit(next)) {
// first see if it's a date. If it isn't, treat it like a number
token = readDate(next);
if (token == null) {
token = readNumeric(next);
}
} else {
// it must be a system name.
//token = new
token = readVariableTerm(next);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return token;
}
private Term readVariableTerm(char start)
throws IOException, InvalidTermException {
StringBuffer sb = new StringBuffer();
sb.append(start);
expression.mark(1);
int nextChar;
while ((nextChar = expression.read()) >= 0) {
char next = (char) nextChar;
if ((next == ' ') || (singleOperators.indexOf(next) > 0)) {
break;
} else {
sb.append(next);
}
}
VariableTerm vt = termFactory.newVariableTerm(sb.toString());
return (Term) vt;
}
private DateIntervalTerm readDateInterval() throws IOException {
DateIntervalTerm interval = null;
StringBuffer sb = new StringBuffer("P");
int nextChar;
expression.mark(1);
while ((nextChar = expression.read()) >= 0) {
char next = (char) nextChar;
if (Character.isLetterOrDigit(next)) {
sb.append(next);
} else {
break;
}
}
try {
interval = new DateIntervalTerm(sb.toString());
} catch (ParseException e) {
expression.reset();
}
return interval;
}
private StringTerm readString() throws IOException {
StringTerm term;
String quoted = readThrough('"');
term = new StringTerm(quoted.substring(0, quoted.length() - 1));
return term;
}
private DateTerm readDate(char start) throws IOException {
StringBuffer sb = new StringBuffer();
DateTerm rv = null;
expression.mark(1);
int next;
char nextChar;
char[] dateChars = new char[10];
dateChars[0] = start;
int numread = expression.read(dateChars, 1, 9);
if (numread != 9) {
expression.reset();
} else {
String dateStr = new String(dateChars);
if (dateStr.matches("\\d{4}-\\d{2}-\\d{2}")) {
try {
rv = new DateTerm(dateStr);
} catch (ParseException e) {
// since we've validated with a regex, this parse exception can't really happen.
e.printStackTrace();
}
} else {
expression.reset();
}
}
return rv;
}
private NumericTerm readNumeric(char start) throws IOException {
NumericTerm rv = null;
StringBuffer sb = new StringBuffer();
sb.append(start);
int next;
char nextChar;
expression.mark(1);
while ((next = expression.read()) >= 0) {
nextChar = (char) next;
if (Character.isDigit(nextChar)) {
sb.append(nextChar);
expression.mark(1);
} else {
expression.reset();
break;
}
}
try {
rv = new NumericTerm(Double.parseDouble(sb.toString()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
return rv;
}
private Object getDottedToken() throws IOException {
Object token = null;
String tokenString = "." + readThrough('.');
token = OperatorMap.map(tokenString);
if (token == null) {
// then it's one of those 'always there' variables
VariableTerm vt = termFactory.newVariableTerm(tokenString);
token = vt;
}
return token;
}
private Operator getNextOperator(char current) throws IOException {
expression.mark(2);
char nextChar = (char) expression.read();
char[] operStr = new char[2];
operStr[0] = current;
String operator;
if (nextChar == '=') {
operStr[1] = nextChar;
operator = new String(operStr, 0, 2);
} else {
expression.reset();
operator = new String(operStr, 0, 1);
}
return OperatorMap.map(operator);
}
private String readThrough(char stopChar) throws IOException {
StringBuffer sb = new StringBuffer();
int next;
while ((next = expression.read()) >= 0) {
char nextChar = (char) next;
sb.append(nextChar);
if (nextChar == stopChar) {
break;
}
}
return sb.toString();
}
public Term matchTerm(String token) {
if (token.length() == 10) {
// possible date
try {
return new DateTerm(token);
} catch (ParseException e) {
}
}
try {
return new NumericTerm(Long.parseLong(token));
} catch (NumberFormatException nfe) {
}
return new StringTerm(token);
}
/**
* @return
*/
public TermFactory getTermFactory() {
return termFactory;
}
/**
* @param factory
*/
public void setTermFactory(TermFactory factory) {
termFactory = factory;
}
}

View File

@ -0,0 +1,305 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/UpdateField.java,v 1.4 2005/03/30 21:41:53 ekovach Exp $ */
package org.realtor.rets.validation;
import org.apache.xpath.XPathAPI;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.Term;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.transform.TransformerException;
/**
* UpdateField.java Created Sep 26, 2003
* <p>
* <p>
* Copyright 2003, Avantia inc.
*
* @author scohen
* @version $Revision: 1.4 $
*/
public class UpdateField implements Comparable {
private final static Logger logger = LoggerFactory.getLogger(UpdateField.class);
private ValidationError error;
private int sequence;
private int[] attributes;
private String systemName;
private String validateHelpID;
private String validateExternalName;
private ArrayList validationExpressions;
private String def;
private String dataType;
public UpdateField(Node toBuild) {
init(toBuild);
}
/**
* @param toBuild
*/
private void init(Node toBuild) {
validationExpressions = new ArrayList();
try {
systemName = getElementValue(toBuild, "SystemName");
validateHelpID = getElementValue(toBuild, "ValidateHelpID");
try {
sequence = Integer.parseInt(getElementValue(toBuild, "Sequence"));
} catch (NumberFormatException e) {
sequence = 0;
}
attributes = parseAttributes(getElementValue(toBuild, "Attributes"));
validateExternalName = getElementValue(toBuild, "ValidateExternal");
initExpressions(toBuild);
def = getElementValue(toBuild, "Default");
} catch (Exception e) {
logger.error("error: ", e);
}
}
/**
* @param expression
* @throws TransformerException
*/
private void initExpressions(Node expression) throws TransformerException {
String idList = getElementValue(expression, "ValidationExpressionID");
if (idList != null) {
String[] expressionNames = idList.split(",");
System.out.println("For string " + idList +
" the split returned an array of length " + expressionNames.length);
for (int i = 0; i < expressionNames.length; i++) {
ValidationExpression current = new ValidationExpression(expressionNames[i]);
validationExpressions.add(current);
System.out.println(this.systemName + ".expressions[" + i + "]:" +
expressionNames[i]);
}
}
}
/**
* @param string
* @return
*/
private int[] parseAttributes(String string) {
int[] rv = null;
if ((string != null) && (string.trim().length() > 0)) {
String[] atts = string.split(",");
rv = new int[atts.length];
for (int i = 0; i < atts.length; i++) {
try {
rv[i] = Integer.parseInt(atts[i]);
} catch (NumberFormatException e) {
logger.error("error: ", e);
}
}
}
return rv;
}
private String getElementValue(Node toQuery, String nodeName)
throws TransformerException {
Node selected = XPathAPI.selectSingleNode(toQuery, nodeName +
"/text()");
String value = null;
if (selected != null) {
value = selected.getNodeValue().trim();
}
return value;
}
/**
* @return
*/
public int[] getAttributes() {
return attributes;
}
/**
* @return
*/
public int getSequence() {
return sequence;
}
/**
* @return
*/
public String getSystemName() {
return systemName;
}
/**
* @param is
*/
public void setAttributes(int[] is) {
attributes = is;
}
/**
* @param i
*/
public void setSequence(int i) {
sequence = i;
}
/**
* @param string
*/
public void setSystemName(String string) {
systemName = string;
}
/**
* @return
*/
public String getDefault() {
return def;
}
/**
* @return
*/
public String getValidateExternalName() {
return validateExternalName;
}
/**
* @return
*/
public String getValidateHelpID() {
return validateHelpID;
}
/**
* @param string
*/
public void setDefault(String string) {
def = string;
}
/**
* @param string
*/
public void setValidateExternalName(String string) {
validateExternalName = string;
}
/**
* @param string
*/
public void setValidateHelpID(String string) {
validateHelpID = string;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object o) {
UpdateField update = (UpdateField) o;
return sequence - update.getSequence();
}
/**
* @return
*/
public List getValidationExpressions() {
return validationExpressions;
}
public void addValidationExpression(ValidationExpression expr) {
validationExpressions.add(expr);
}
/**
* @param expressions
*/
public void setValidationExpressions(List expressions) {
validationExpressions.clear();
validationExpressions.addAll(expressions);
}
public void validate(Map symbols) {
ValidationExpressionEvaluator evaluator = new ValidationExpressionEvaluator();
evaluator.getTermFactory().setSymbolTable(symbols);
evaluator.getTermFactory().setEntry(getSystemName());
boolean accepted = false;
System.out.println("Validating field " + getSystemName() +
" there are " + validationExpressions.size() + " expressions");
for (Iterator iter = validationExpressions.iterator(); iter.hasNext(); ) {
ValidationExpression expression = (ValidationExpression) iter.next();
String type = expression.getType();
String exprText = expression.getExpression();
String toSet = "";
Term result;
Boolean TRUE = new Boolean(true);
System.out.println("Executing " + exprText);
if ("SET".equals(type)) {
int equalsPos = exprText.indexOf("=");
if (equalsPos < 0) {
System.out.println("Couldn't find an equals in expression " +
exprText);
continue;
} else {
exprText = exprText.substring(equalsPos + 1);
toSet = exprText.substring(0, equalsPos);
}
} else if (accepted) {
// if it's a set, we'll execute, otherwise continue to the next one.
continue;
}
try {
result = evaluator.eval(exprText);
if (type.equals("SET")) {
evaluator.getTermFactory().setSymbol(toSet.trim(), result);
} else if (TRUE.equals(result.getValue()) &&
type.equals("REJECT")) {
error = new ValidationError(getSystemName(),
" failed validation because " +
expression.getExpression());
break;
} else if (TRUE.equals(result.getValue()) &&
type.equals("ACCEPT")) {
// only process SET
accepted = true;
}
} catch (InvalidTermException e) {
// TODO Auto-generated catch block
logger.error("error: ", e);
error = new ValidationError(getSystemName(),
" failed because " + e.getMessage());
}
}
}
/**
* @return
*/
public ValidationError getError() {
return error;
}
}

View File

@ -0,0 +1,56 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/ValidationError.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation;
/**
* ValidationError.java Created Oct 3, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class ValidationError {
private String fieldName;
private String errorMessage;
public ValidationError() {
}
public ValidationError(String fieldName, String errorMessage) {
this.fieldName = fieldName;
this.errorMessage = errorMessage;
}
/**
* @return
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* @return
*/
public String getFieldName() {
return fieldName;
}
/**
* @param string
*/
public void setErrorMessage(String string) {
errorMessage = string;
}
/**
* @param string
*/
public void setFieldName(String string) {
fieldName = string;
}
public String toString() {
return fieldName + " " + errorMessage;
}
}

View File

@ -0,0 +1,68 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/ValidationExpression.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation;
/**
* ValidationExpression.java Created Oct 3, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class ValidationExpression {
private String expression;
private String type;
private String id;
public ValidationExpression(String id) {
this.id = id;
}
public ValidationExpression(String type, String id) {
this.type = type;
this.id = id;
}
/**
* @return
*/
public String getExpression() {
return expression;
}
/**
* @return
*/
public String getType() {
return type;
}
/**
* @param string
*/
public void setExpression(String string) {
expression = string;
}
/**
* @param string
*/
public void setType(String string) {
type = string;
}
/**
* @return
*/
public String getID() {
return id;
}
/**
* @param string
*/
public void setID(String string) {
id = string;
}
}

View File

@ -0,0 +1,201 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/ValidationExpressionEvaluator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation;
import org.realtor.rets.validation.operators.CloseParen;
import org.realtor.rets.validation.operators.NotOperator;
import org.realtor.rets.validation.operators.OpenParen;
import org.realtor.rets.validation.operators.Operator;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.Term;
import org.realtor.rets.validation.terms.TermFactory;
import java.util.Map;
import java.util.Stack;
/**
* ValidationExpressionEvaluator.java Created Aug 22, 2003
* This class implements the RETS validation language version 1.5.
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class ValidationExpressionEvaluator {
private String expression;
private ParseTree tree;
private Stack tokens;
private TermFactory factory;
public ValidationExpressionEvaluator() {
expression = "(3 + 5)";
factory = new TermFactory();
}
public ValidationExpressionEvaluator(String expr) {
this();
expression = expr;
}
/**
* Evaluates an expression and returns a Term which is the result of the evaluation.
* the exact type of the term depends on the expression.
* @param expr The expression to evaluate
* @return a term representing the result of the evaluation
* @throws InvalidTermException
*/
public Term eval(String expr) throws InvalidTermException {
setExpression(expr);
eval(Operator.MIN_PRECEDENCE);
return (Term) tokens.pop();
}
private void eval(int currentPrecedence) throws InvalidTermException {
while (tokens.size() > 1) {
Term firstTerm;
Operator oper;
Term secondTerm;
Object firstObj = tokens.pop();
if (firstObj instanceof OpenParen) {
tokens.push(firstObj);
parseParenthetical();
} else if (firstObj instanceof NotOperator) {
NotOperator not = (NotOperator) firstObj;
eval(not.getPrecedence());
tokens.push(not.apply((Term) tokens.pop()));
} else {
firstTerm = (Term) firstObj;
oper = (Operator) tokens.pop();
if (tokens.peek() instanceof OpenParen) {
parseParenthetical();
}
secondTerm = (Term) tokens.pop();
if (tokens.size() > 0) {
Object lookAhead = tokens.peek();
if (lookAhead instanceof Operator) {
Operator nextOper = (Operator) lookAhead;
if (nextOper instanceof CloseParen) {
tokens.pop();
} else if (nextOper.getPrecedence() > oper.getPrecedence()) {
tokens.push(secondTerm);
eval(nextOper.getPrecedence());
secondTerm = (Term) tokens.pop();
} else if (nextOper.getPrecedence() < currentPrecedence) {
tokens.push(oper.apply(firstTerm, secondTerm));
break;
}
} else {
// invalid expression?
throw new InvalidTermException(
"Invalid Expression, expected an operator but got " +
lookAhead);
}
}
tokens.push(oper.apply(firstTerm, secondTerm));
}
}
}
/**
* This method pulls out the parenthetical expression, evaluates it, and then places the result on the
* original stack in place of the expression.
* @throws InvalidTermException
*/
private void parseParenthetical() throws InvalidTermException {
Stack paren = getParentheticalExpression(tokens);
Stack tmpTokens = tokens;
tokens = paren;
eval(Operator.MIN_PRECEDENCE);
tmpTokens.push(tokens.pop());
tokens = tmpTokens;
}
/**
* Returns a stack containing a parenthetical expresion.
* If the expression is ( 3 + 5), 3 + 5 is returned. If the expression is ((3)) (3) is returned.
* @param orig
* @return
*/
private Stack getParentheticalExpression(Stack orig) {
Stack newEq = new Stack();
orig.pop(); // remove the first paren
int openParens = 1;
while (orig.size() > 0) {
Object current = orig.pop();
if (current instanceof OpenParen) {
openParens++;
} else if (current instanceof CloseParen) {
openParens--;
if (openParens == 0) {
break;
}
}
newEq.add(0, current);
}
return newEq;
}
/**
* This method tokenizes an expression. That is, it replaces the textual
* representation of the expression with
* @param expr
*/
private void tokenize(String expr) {
RetsTokenParser tokenizer = new RetsTokenParser(expr);
tokenizer.setTermFactory(factory);
tokens = new Stack();
int i = 0;
Object token;
while ((token = tokenizer.nextToken()) != null) {
tokens.add(i, token);
}
}
/**
* Return
* @return
*/
public String getExpression() {
return expression;
}
/**
* Sets the expression to evaluate
* @param string The expression to be evaluated.
*/
public void setExpression(String string) {
expression = string;
tokenize(expression);
}
public void setSymbolTable(Map m) {
factory.setSymbolTable(m);
}
public TermFactory getTermFactory() {
return factory;
}
public static void main(String[] args) throws Exception {
ValidationExpressionEvaluator parser = new ValidationExpressionEvaluator();
parser.eval("((3))");
}
}

View File

@ -0,0 +1,69 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/AdditionOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
import java.util.Calendar;
import java.util.Date;
/**
* AdditionOperator.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class AdditionOperator extends Operator {
public AdditionOperator() {
symbol = "+";
setPrecedence(2);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.operators.Term, org.realtor.rets.validation.operators.Term)
*/
public Term apply(DateTerm t1, Term t2) throws InvalidTermException {
Calendar c = Calendar.getInstance();
c.setTime((Date) t1.getValue());
if (t2.isClass(DateTerm.class)) {
throw new InvalidTermException("Cannot add two dates together");
} else if (t2.isClass(DateIntervalTerm.class)) {
DateIntervalTerm interval = (DateIntervalTerm) t2;
c.add(Calendar.YEAR, interval.getYears());
c.add(Calendar.MONTH, interval.getMonths());
c.add(Calendar.DATE, interval.getDays());
c.add(Calendar.HOUR, interval.getHours());
c.add(Calendar.MINUTE, interval.getMinutes());
c.add(Calendar.SECOND, interval.getSeconds());
} else {
NumericTerm i = TermConverter.toNumericTerm(t2);
Double days = (Double) i.getValue();
c.add(Calendar.DATE, days.intValue());
}
return new DateTerm(c.getTime());
}
public Term apply(Term t1, Term t2) throws InvalidTermException {
if (t1.isClass(DateTerm.class)) {
return apply((DateTerm) t1.getTerm(), t2);
} else if (t2.isClass(DateTerm.class)) {
return apply((DateTerm) t2.getTerm(), t1);
} else {
NumericTerm it1;
NumericTerm it2;
it1 = TermConverter.toNumericTerm(t1);
it2 = TermConverter.toNumericTerm(t2);
double i1;
double i2;
i1 = ((Double) it1.getValue()).doubleValue();
i2 = ((Double) it2.getValue()).doubleValue();
return new NumericTerm(i1 + i2);
}
}
}

View File

@ -0,0 +1,46 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/AndOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
/**
* And.java Created Aug 22, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class AndOperator extends Operator implements LogicOperator {
public AndOperator() {
super();
setPrecedence(5);
symbol = ".AND.";
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply()
*/
public Term apply(Term t1, Term t2) {
if (t1.isClass(BooleanTerm.class) && t2.isClass(BooleanTerm.class)) {
BooleanTerm b1;
BooleanTerm b2;
b1 = (BooleanTerm) t1;
b2 = (BooleanTerm) t2;
boolean bool1;
boolean bool2;
bool1 = ((Boolean) b1.getValue()).booleanValue();
bool2 = ((Boolean) b2.getValue()).booleanValue();
return new BooleanTerm(bool1 && bool2);
} else {
System.out.println(
"One of the terms in AND is not a boolean term t1:" +
t1.getClass().getName() + " t2: " + t2.getClass().getName());
return null;
}
}
}

View File

@ -0,0 +1,30 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/CloseParen.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.Term;
/**
* CloseParen.java Created Sep 3, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class CloseParen extends Operator implements Parenthetical {
public CloseParen() {
super();
symbol = ")";
setPrecedence(0);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,29 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/ComparisonOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
/**
* ComparisonOperator.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public abstract class ComparisonOperator extends Operator {
public ComparisonOperator() {
this.setPrecedence(3);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.operators.Term, org.realtor.rets.validation.operators.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
return new BooleanTerm(doComparison(t1, t2));
}
protected abstract boolean doComparison(Term t1, Term t2)
throws InvalidTermException;
}

View File

@ -0,0 +1,42 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/ContainsOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.BooleanTerm;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.StringTerm;
import org.realtor.rets.validation.terms.Term;
import org.realtor.rets.validation.terms.TermConverter;
/**
* ContainsOperator.java Created Sep 15, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class ContainsOperator extends Operator {
public ContainsOperator() {
super();
symbol = ".CONTAINS.";
setPrecedence(2);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
StringTerm st1;
StringTerm st2;
st1 = TermConverter.toStringTerm(t1);
st2 = TermConverter.toStringTerm(t2);
String s1;
String s2;
s1 = (String) st1.getValue();
s2 = (String) st2.getValue();
return new BooleanTerm(s1.indexOf(s2) >= 0);
}
}

View File

@ -0,0 +1,38 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/DivisionOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
import org.realtor.rets.validation.terms.InvalidTermException;
/**
* DivisonOperator.java Created Sep 19, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class DivisionOperator extends Operator {
public DivisionOperator() {
symbol = "/";
setPrecedence(1);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
NumericTerm i1;
NumericTerm i2;
i1 = TermConverter.toNumericTerm(t1);
i2 = TermConverter.toNumericTerm(t2);
Double l1;
Double l2;
l1 = (Double) i1.getValue();
l2 = (Double) i2.getValue();
return new NumericTerm(l1.doubleValue() / l2.doubleValue());
}
}

View File

@ -0,0 +1,32 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/EqualsOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
/**
* EqualsOperator.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class EqualsOperator extends ComparisonOperator {
public EqualsOperator() {
super();
symbol = "=";
setPrecedence(4);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.ComparisonOperator#doComparison(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
protected boolean doComparison(Term t1, Term t2)
throws InvalidTermException {
boolean ret = false;
ret = t1.getValue().equals(t2.getValue());
return ret;
}
}

View File

@ -0,0 +1,55 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/GreaterThanOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
/**
* GreaterThanOperator.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class GreaterThanOperator extends ComparisonOperator
implements MathematicOperator {
public GreaterThanOperator() {
super();
comparable = true;
symbol = ">";
setPrecedence(3);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.ComparisonOperator#doComparison(org.realtor.rets.validation.operators.Term, org.realtor.rets.validation.operators.Term)
*/
protected boolean doComparison(Term t1, Term t2)
throws InvalidTermException {
double i1;
double i2;
if (t1.isClass(StringTerm.class)) {
StringTerm st1;
StringTerm st2;
st1 = (StringTerm) t1;
st2 = TermConverter.toStringTerm(t2);
String s1;
String s2;
s1 = (String) st1.getValue();
s2 = (String) st2.getValue();
return s1.compareTo(s2) > 0;
} else {
NumericTerm it1;
NumericTerm it2;
it1 = TermConverter.toNumericTerm(t1);
it2 = TermConverter.toNumericTerm(t2);
i1 = ((Double) it1.getValue()).doubleValue();
i2 = ((Double) it2.getValue()).doubleValue();
}
return i1 > i2;
}
}

View File

@ -0,0 +1,59 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/GreaterThanOrEqualToOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.NumericTerm;
import org.realtor.rets.validation.terms.StringTerm;
import org.realtor.rets.validation.terms.Term;
import org.realtor.rets.validation.terms.TermConverter;
/**
* GreaterThanOrEqualToOperator.java Created Sep 10, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class GreaterThanOrEqualToOperator extends ComparisonOperator {
/**
*
*/
public GreaterThanOrEqualToOperator() {
super();
symbol = ">=";
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.ComparisonOperator#doComparison(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
protected boolean doComparison(Term t1, Term t2)
throws InvalidTermException {
double i1;
double i2;
if (t1.isClass(StringTerm.class)) {
StringTerm st1;
StringTerm st2;
st1 = (StringTerm) t1;
st2 = TermConverter.toStringTerm(t2);
String s1;
String s2;
s1 = (String) st1.getValue();
s2 = (String) st2.getValue();
return s1.compareTo(s2) >= 0;
} else {
NumericTerm it1;
NumericTerm it2;
it1 = TermConverter.toNumericTerm(t1);
it2 = TermConverter.toNumericTerm(t2);
i1 = ((Double) it1.getValue()).doubleValue();
i2 = ((Double) it2.getValue()).doubleValue();
}
return i1 >= i2;
}
}

View File

@ -0,0 +1,57 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/LessThanOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
/**
* LessThanOperator.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class LessThanOperator extends ComparisonOperator
implements MathematicOperator {
public LessThanOperator() {
symbol = "<";
comparable = true;
setPrecedence(3);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.ComparisonOperator#doComparison(org.realtor.rets.validation.operators.Term, org.realtor.rets.validation.operators.Term)
*/
protected boolean doComparison(Term t1, Term t2)
throws InvalidTermException {
if (t1.isClass(StringTerm.class)) {
StringTerm st1;
StringTerm st2;
st1 = (StringTerm) t1;
st2 = TermConverter.toStringTerm(t2);
String s1;
String s2;
s1 = (String) st1.getValue();
s2 = (String) st2.getValue();
return s1.compareTo(s2) > 0;
} else {
// most other terms can be converted to int.
NumericTerm it1;
// most other terms can be converted to int.
NumericTerm it2;
double i1;
double i2;
it1 = TermConverter.toNumericTerm(t1.getTerm());
it2 = TermConverter.toNumericTerm(t2.getTerm());
i1 = ((Double) it1.getValue()).doubleValue();
i2 = ((Double) it2.getValue()).doubleValue();
return i1 < i2;
}
}
}

View File

@ -0,0 +1,56 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/LessThanOrEqualToOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.NumericTerm;
import org.realtor.rets.validation.terms.StringTerm;
import org.realtor.rets.validation.terms.Term;
import org.realtor.rets.validation.terms.TermConverter;
/**
* LessThanOrEqualToOperator.java Created Sep 11, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class LessThanOrEqualToOperator extends ComparisonOperator {
public LessThanOrEqualToOperator() {
symbol = "<=";
setPrecedence(3);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.ComparisonOperator#doComparison(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
protected boolean doComparison(Term t1, Term t2)
throws InvalidTermException {
double i1;
double i2;
if (t1.isClass(StringTerm.class)) {
StringTerm st1;
StringTerm st2;
st1 = (StringTerm) t1;
st2 = TermConverter.toStringTerm(t2);
String s1;
String s2;
s1 = (String) st1.getValue();
s2 = (String) st2.getValue();
return s1.compareTo(s2) <= 0;
} else {
NumericTerm it1;
NumericTerm it2;
it1 = TermConverter.toNumericTerm(t1.getTerm());
it2 = TermConverter.toNumericTerm(t2.getTerm());
i1 = ((Double) it1.getValue()).doubleValue();
i2 = ((Double) it2.getValue()).doubleValue();
}
return i1 <= i2;
}
}

View File

@ -0,0 +1,14 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/LogicOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
/**
* LogicOperator.java Created Aug 27, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public interface LogicOperator {
}

View File

@ -0,0 +1,14 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/MathematicOperator.java,v 1.2 2003/12/04 15:28:32 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
/**
* MathematicOperator.java Created Aug 27, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public interface MathematicOperator {
}

View File

@ -0,0 +1,40 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/ModOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.NumericTerm;
import org.realtor.rets.validation.terms.Term;
import org.realtor.rets.validation.terms.TermConverter;
/**
* ModOperator.java Created Sep 24, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class ModOperator extends Operator {
public ModOperator() {
symbol = ".MOD.";
setPrecedence(1);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
NumericTerm i1;
NumericTerm i2;
i1 = TermConverter.toNumericTerm(t1);
i2 = TermConverter.toNumericTerm(t2);
Double l1;
Double l2;
l1 = (Double) i1.getValue();
l2 = (Double) i2.getValue();
return new NumericTerm(l1.doubleValue() % l2.doubleValue());
}
}

View File

@ -0,0 +1,41 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/MultiplicationOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.NumericTerm;
import org.realtor.rets.validation.terms.Term;
import org.realtor.rets.validation.terms.TermConverter;
/**
* MultiplicationOperator.java Created Sep 3, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class MultiplicationOperator extends Operator {
public MultiplicationOperator() {
super();
setPrecedence(1);
symbol = "*";
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
return apply(TermConverter.toNumericTerm(t1),
TermConverter.toNumericTerm(t2));
}
public Term apply(NumericTerm t1, NumericTerm t2) {
Double i1;
Double i2;
i1 = (Double) t1.getValue();
i2 = (Double) t2.getValue();
return new NumericTerm(i1.doubleValue() * i2.doubleValue());
}
}

View File

@ -0,0 +1,31 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/NotEqualsOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.Term;
/**
* NotEqualsOperator.java Created Sep 15, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class NotEqualsOperator extends ComparisonOperator {
public NotEqualsOperator() {
symbol = "!=";
setPrecedence(4);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.ComparisonOperator#doComparison(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
protected boolean doComparison(Term t1, Term t2)
throws InvalidTermException {
System.out.println("T1: " + t1 + " t2: " + t2);
return !t1.getValue().equals(t2.getValue());
}
}

View File

@ -0,0 +1,44 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/NotOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
import org.realtor.rets.validation.terms.InvalidTermException;
/**
* NotOperator.java Created Sep 17, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class NotOperator extends Operator {
public NotOperator() {
setPrecedence(7);
symbol = ".NOT.";
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
throw new InvalidTermException(
"This is a unary operator, it is not applicable for " + t1 + "," +
t2);
}
public Term apply(Term t1) throws InvalidTermException {
if (!(t1 instanceof BooleanTerm)) {
String className = t1.getClass().getName();
className = className.substring(className.lastIndexOf(".") + 1);
throw new InvalidTermException(
"Expected a boolean expression but found a " + className +
" while processing .NOT.");
}
Boolean orig = (Boolean) t1.getValue();
return new BooleanTerm(!orig.booleanValue());
}
}

View File

@ -0,0 +1,30 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/OpenParen.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.Term;
/**
* OpenParen.java Created Sep 3, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class OpenParen extends Operator implements Parenthetical {
public OpenParen() {
super();
symbol = "(";
setPrecedence(0);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,60 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/Operator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
/**
* Operator.java Created Aug 22, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public abstract class Operator {
public static int MIN_PRECEDENCE = Integer.MIN_VALUE;
protected Object leftSide;
protected Object rightSide;
protected boolean comparable = false;
protected String symbol;
protected int precedence;
public abstract Term apply(Term t1, Term t2) throws InvalidTermException;
public boolean isComparable() {
return comparable;
}
public String getSymbol() {
return symbol;
}
public String toString() {
String className = getClass().getName();
return className.substring(className.lastIndexOf(".") + 1);
}
/**
* @return
*/
public int getPrecedence() {
return precedence;
}
/**
* @param i
*/
public void setPrecedence(int i) {
precedence = 0 - i;
}
public boolean equals(Object another) {
if (another != null) {
return another.getClass().equals(this.getClass());
} else {
return false;
}
}
}

View File

@ -0,0 +1,46 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/OrOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
/**
* OrOperator.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class OrOperator extends Operator implements LogicOperator {
public OrOperator() {
super();
setPrecedence(6);
symbol = ".OR.";
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.operators.Term, org.realtor.rets.validation.operators.Term)
*/
public Term apply(Term t1, Term t2) {
if (t1.isClass(BooleanTerm.class) && t2.isClass(BooleanTerm.class)) {
BooleanTerm b1;
BooleanTerm b2;
b1 = (BooleanTerm) t1;
b2 = (BooleanTerm) t2;
boolean bool1;
boolean bool2;
bool1 = ((Boolean) b1.getValue()).booleanValue();
bool2 = ((Boolean) b2.getValue()).booleanValue();
return new BooleanTerm(bool1 || bool2);
} else {
System.out.println(
"One of the terms in OR is not a boolean term t1:" +
t1.getClass().getName() + " t2: " + t2.getClass().getName());
return null;
}
}
}

View File

@ -0,0 +1,14 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/Parenthetical.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
/**
* Parenthetical.java Created Sep 8, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public interface Parenthetical {
}

View File

@ -0,0 +1,77 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/operators/SubtractionOperator.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.operators;
import org.realtor.rets.validation.terms.*;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.NumericTerm;
import java.util.Calendar;
import java.util.Date;
/**
* SubtractionOperator.java Created Sep 8, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class SubtractionOperator extends Operator {
public SubtractionOperator() {
symbol = "-";
setPrecedence(2);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Operator#apply(org.realtor.rets.validation.terms.Term, org.realtor.rets.validation.terms.Term)
*/
public Term apply(Term t1, Term t2) throws InvalidTermException {
if (t1.isClass(DateTerm.class)) {
return apply((DateTerm) t1.getTerm(), t2);
}
return apply(TermConverter.toNumericTerm(t1),
TermConverter.toNumericTerm(t2));
}
public Term apply(DateTerm t1, Term t2) throws InvalidTermException {
Calendar c = Calendar.getInstance();
c.setTime((Date) t1.getValue());
if (t2.isClass(DateTerm.class)) {
DateTerm toSubtract = (DateTerm) t2.getTerm();
Date d1;
Date d2;
d1 = (Date) t1.getValue();
d2 = (Date) toSubtract.getValue();
return new DateIntervalTerm(d1.getTime() - d2.getTime());
} else if (t2.isClass(DateIntervalTerm.class)) {
DateIntervalTerm interval = (DateIntervalTerm) t2;
c.add(Calendar.YEAR, interval.getYears() * -1);
c.add(Calendar.MONTH, interval.getMonths() * -1);
c.add(Calendar.DATE, interval.getDays() * -1);
c.add(Calendar.HOUR, interval.getHours() * -1);
c.add(Calendar.MINUTE, interval.getMinutes() * -1);
c.add(Calendar.SECOND, interval.getSeconds() * -1);
c.add(Calendar.DATE, (interval.getWeeks() * 7) * -1);
} else {
NumericTerm i = TermConverter.toNumericTerm(t2);
Double days = (Double) i.getValue();
c.add(Calendar.DATE, days.intValue() * -1);
}
return new DateTerm(c.getTime());
}
public Term apply(NumericTerm t1, NumericTerm t2)
throws InvalidTermException {
Double l1;
Double l2;
l1 = (Double) t1.getValue();
l2 = (Double) t2.getValue();
return new NumericTerm(l1.doubleValue() - l2.doubleValue());
}
}

View File

@ -0,0 +1,46 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/AbstractTerm.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
/**
* AbstractTerm.java Created Sep 29, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public abstract class AbstractTerm implements Term {
protected Class type = this.getClass();
protected Object value;
/* (non-Javadoc)
* @see org.realtor.rets.validation.terms.Term#getValue()
*/
public Object getValue() {
return value;
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.terms.Term#setValue(java.lang.Object)
*/
public void setValue(Object val) {
value = val;
}
public boolean isClass(Class toTest) {
return type.equals(toTest);
}
public String toString() {
return type.getName() + "-->" + value;
}
public Class getType() {
return type;
}
public Term getTerm() {
return this;
}
}

View File

@ -0,0 +1,28 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/BooleanTerm.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
/**
* BooleanTerm.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class BooleanTerm extends AbstractTerm {
public BooleanTerm(boolean b) {
value = new Boolean(b);
}
public boolean equals(Object another) {
if (another instanceof BooleanTerm) {
BooleanTerm otherBool = (BooleanTerm) another;
Boolean otherValue = (Boolean) otherBool.getValue();
return (value.equals(otherValue));
} else {
return false;
}
}
}

View File

@ -0,0 +1,280 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/DateIntervalTerm.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
import java.text.ParseException;
import java.util.regex.*;
/**
* DateIntervalTerm.java Created Sep 17, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class DateIntervalTerm extends AbstractTerm {
private static long MILLIS_PER_HOUR = 3600 * 1000;
private static long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
private static long MILLIS_PER_YEAR = 365 * MILLIS_PER_DAY;
private static Pattern iso8601;
private int days = 0;
private int hours = 0;
private int minutes = 0;
private int seconds = 0;
private int months = 0;
private int weeks = 0;
private int years = 0;
DateIntervalTerm() {
super();
if (iso8601 == null) {
iso8601 = Pattern.compile(
"P(?:(-?\\d+)Y)?(?:(-?\\d+)M)?(?:(-?\\d+)D)?(?:T(?:(-?\\d+)H)?(?:(-?\\d+)M)?(?:(-?\\d+)S)?)?");
}
}
/**
* @param l
*/
public DateIntervalTerm(long interval) {
this();
setTime(interval);
}
/**
*
*/
public DateIntervalTerm(String interval) throws ParseException {
this();
setValue(interval);
}
public void setInterval(String interval) throws ParseException {
value = interval.toUpperCase();
parseInterval();
}
public long getTime() {
long rv = 0;
rv += (years * 365);
rv += (months * 30);
rv += (weeks * 7);
rv += days;
// now get it into seconds
rv *= (24 * 3600);
rv += (minutes * 60);
rv += seconds;
rv *= 1000;
return rv;
}
public void setTime(long interval) {
years = (int) (interval / MILLIS_PER_YEAR);
interval -= (years * MILLIS_PER_YEAR);
weeks = (int) (interval / (7 * MILLIS_PER_DAY));
interval -= (weeks * (7 * MILLIS_PER_DAY));
days = (int) (interval / MILLIS_PER_DAY);
interval -= (days * MILLIS_PER_DAY);
hours = (int) interval / (3600 * 1000);
interval -= (hours * (3600 * 1000));
minutes = (int) interval / (60 * 1000);
interval -= (minutes * (60 * 1000));
seconds = (int) interval / 1000;
interval -= (seconds * 1000);
generateDateString();
}
/**
*
*/
private void generateDateString() {
StringBuffer date = new StringBuffer("P");
appendTimeUnit(date, years, "Y", false);
appendTimeUnit(date, months, "M", false);
appendTimeUnit(date, weeks, "W", false);
appendTimeUnit(date, days, "D", false);
appendTimeUnit(date, hours, "H", true);
appendTimeUnit(date, minutes, "M", true);
appendTimeUnit(date, seconds, "S", true);
value = date.toString();
}
private void appendTimeUnit(StringBuffer toAppend, int time, String label,
boolean isTimeUnit) {
if (time > 0) {
if (isTimeUnit && (toAppend.indexOf("T") < 0)) {
toAppend.append("T");
}
toAppend.append(time);
toAppend.append(label);
}
}
/**
* @param interval
* @return
*/
private void parseInterval() throws ParseException {
String sVal = (String) getValue();
if (sVal.matches("P-?\\d+W")) {
System.out.println("Matches! " + sVal);
weeks = toInt(sVal.substring(1, sVal.indexOf("W")));
} else {
Matcher matcher = iso8601.matcher(sVal);
if (matcher.find()) {
years = toInt(matcher.group(1));
months = toInt(matcher.group(2));
days = toInt(matcher.group(3));
hours = toInt(matcher.group(4));
minutes = toInt(matcher.group(5));
seconds = toInt(matcher.group(6));
weeks = 0;
} else {
throw new ParseException(sVal +
" is not a valid Date interval", 0);
}
}
}
/**
* @param string
* @return
*/
private int toInt(String string) {
int rv = 0;
if (string != null) {
try {
rv = Integer.parseInt(string);
} catch (NumberFormatException e) {
}
}
return rv;
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.terms.Term#setValue(java.lang.Object)
*/
public void setValue(Object val) {
super.setValue(val);
String sVal = val.toString();
try {
setInterval(sVal);
parseInterval();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @return
*/
public int getDays() {
return days;
}
/**
* @return
*/
public int getMinutes() {
return minutes;
}
/**
* @return
*/
public int getMonths() {
return months;
}
/**
* @return
*/
public int getSeconds() {
return seconds;
}
/**
* @return
*/
public int getWeeks() {
return weeks;
}
/**
* @return
*/
public int getYears() {
return years;
}
/**
* @param i
*/
public void setDays(int i) {
days = i;
}
/**
* @param i
*/
public void setMinutes(int i) {
minutes = i;
}
/**
* @param i
*/
public void setMonths(int i) {
months = i;
}
/**
* @param i
*/
public void setSeconds(int i) {
seconds = i;
}
/**
* @param i
*/
public void setWeeks(int i) {
weeks = i;
}
/**
* @param i
*/
public void setYears(int i) {
years = i;
}
/**
* @return
*/
public int getHours() {
return hours;
}
/**
* @param i
*/
public void setHours(int i) {
hours = i;
}
}

View File

@ -0,0 +1,57 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/DateTerm.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* DateTerm.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class DateTerm extends AbstractTerm {
private static SimpleDateFormat sdf;
public DateTerm() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
value = cal.getTime();
}
public DateTerm(Date date) {
value = date;
}
public DateTerm(String dateFmt) throws ParseException {
if (sdf == null) {
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
value = sdf.parse(dateFmt);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Term#setValue(java.lang.Object)
*/
public void setValue(Object val) {
if (val instanceof Date) {
value = (Date) val;
} else if (val instanceof String) {
try {
value = sdf.parse((String) val);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,17 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/InvalidTermException.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
/**
* InvalidTermException.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class InvalidTermException extends Exception {
public InvalidTermException(String message) {
super(message);
}
}

View File

@ -0,0 +1,41 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/NumericTerm.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
/**
* IntTerm.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class NumericTerm extends AbstractTerm {
public NumericTerm(String s) {
value = new Double(s);
}
public NumericTerm(char c) {
}
public NumericTerm(int i) {
value = new Double(i);
}
public NumericTerm(double d) {
value = new Double(d);
}
public NumericTerm(long i) {
value = new Double(i);
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.operators.Term#setValue(java.lang.Object)
*/
public void setValue(Object val) {
if (val instanceof Double) {
value = val;
}
}
}

View File

@ -0,0 +1,17 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/StringTerm.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
/**
* String.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class StringTerm extends AbstractTerm {
public StringTerm(String val) {
value = val;
}
}

View File

@ -0,0 +1,23 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/Term.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
/**
* Term.java Created Aug 25, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public interface Term {
public boolean isClass(Class toTest);
public Object getValue();
public void setValue(Object val);
public Class getType();
public Term getTerm();
}

View File

@ -0,0 +1,98 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/TermConverter.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* TermConverter.java Created Aug 25, 2003
* This object takes terms of one type and tries to convert them to another type. If the conversion fails,
* and InvalidTermException is thrown.
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class TermConverter {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public static NumericTerm toNumericTerm(Term t) throws InvalidTermException {
// short circuit the whole method if it's already an int term.
if (t.isClass(NumericTerm.class)) {
return (NumericTerm) t.getTerm();
}
Object origValue = null;
NumericTerm rv = null;
try {
origValue = t.getTerm().getValue();
if (origValue instanceof String) {
rv = new NumericTerm((String) origValue);
} else if (origValue instanceof Date) {
rv = new NumericTerm(((Date) origValue).getTime());
} else if (t.isClass(DateIntervalTerm.class)) {
DateIntervalTerm interval = (DateIntervalTerm) t.getTerm();
rv = new NumericTerm(interval.getTime());
}
} catch (Exception ex) {
throw new InvalidTermException("Could not convert \"" + origValue +
"\" into an Integer");
}
return rv;
}
public static StringTerm toStringTerm(Term t) {
Object val = t.getTerm().getValue();
return new StringTerm(val.toString());
}
public static DateTerm toDateTerm(Term t) throws InvalidTermException {
if (t.isClass(DateTerm.class)) {
return (DateTerm) t.getTerm();
}
DateTerm rv = null;
Object origValue = t.getTerm().getValue();
try {
rv = new DateTerm(origValue.toString());
} catch (Exception e) {
throw new InvalidTermException("Could not convert \"" + origValue +
"\" to a string in YYYY-MM-DD format");
}
return rv;
}
/**
* Converts a term to a DateInterval term. The term to be converted can be a string that represents a
* Date Interval in ISO8601 format.
* @param t The term to be converted
* @return a date interval term if the argument can be converted.
* @throws InvalidTermException
*/
public static DateIntervalTerm toDateIntervalTerm(Term t)
throws InvalidTermException {
if (t.isClass(DateIntervalTerm.class)) {
return (DateIntervalTerm) t.getTerm();
}
DateIntervalTerm rv = null;
Object origValue = t.getTerm().getValue();
try {
rv = new DateIntervalTerm(origValue.toString());
} catch (Exception e) {
throw new InvalidTermException("Could not convert \"" + origValue +
"\" to a string in YYYY-MM-DD format");
}
return rv;
}
}

View File

@ -0,0 +1,80 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/TermFactory.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
import java.util.*;
/**
* Factory object for creating VariableTerms. This object houses the Symbol Table so
* all the variable terms in a thread can share the resource while allowing other threads to
* have their own symbol table.
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class TermFactory {
private Map symbolTable;
public TermFactory() {
symbolTable = new HashMap();
}
/**
* Returns the symbol table for this factory
* @return a map of name -> term mappings
*/
public Map getSymbolTable() {
return symbolTable;
}
/**
* Instantiates a new variable term with the specified name.
* @param varName The name of the variable
* @return a newly instantiated variable term
*/
public VariableTerm newVariableTerm(String varName) {
VariableTerm vt = new VariableTerm(varName);
vt.setTermFactory(this);
return vt;
}
/**
* Sets the symbol table for this factory. Also creates the .EMPTY. variable if none exists.
* @param toSet the map to use as the Symbol Table. It must contain name-> Term mappings.
*/
public void setSymbolTable(Map toSet) {
symbolTable = toSet;
if (symbolTable.get(".EMPTY.") == null) {
symbolTable.put(".EMPTY.", new StringTerm(""));
}
}
/**
* Sets a symbol in the symbol table
* @param name the name of the symbol
* @param value a term representing the symbol's value
*/
public void setSymbol(String name, Term value) {
symbolTable.put(name, value);
}
/**
* This method designates the symbol with the name passed in as the current entry
* in the validation language.
* @param termName The name of the variable to use as the entry.
*/
public void setEntry(String termName) {
VariableTerm entry = newVariableTerm(termName);
entry.setValue(symbolTable.get(termName));
if (entry.getValue() == null) {
symbolTable.put(".ENTRY.", symbolTable.get(".EMPTY."));
} else {
symbolTable.put(".ENTRY.", entry);
}
}
}

View File

@ -0,0 +1,89 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/terms/VariableTerm.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.terms;
import java.util.*;
/**
* VariableTerm.java Created Sep 29, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.2 $
* @author scohen
*/
public class VariableTerm extends AbstractTerm {
private static final String EMPTY = ".EMPTY.";
private String variableName;
private TermFactory factory;
protected VariableTerm(String name) {
variableName = name;
}
public void setTermFactory(TermFactory f) {
factory = f;
}
public void setSymbol(String symbolName, Term value) {
factory.getSymbolTable().put(symbolName, value);
}
public void setEntry(String termName) {
VariableTerm entry = factory.newVariableTerm(termName);
System.out.println("Setting entry to " + termName + "::" + entry);
entry.setValue(factory.getSymbolTable().get(termName));
if (entry.getValue() == null) {
System.out.println("Couldn't find " + termName +
" in symbol factory.getSymbolTable().");
}
factory.getSymbolTable().put(".ENTRY.", entry);
}
public void setVariableName(String varName) {
variableName = varName;
}
public String getVariableName() {
return variableName;
}
/* (non-Javadoc)
* @see org.realtor.rets.validation.terms.Term#getValue()
*/
public Object getValue() {
Object test = factory.getSymbolTable().get(variableName);
if (test == null) {
System.out.println("Couldn't find symbol " + variableName);
}
Term rv = (Term) test;
if (rv == null) {
rv = (Term) factory.getSymbolTable().get(EMPTY);
}
return rv.getValue();
}
public boolean isClass(Class toTest) {
System.out.println("isClass: toTest is " + toTest + " variable is " +
variableName);
Object binding = factory.getSymbolTable().get(variableName);
if (binding == null) {
// the variable was not found.
binding = factory.getSymbolTable().get(EMPTY);
}
return binding.getClass().equals(toTest);
}
public Term getTerm() {
return (Term) factory.getSymbolTable().get(variableName);
}
}

View File

@ -0,0 +1,9 @@
#
# Properties file for rets 1.0 build script
#
etc=etc
src=src
lib=lib
build=classes
jar=RetsHealthCheck.jar
TOMCAT_HOME=C:/Program Files/Apache Group/Tomcat 4.1

View File

@ -0,0 +1,80 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/tests/DateIntervalTest.java,v 1.1.1.1 2003/11/21 16:20:05 rsegelman Exp $ */
package org.realtor.rets.validation.tests;
import org.junit.jupiter.api.Test;
import org.realtor.rets.validation.terms.DateIntervalTerm;
import java.text.ParseException;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* DateIntervalTest.java Created Sep 18, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.1.1.1 $
* @author scohen
*/
public class DateIntervalTest {
private DateIntervalTerm term;
@Test
public void testDays() throws ParseException {
term.setInterval("P15D");
assertEquals(new Integer(15), new Integer(term.getDays()));
}
public void testYears() throws ParseException {
term.setInterval("P10Y");
assertEquals(new Integer(10), new Integer(term.getYears()));
}
public void testWeeks() throws ParseException {
term.setInterval("P8W");
assertEquals(new Integer(8), new Integer(term.getWeeks()));
}
public void testMonths() throws ParseException {
term.setInterval("P6M");
assertEquals(new Integer(6), new Integer(term.getMonths()));
}
public void testHours() throws ParseException {
term.setInterval("PT10H");
assertEquals(new Integer(10), new Integer(term.getHours()));
}
public void testMinutes() throws ParseException {
term.setInterval("PT72M");
assertEquals(new Integer(72), new Integer(term.getMinutes()));
}
public void testSeconds() throws ParseException {
term.setInterval("PT45S");
assertEquals(new Integer(45), new Integer(term.getSeconds()));
}
public void testCombination() throws ParseException {
term.setInterval("P1M10DT1H2M30S");
assertEquals(new Integer(1), new Integer(term.getMonths()));
assertEquals(new Integer(10), new Integer(term.getDays()));
assertEquals(new Integer(1), new Integer(term.getHours()));
assertEquals(new Integer(2), new Integer(term.getMinutes()));
assertEquals(new Integer(30), new Integer(term.getSeconds()));
term.setInterval("P15Y6DT10H");
assertEquals(new Integer(15), new Integer(term.getYears()));
assertEquals(new Integer(6), new Integer(term.getDays()));
assertEquals(new Integer(10), new Integer(term.getHours()));
}
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
term = new DateIntervalTerm("24d");
}
}

View File

@ -0,0 +1,402 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/tests/ParserTest.java,v 1.2 2003/12/04 15:28:33 rsegelman Exp $ */
package org.realtor.rets.validation.tests;
import org.junit.jupiter.api.Test;
import org.realtor.rets.validation.ValidationExpressionEvaluator;
import org.realtor.rets.validation.terms.*;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* ParserTest.java Created Sep 5, 2003
* <p>
* <p>
* Copyright 2003, Avantia inc.
*
* @author scohen
* @version $Revision: 1.2 $
*/
public class ParserTest {
private ValidationExpressionEvaluator evaluator;
@Test
public void testSingleTerm() {
NumericTerm rv = (NumericTerm) evaluateExpression("5");
assertEquals(rv.getValue(), new Double(5));
}
public void testStringAddition() {
Term result = evaluateExpression("\"3\" + \"1\"");
assertEquals(new Double(4), result.getValue());
}
public void testSimpleAddition() {
NumericTerm result = (NumericTerm) evaluateExpression("5 + 1");
assertEquals(new Double(6), result.getValue());
}
public void testSimpleSubtraction() {
NumericTerm result = (NumericTerm) evaluateExpression("10 - 5");
assertEquals(new Double(5), result.getValue());
}
public void testMultiplePositiveSubtraction() {
NumericTerm result = (NumericTerm) evaluateExpression("20 - 3 - 10");
assertEquals(new Double(7), result.getValue());
}
public void testNegativeSubtraction() {
NumericTerm term = (NumericTerm) evaluateExpression("3 - 5");
assertEquals(new Double(-2), term.getValue());
}
public void testDivision() {
NumericTerm term = (NumericTerm) evaluateExpression("10/5");
assertEquals(new Double(2), term.getValue());
}
public void testMultipleNegative() {
NumericTerm term = (NumericTerm) evaluateExpression("3 - 5 - 8");
assertEquals(new Double(-10), term.getValue());
}
public void testMultipleAdds() {
NumericTerm term = (NumericTerm) evaluateExpression("5 + 6 + 3");
assertEquals(new Double(14), term.getValue());
}
public void testMultipleAssortedOperations() {
NumericTerm term = (NumericTerm) evaluateExpression("5 * 3 + 4");
assertEquals(new Double(19), term.getValue());
}
public void testFourOperations() {
NumericTerm term = (NumericTerm) evaluateExpression("3 * 4 * 6 * 10");
assertEquals(new Double(720), term.getValue());
}
public void testSimpleOrderOfOperations() {
NumericTerm term = (NumericTerm) evaluateExpression("5 + 6 * 8");
assertEquals(new Double(53), term.getValue());
}
public void testComplexOrderOfOperations() {
NumericTerm term = (NumericTerm) evaluateExpression("5 - 6 * 5 - 2");
assertEquals(new Double(-27), term.getValue());
}
public void testMoreComplexOrderOfOperations() {
NumericTerm term = (NumericTerm) evaluateExpression("5 - 6 * 5 * 3 - 2");
assertEquals(new Double(-87), term.getValue());
}
public void testSimpleParenthetical() {
NumericTerm term = (NumericTerm) evaluateExpression("(3 * 5)");
assertEquals(new Double(15), term.getValue());
}
public void testUselessParenthetical() {
NumericTerm term = (NumericTerm) evaluateExpression("(((32)))");
assertEquals(new Double(32), term.getValue());
}
public void testPrefixParenthetical() {
NumericTerm term = (NumericTerm) evaluateExpression("(3 + 4) * 2");
assertEquals(new Double(14), term.getValue());
}
public void testPostfixParenthetical() {
NumericTerm term = (NumericTerm) evaluateExpression("2 * ( 3 + 4)");
assertEquals(new Double(14), term.getValue());
}
public void testNestedParenthetical() {
NumericTerm term = (NumericTerm) evaluateExpression("((1 + 9) + 7) * 3");
assertEquals(new Double(51), term.getValue());
}
public void testComplexParenthetica() {
NumericTerm term = (NumericTerm) evaluateExpression("((2+4)*(7-2)*3)+5");
assertEquals(new Double(95), term.getValue());
}
public void testMaddeninglyComplexParenthetical() {
NumericTerm term = (NumericTerm) evaluateExpression(
"(((2+4)* 6) * 2) - (6 * 5) + 4 - 2");
assertEquals(new Double(44), term.getValue());
}
public void testSimpleTripleParenthetical() {
NumericTerm term = (NumericTerm) evaluateExpression("( 3 + 4 + 5 + 6)");
assertEquals(new Double(18), term.getValue());
}
public void testTripleParenthetical() {
NumericTerm term = (NumericTerm) evaluateExpression(
"( 3 + (4 + 5) + 7)");
assertEquals(new Double(19), term.getValue());
}
public void testSimpleBoolean() {
BooleanTerm term = (BooleanTerm) evaluateExpression("(3 = 3)");
assertEquals(new Boolean(true), term.getValue());
}
public void testSimpleGreaterThan() {
Term term = evaluateExpression("(10 > 3)");
assertEquals(new Boolean(true), term.getValue());
}
public void testArithmeticComparison() {
Term term = evaluateExpression(" (10 + 4) = 14");
assertEquals(new Boolean(true), term.getValue());
}
public void greaterThanTest() {
Term term = evaluateExpression("10 > 3");
assertEquals(new Boolean(true), term.getValue());
}
public void testGreaterThanOrEqualTo() {
Term term = evaluateExpression("10 >= 9");
assertEquals(new Boolean(true), term.getValue());
term = evaluateExpression("10 >= 10");
assertEquals(new Boolean(true), term.getValue());
term = evaluateExpression("10 >= 11");
assertEquals(new Boolean(false), term.getValue());
}
public void testLessThanOrEqualTo() {
Term term = evaluateExpression("9 <= 10");
assertEquals(new Boolean(true), term.getValue());
term = evaluateExpression("10 <= 10");
assertEquals(new Boolean(true), term.getValue());
term = evaluateExpression("11 <= 10");
assertEquals(new Boolean(false), term.getValue());
}
@Test
public void testComplexBooleanExpression() {
String expr = "(3 + 4) > (3 * 4)";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(false), term.getValue());
expr = "(3+4) > 3 * 4";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(false), term.getValue());
expr = "(3+4) < (3 * 4)";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(3 + 4 ) < 3 * 4";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
}
@Test
public void testStringComparison() {
String expr = "\"One\" = \"One\"";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "\"One\" = \"one\"";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(false), term.getValue());
expr = "\"One\" != \"one\"";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
}
public void testContainsOperator() {
String expr = "\"Everyone\" .CONTAINS. \"very\"";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "\"Someone\" .CONTAINS. \"everyone\"";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(false), term.getValue());
}
public void testOrOperator() {
String expr = "(\"Someone\" .CONTAINS. \"me\") .OR. ( \"Test\" = \"false\")";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(\"Someone\" .CONTAINS. \"time\") .OR. ( \"Test\" = \"false\")";
// assertEquals(expr, new Boolean(true), term.getValue());
}
/*
public void testQuotedDateAddition() {
String expr = " (\"2003-09-15\" + \"P3D\") = 2003-09-18 ";
Term term = evaluateExpression(expr);
assertEquals(expr,new Boolean(true),term.getValue());
}
*/
public void testDateComparison() {
String expr = "2000-06-30 = 2000-06-30";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
}
public void testDateAddition() {
String expr = "2002-09-10 + 5";
Term term = evaluateExpression(expr);
// try {
// assertEquals(expr, new DateTerm("2002-09-15").getValue(),
// term.getValue());
// } catch (ParseException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
public void testDivisionOperator() {
String expr = " 10 / 5";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Double(2), term.getValue());
expr = "7 .MOD. 3";
term = evaluateExpression(expr);
// assertEquals(expr, new Double(1), term.getValue());
}
public void testUnaryNot() {
String expr = ".NOT. ( 3 = 5)";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
}
public void testComplexBooleanExpressionWithNot() {
String expr = (" (.NOT. 2003-09-15 = 2003-09-15) .OR. ( ( 3 = 5))");
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(false), term.getValue());
expr = "(.NOT. 3 = 98 .AND. 25 = 5)";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(100 + 50 - 75) = ( 70 + 5)";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
}
public void testDateIntervalExpression() throws ParseException {
String expr = "(2003-09-15 + P1D)";
Term term = evaluateExpression(expr);
// assertEquals(expr, new DateTerm("2003-09-16").getValue(),
// term.getValue());
expr = "(2003-09-15 - P1D)";
term = evaluateExpression(expr);
// assertEquals(expr, new DateTerm("2003-09-14").getValue(),
// term.getValue());
}
public void testDateSubtraction() {
String expr = "(2003-09-11 - 2003-09-10) = P1D";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(2003-09-11 - 2003-09-04) = P1W";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(2003-09-11 - 2002-09-11) = P1Y";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
}
public void testVariableExpression() throws ParseException {
HashMap values = new HashMap();
values.put("ListPrice", new NumericTerm("100000"));
values.put("AgentName", new StringTerm("John Smith"));
values.put("ListDate", new DateTerm("2003-09-14"));
setSymbolTable(values);
String expr = "( ListPrice = 100000)";
Term term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(ListPrice - 1000 ) = 99000";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(AgentName = \"John Smith\")";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "ListDate = 2003-09-14";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(2003-09-19 - P1D)";
term = evaluateExpression(expr);
// assertEquals(expr, new DateTerm("2003-09-18").getValue(),
// term.getValue());
}
public void testComplexDateMath() throws Exception {
Term term;
String expr;
HashMap values = new HashMap();
values.put("Sept11", new DateTerm("2001-09-11"));
values.put(".TODAY.", new DateTerm());
setSymbolTable(values);
expr = "(2003-09-18 - P1D ) < 2003-09-18";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(Sept11 <= ( .TODAY. - P3M))";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(( .TODAY. - P1M) < .TODAY.)";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
expr = "(Sept11 < ( .TODAY. - P1Y)) .AND. ( .TODAY. > Sept11 - P3M))";
term = evaluateExpression(expr);
// assertEquals(expr, new Boolean(true), term.getValue());
}
public void testEverything() throws Exception {
HashMap values = new HashMap();
values.put("Sept11", new DateTerm("2001-09-11"));
values.put(".TODAY.", new DateTerm());
setSymbolTable(values);
String expr = " (.TODAY. - ( 18 .MOD. 4) ) > ( .TODAY. - ( 4 * 3 )) .AND. ( Sept11 - P1Y < .TODAY.)";
Term term = evaluateExpression(expr);
assertEquals(new Boolean(true), term.getValue());
}
/**
* @param values
*/
private void setSymbolTable(HashMap values) {
evaluator.setSymbolTable(values);
}
private Term evaluateExpression(String exp) {
try {
Term rv = evaluator.eval(exp);
return rv;
} catch (InvalidTermException e) {
e.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
evaluator = new ValidationExpressionEvaluator();
}
}

View File

@ -0,0 +1,113 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/tests/RETSUpdateValidatorTest.java,v 1.1.1.1 2003/11/21 16:20:05 rsegelman Exp $ */
package org.realtor.rets.validation.tests;
import com.ossez.usreio.common.util.XMLUtils;
import org.junit.jupiter.api.Test;
import org.realtor.rets.validation.RETSUpdateValidator;
import org.realtor.rets.validation.UpdateField;
import org.realtor.rets.validation.ValidationExpressionEvaluator;
import org.realtor.rets.validation.terms.InvalidTermException;
import org.realtor.rets.validation.terms.StringTerm;
import org.realtor.rets.validation.terms.Term;
import org.w3c.dom.Document;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* RETSUpdateValidatorTest.java Created Sep 26, 2003
*
*
* Copyright 2003, Avantia inc.
* @version $Revision: 1.1.1.1 $
* @author scohen
*/
public class RETSUpdateValidatorTest {
private static boolean setUp = false;
private static Document doc;
private static List list;
private static RETSUpdateValidator validator;
private String xmlFile = "/home/scohen/metadataSample2.xml";
private ValidationExpressionEvaluator evaluator;
/**
*
*/
public RETSUpdateValidatorTest() {
evaluator = new ValidationExpressionEvaluator();
// TODO Auto-generated constructor stub
}
public void setUp() {
if (setUp) {
return;
}
try {
validator = new RETSUpdateValidator();
FileInputStream fis = new FileInputStream("/tmp/retsmetadata.xml");
StringBuffer xmlDoc = new StringBuffer();
int read;
while ((read = fis.read()) >= 0) {
xmlDoc.append((char) read);
}
Document doc = XMLUtils.stringToDocument(xmlDoc.toString());
System.out.println("Doc: " + doc);
// set up Symbol table
Map table = new HashMap();
table.put(".ENTRY.", new StringTerm("Test"));
table.put(".EMPTY.", new StringTerm(""));
validator.setSymbolTable(table);
validator.setMetaData(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testEmpty() {
validator.validate();
}
/*
public void testValidationID() {
UpdateField yadda = (UpdateField) list.get(4);
System.out.println("ID is " + yadda.getValidationExpressionIDs());
assertEquals("Should be 551", "551", yadda.getValidationExpressionIDs());
yadda = (UpdateField) list.get(5);
System.out.println("ID is " + yadda.getValidationExpressionIDs());
assertEquals("Should be 561", "561", yadda.getValidationExpressionIDs());
}
public void testValidationExpression() {
UpdateField field = (UpdateField) list.get(4);
assertNotNull(field.getValidationExpressions());
assertEquals(
field.getValidationExpressions()[0],
"(List_Agent=.AGENTCODE. .OR. .USERCLASS. > 2) .AND. .USERLEVEL. > 2");
field = (UpdateField) list.get(5);
assertNotNull(field.getValidationExpressions());
assertEquals(
field.getValidationExpressions()[0],
"(List_Office=.BROKERBRANCH. .OR. .USERCLASS. > 2) .AND. .USERLEVEL. > 2");
}
*/
public void testEntry() throws InvalidTermException {
Term t = evaluator.eval(".ENTRY. = .EMPTY.");
assertEquals(new Boolean(false), t.getValue());
}
}

View File

@ -0,0 +1,268 @@
/* $Header: /usr/local/cvsroot/rets/validation/src/org/realtor/rets/validation/tests/TokenizerTest.java,v 1.1.1.1 2003/11/21 16:20:05 rsegelman Exp $ */
package org.realtor.rets.validation.tests;
import org.junit.jupiter.api.Test;
import org.realtor.rets.validation.RetsTokenParser;
import org.realtor.rets.validation.operators.*;
import org.realtor.rets.validation.terms.*;
import java.text.ParseException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* TokenizerTest.java Created Sep 10, 2003
* <p>
* <p>
* Copyright 2003, Avantia inc.
*
* @author scohen
* @version $Revision: 1.1.1.1 $
*/
public class TokenizerTest {
private RetsTokenParser tokenizer;
public TokenizerTest() {
}
@Test
public void testNullExpression() {
tokenizer.setExpression("");
assertNull(tokenizer.nextToken());
tokenizer.setExpression(" ");
assertNull(tokenizer.nextToken());
}
public void testSingleNumericToken() {
tokenizer.setExpression("3");
Term t = (Term) tokenizer.nextToken();
assertIntTermValue(t, 3);
tokenizer.setExpression("150");
t = (Term) tokenizer.nextToken();
assertIntTermValue(t, 150);
tokenizer.setExpression(" 1500 ");
t = (Term) tokenizer.nextToken();
assertIntTermValue(t, 1500);
}
public void testSingleOperator() {
tokenizer.setExpression("+");
Operator oper = (Operator) tokenizer.nextToken();
assertEquals(oper, new AdditionOperator());
tokenizer.setExpression("-");
oper = (Operator) tokenizer.nextToken();
assertEquals(oper, new SubtractionOperator());
tokenizer.setExpression("*");
oper = (Operator) tokenizer.nextToken();
assertEquals(oper, new MultiplicationOperator());
tokenizer.setExpression(">");
oper = (Operator) tokenizer.nextToken();
assertEquals(oper, new GreaterThanOperator());
tokenizer.setExpression("<");
oper = (Operator) tokenizer.nextToken();
assertEquals(oper, new LessThanOperator());
tokenizer.setExpression("=");
oper = (Operator) tokenizer.nextToken();
assertEquals(oper, new EqualsOperator());
}
public void testCompoundOperators() {
Operator oper;
tokenizer.setExpression(">=");
oper = (Operator) tokenizer.nextToken();
assertEquals(new GreaterThanOrEqualToOperator(), oper);
tokenizer.setExpression("!=");
assertCorrectOperator(tokenizer.nextToken(), new NotEqualsOperator());
}
public void testSingleDottedOperators() {
tokenizer.setExpression(".CONTAINS.");
assertCorrectOperator(tokenizer.nextToken(), new ContainsOperator());
tokenizer.setExpression(".OR.");
assertCorrectOperator(tokenizer.nextToken(), new OrOperator());
tokenizer.setExpression(".AND.");
assertCorrectOperator(tokenizer.nextToken(), new AndOperator());
}
public void testReadSingleQuotedString() {
tokenizer.setExpression("\"QuotedString\"");
StringTerm term = (StringTerm) tokenizer.nextToken();
assertEquals("QuotedString", term.getValue());
tokenizer.setExpression("\"Quoted String\"");
term = (StringTerm) tokenizer.nextToken();
assertEquals("Quoted String", term.getValue());
tokenizer.setExpression("\" \"");
term = (StringTerm) tokenizer.nextToken();
assertEquals(" ", term.getValue());
}
public void testSimpleExpression() {
tokenizer.setExpression("1 + 3");
Term t = (Term) tokenizer.nextToken();
assertIntTermValue(t, 1);
Operator o = (Operator) tokenizer.nextToken();
assertEquals(o, new AdditionOperator());
assertIntTermValue((Term) tokenizer.nextToken(), 3);
}
public void testQuotedStrings() {
String expr = "\"First String\" = \"SecondString\"";
// should have three tokens;
tokenizer.setExpression(expr);
StringTerm firstTerm = (StringTerm) tokenizer.nextToken();
assertCorrectOperator(tokenizer.nextToken(), new EqualsOperator());
StringTerm secondTerm = (StringTerm) tokenizer.nextToken();
assertEquals("First String", firstTerm.getValue());
assertEquals("SecondString", secondTerm.getValue());
}
public void testGreaterThan() {
tokenizer.setExpression("10>2");
assertIntTermValue(tokenizer.nextToken(), 10);
assertCorrectOperator(tokenizer.nextToken(), new GreaterThanOperator());
assertIntTermValue(tokenizer.nextToken(), 2);
}
public void testParentheticalOperators() {
tokenizer.setExpression("()");
assertCorrectOperator(tokenizer.nextToken(), new OpenParen());
assertCorrectOperator(tokenizer.nextToken(), new CloseParen());
}
public void testParenthesizedEquation() {
tokenizer.setExpression("(1+3)");
Operator o = (Operator) tokenizer.nextToken();
assertIntTermValue((Term) tokenizer.nextToken(), 1);
assertCorrectOperator(tokenizer.nextToken(), new AdditionOperator());
assertIntTermValue(tokenizer.nextToken(), 3);
assertCorrectOperator(tokenizer.nextToken(), new CloseParen());
}
public void testParentheticalGreaterThan() {
tokenizer.setExpression("(10>2)");
assertCorrectOperator(tokenizer.nextToken(), new OpenParen());
assertIntTermValue(tokenizer.nextToken(), 10);
assertCorrectOperator(tokenizer.nextToken(), new GreaterThanOperator());
assertIntTermValue(tokenizer.nextToken(), 2);
assertCorrectOperator(tokenizer.nextToken(), new CloseParen());
}
public void testNotEqualsExpression() {
String expr = "3 != 4";
tokenizer.setExpression(expr);
assertIntTermValue(tokenizer.nextToken(), 3);
assertCorrectOperator(tokenizer.nextToken(), new NotEqualsOperator());
assertIntTermValue(tokenizer.nextToken(), 4);
}
public void testDateExpression() {
String expr = "2002-09-10";
tokenizer.setExpression(expr);
assertEquals(DateTerm.class, tokenizer.nextToken().getClass());
expr = "2009-09-10 = 2002-09-10";
tokenizer.setExpression(expr);
assertEquals(DateTerm.class, tokenizer.nextToken().getClass());
assertCorrectOperator(tokenizer.nextToken(), new EqualsOperator());
assertEquals(DateTerm.class, tokenizer.nextToken().getClass());
}
public void testDateAddition() {
String expr = "2002-09-10 + 5";
tokenizer.setExpression(expr);
assertEquals(DateTerm.class, tokenizer.nextToken().getClass());
assertCorrectOperator(tokenizer.nextToken(), new AdditionOperator());
assertIntTermValue(tokenizer.nextToken(), 5);
}
public void testDateInterval() {
String expr = "P1M";
tokenizer.setExpression(expr);
// assertEquals(expr, DateIntervalTerm.class,
// tokenizer.nextToken().getClass());
}
public void testVariables() {
String expr = "ListPrice";
tokenizer.setExpression(expr);
// assertEquals(expr, VariableTerm.class, tokenizer.nextToken().getClass());
}
public void testModOperator() {
String expr = ".MOD.";
tokenizer.setExpression(expr);
assertCorrectOperator(tokenizer.nextToken(), new ModOperator());
expr = "7 .MOD. 3 ";
tokenizer.setExpression(expr);
assertIntTermValue(tokenizer.nextToken(), 7);
assertCorrectOperator(tokenizer.nextToken(), new ModOperator());
assertIntTermValue(tokenizer.nextToken(), 3);
}
public void testNotOperator() {
String expr = ".NOT.";
tokenizer.setExpression(expr);
assertCorrectOperator(tokenizer.nextToken(), new NotOperator());
expr = (".NOT. ( 3 = 5)");
tokenizer.setExpression(expr);
assertCorrectOperator(tokenizer.nextToken(), new NotOperator());
assertCorrectOperator(tokenizer.nextToken(), new OpenParen());
assertIntTermValue(tokenizer.nextToken(), 3);
assertCorrectOperator(tokenizer.nextToken(), new EqualsOperator());
assertIntTermValue(tokenizer.nextToken(), 5);
assertCorrectOperator(tokenizer.nextToken(), new CloseParen());
}
public void testDateRange() throws ParseException {
String expr = "(2003-09-18 - P1D )> 2003-09-17";
tokenizer.setExpression(expr);
assertCorrectOperator(tokenizer.nextToken(), new OpenParen());
assertEquals(((Term) tokenizer.nextToken()).getValue(),
new DateTerm("2003-09-18").getValue());
assertCorrectOperator(tokenizer.nextToken(), new SubtractionOperator());
assertEquals(((Term) tokenizer.nextToken()).getValue(),
new DateIntervalTerm("P1D").getValue());
assertCorrectOperator(tokenizer.nextToken(), new CloseParen());
assertCorrectOperator(tokenizer.nextToken(), new GreaterThanOperator());
assertEquals(new DateTerm("2003-09-17").getValue(),
((DateTerm) tokenizer.nextToken()).getValue());
}
public void assertCorrectOperator(Object toTest, Operator expected) {
assertEquals(expected, toTest);
}
private void assertIntTermValue(Object t, long val) {
// assertTrue(t + " is not an int term", t instanceof NumericTerm);
assertEquals(new Double(val), ((NumericTerm) t).getValue());
}
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
tokenizer = new RetsTokenParser();
tokenizer.setTermFactory(new TermFactory());
}
}

View File

@ -0,0 +1,22 @@
package org.realtor.rets.validation.tests;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author YuCheng
*/
public class VariableTest {
private final static Logger logger = LoggerFactory.getLogger(VariableTest.class);
/**
* Do RetsServerConnection Test
*/
@Test
public void testStaticVariableChange() {
}
}

View File

@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE RelativeLayout>
<Configuration status="WARN">
<Properties>
<Property name="baseDir">/home/logs/reoc/services/</Property>
</Properties>
<Appenders>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- C O N S O L E - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout pattern="%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n" />
<ThresholdFilter level="TRACE" onMatch="ACCEPT" onMismatch="DENY" />
</Console>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- D E B U G _ F I L E - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<RollingFile name="FILE_DEBUG" append="true" fileName="${baseDir}/services_debug.log" filePattern="${baseDir}/$${date:yyyy-MM}/services-debug-%d{yyyy-MM-dd}-%i.log.gz">
<ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout>
<pattern>%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"></SizeBasedTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy max="12" />
</RollingFile>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- I N F O _ F I L E - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<RollingFile name="FILE_INFO" append="true" fileName="${baseDir}/services_info.log" filePattern="${baseDir}/$${date:yyyy-MM}/services-info-%d{yyyy-MM-dd}.log.gz">
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout>
<pattern>%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"></SizeBasedTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy max="12" />
</RollingFile>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- F I L E _ W A R N - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<RollingFile name="FILE_WARN" append="true" fileName="${baseDir}/services_info.log" filePattern="${baseDir}/$${date:yyyy-MM}/services-warn-%d{yyyy-MM-dd}.log.gz">
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout>
<pattern>%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"></SizeBasedTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy max="12" />
</RollingFile>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- F I L E _ E R R O R - A P P E N D E R -->
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<RollingFile name="FILE_ERROR" append="true" fileName="${baseDir}/services_error.log" filePattern="${baseDir}/$${date:yyyy-MM}/services-error-%d{yyyy-MM-dd}.log.gz">
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout>
<pattern>%-d{yyyy/MM/dd HH:mm:ss} %-5p [%c] - %m%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"></SizeBasedTriggeringPolicy>
</Policies>
<DefaultRolloverStrategy max="12" />
</RollingFile>
</Appenders>
<!-- LOGGERS -->
<Loggers>
<Logger name="com" level="TRACE" additivity="false">
<AppenderRef ref="CONSOLE" level="DEBUG" />
<AppenderRef ref="FILE_DEBUG" level="DEBUG" />
<AppenderRef ref="FILE_INFO" level="INFO" />
<AppenderRef ref="FILE_WARN" level="WARN" />
<AppenderRef ref="FILE_ERROR" level="ERROR" />
</Logger>
<root level="TRACE">
</root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8" ?>
<configuration debug="true">
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned by default the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
</Pattern>
</layout>
</appender>
<root level="debug">
<appender-ref ref="STDOUT"/>
</root>
</configuration>