Change license to Apache2 and reformat

This commit is contained in:
rbygrave committed 2012-09-15 00:00:08 +12:00
1 parent 96ce4c0ddf
commit 7aae897def
560 files changed
+73292 -85907

No files matched your search

@@ -1,40 +1,23 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general exception when creating an Object.
*/
public class CreateObjectException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539736L;
public CreateObjectException(Exception cause) {
super(cause);
}
public CreateObjectException(String s, Exception cause) {
super(s, cause);
}
public CreateObjectException(String s) {
super(s);
}
}
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general exception when creating an Object.
*/
public class CreateObjectException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539736L;
public CreateObjectException(Exception cause) {
super(cause);
}
public CreateObjectException(String s, Exception cause) {
super(s, cause);
}
public CreateObjectException(String s) {
super(s);
}
}
@@ -1,345 +1,328 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
/**
* A lightweight tree structure for simple XML handling.
* <p>
* It removes support for nodes being mixed with content. That is, a node can
* only contain content or a list of one or more child nodes. It does not
* support mixing bits of content between the child nodes.
* </p>
* <p>
* Although designed to simplify XML in supported cases it can be used as a
* general tree structure with attributes of java Objects.
* </p>
*/
public class Dnode {
int level;
String nodeName;
String nodeContent;
ArrayList<Dnode> children;
LinkedHashMap<String, String> attrList = new LinkedHashMap<String, String>();
/**
* Create a node.
*/
public Dnode() {
}
/**
* Parse the raw XML string.
*/
public static Dnode parse(String s){
DnodeReader r = new DnodeReader();
return r.parseXml(s);
}
/**
* Return the node as XML.
*/
public String toXml() {
StringBuilder sb = new StringBuilder();
generate(sb);
return sb.toString();
}
/**
* Generate this node as xml to the buffer.
*/
public StringBuilder generate(StringBuilder sb) {
if (sb == null) {
sb = new StringBuilder();
}
sb.append("<").append(nodeName);
Iterator<String> it = attributeNames();
while (it.hasNext()) {
String attr = it.next();
Object attrValue = getAttribute(attr);
sb.append(" ").append(attr).append("=\"");
if (attrValue != null) {
sb.append(attrValue);
}
sb.append("\"");
}
if (nodeContent == null && !hasChildren()) {
sb.append(" />");
} else {
sb.append(">");
if (children != null && children.size() > 0) {
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.generate(sb);
}
}
if (nodeContent != null) {
sb.append(nodeContent);
}
sb.append("</").append(nodeName).append(">");
}
return sb;
}
/**
* Return the node name.
*/
public String getNodeName() {
return nodeName;
}
/**
* Set the node name.
*/
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
/**
* Return the node content.
*/
public String getNodeContent() {
return nodeContent;
}
/**
* Set the node content.
*/
public void setNodeContent(String nodeContent) {
this.nodeContent = nodeContent;
}
/**
* Return true if this node has children.
*/
public boolean hasChildren() {
return getChildrenCount() > 0;
}
/**
* Return the number of children this node has.
*/
public int getChildrenCount() {
if (children == null) {
return 0;
}
return children.size();
}
/**
* Remove a ancestor node.
*/
public boolean remove(Dnode node) {
if (children == null) {
return false;
}
if (children.remove(node)) {
return true;
}
Iterator<Dnode> it = children.iterator();
while (it.hasNext()) {
Dnode child = it.next();
if (child.remove(node)) {
return true;
}
}
return false;
}
/**
* List of children nodes.
*/
public List<Dnode> children() {
if (children == null) {
return null;
}
return children;
}
/**
* Add a child.
*/
public void addChild(Dnode child) {
if (children == null) {
children = new ArrayList<Dnode>();
}
children.add(child);
child.setLevel(level + 1);
}
/**
* Return the level or depth of the node from the root.
*/
public int getLevel() {
return level;
}
/**
* Set the level or depth of this node from the root.
*/
public void setLevel(int level) {
this.level = level;
if (children != null) {
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.setLevel(level + 1);
}
}
}
/**
* Find the first matching node using nodeName. This is a depth first tree
* search.
*/
public Dnode find(String nodeName) {
return find(nodeName, null, null);
}
/**
* Find the first node matching nodeName and attribute value. This is a
* depth first tree search.
*/
public Dnode find(String nodeName, String attrName, Object value) {
return find(nodeName, attrName, value, -1);
}
/**
* Search for a single node with control over maxLevel. Find the first node
* matching nodeName and attribute value. If attrName and value are null
* then this will just search using the nodeName. This is a depth first tree
* search. Once a matching node is found the search will stop.
*/
public Dnode find(String nodeName, String attrName, Object value, int maxLevel) {
ArrayList<Dnode> list = new ArrayList<Dnode>();
findByNode(list, nodeName, true, attrName, value, maxLevel);
if (list.size() >= 1) {
return list.get(0);
}
return null;
}
/**
* Find all the nodes that match the nodeName.
*
*/
public List<Dnode> findAll(String nodeName, int maxLevel) {
int level = -1;
if (maxLevel > 0) {
level = this.level + maxLevel;
}
return findAll(nodeName, null, null, level);
}
/**
* Find all the nodes that match the nodeName and attribute value.
*/
public List<Dnode> findAll(String nodeName, String attrName, Object value, int maxLevel) {
if (nodeName == null && attrName == null) {
throw new RuntimeException("You can not have both nodeName and attrName null");
}
ArrayList<Dnode> list = new ArrayList<Dnode>();
findByNode(list, nodeName, false, attrName, value, maxLevel);
return list;
}
/**
* Used for recursive calling.
*/
private void findByNode(List<Dnode> list, String node, boolean findOne,String attrName, Object value, int maxLevel) {
if (findOne && list.size() == 1) {
return;
}
if (node == null || node.equals(nodeName)) {
if (attrName == null || value.equals(getAttribute(attrName))) {
list.add(this);
if (findOne) {
return;
}
}
}
if (maxLevel > 0 && level >= maxLevel) {
// hit max level
} else if (children != null) {
// recursively search the children
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.findByNode(list, node, findOne, attrName, value,maxLevel);
}
}
}
/**
* The attribute names as strings.
*/
public Iterator<String> attributeNames() {
return attrList.keySet().iterator();
}
/**
* Return the attribute for a given name.
*/
public String getAttribute(String name) {
return attrList.get(name);
}
/**
* Returns an Attribute as a String.
* <p>
* Will throw a ClassCastException if the attribute is not a String.
* </p>
*/
public String getStringAttr(String name, String defaultValue) {
Object o = attrList.get(name);
if (o == null){
return defaultValue;
} else {
return o.toString();
}
}
/**
* Set an attribute.
*/
public void setAttribute(String name, String value) {
attrList.put(name, value);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[").append(getNodeName()).append(" ").append(attrList).append("]");
return sb.toString();
}
}
package com.avaje.ebeaninternal.server.lib.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
/**
* A lightweight tree structure for simple XML handling.
* <p>
* It removes support for nodes being mixed with content. That is, a node can
* only contain content or a list of one or more child nodes. It does not
* support mixing bits of content between the child nodes.
* </p>
* <p>
* Although designed to simplify XML in supported cases it can be used as a
* general tree structure with attributes of java Objects.
* </p>
*/
public class Dnode {
int level;
String nodeName;
String nodeContent;
ArrayList<Dnode> children;
LinkedHashMap<String, String> attrList = new LinkedHashMap<String, String>();
/**
* Create a node.
*/
public Dnode() {
}
/**
* Parse the raw XML string.
*/
public static Dnode parse(String s){
DnodeReader r = new DnodeReader();
return r.parseXml(s);
}
/**
* Return the node as XML.
*/
public String toXml() {
StringBuilder sb = new StringBuilder();
generate(sb);
return sb.toString();
}
/**
* Generate this node as xml to the buffer.
*/
public StringBuilder generate(StringBuilder sb) {
if (sb == null) {
sb = new StringBuilder();
}
sb.append("<").append(nodeName);
Iterator<String> it = attributeNames();
while (it.hasNext()) {
String attr = it.next();
Object attrValue = getAttribute(attr);
sb.append(" ").append(attr).append("=\"");
if (attrValue != null) {
sb.append(attrValue);
}
sb.append("\"");
}
if (nodeContent == null && !hasChildren()) {
sb.append(" />");
} else {
sb.append(">");
if (children != null && children.size() > 0) {
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.generate(sb);
}
}
if (nodeContent != null) {
sb.append(nodeContent);
}
sb.append("</").append(nodeName).append(">");
}
return sb;
}
/**
* Return the node name.
*/
public String getNodeName() {
return nodeName;
}
/**
* Set the node name.
*/
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
/**
* Return the node content.
*/
public String getNodeContent() {
return nodeContent;
}
/**
* Set the node content.
*/
public void setNodeContent(String nodeContent) {
this.nodeContent = nodeContent;
}
/**
* Return true if this node has children.
*/
public boolean hasChildren() {
return getChildrenCount() > 0;
}
/**
* Return the number of children this node has.
*/
public int getChildrenCount() {
if (children == null) {
return 0;
}
return children.size();
}
/**
* Remove a ancestor node.
*/
public boolean remove(Dnode node) {
if (children == null) {
return false;
}
if (children.remove(node)) {
return true;
}
Iterator<Dnode> it = children.iterator();
while (it.hasNext()) {
Dnode child = it.next();
if (child.remove(node)) {
return true;
}
}
return false;
}
/**
* List of children nodes.
*/
public List<Dnode> children() {
if (children == null) {
return null;
}
return children;
}
/**
* Add a child.
*/
public void addChild(Dnode child) {
if (children == null) {
children = new ArrayList<Dnode>();
}
children.add(child);
child.setLevel(level + 1);
}
/**
* Return the level or depth of the node from the root.
*/
public int getLevel() {
return level;
}
/**
* Set the level or depth of this node from the root.
*/
public void setLevel(int level) {
this.level = level;
if (children != null) {
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.setLevel(level + 1);
}
}
}
/**
* Find the first matching node using nodeName. This is a depth first tree
* search.
*/
public Dnode find(String nodeName) {
return find(nodeName, null, null);
}
/**
* Find the first node matching nodeName and attribute value. This is a
* depth first tree search.
*/
public Dnode find(String nodeName, String attrName, Object value) {
return find(nodeName, attrName, value, -1);
}
/**
* Search for a single node with control over maxLevel. Find the first node
* matching nodeName and attribute value. If attrName and value are null
* then this will just search using the nodeName. This is a depth first tree
* search. Once a matching node is found the search will stop.
*/
public Dnode find(String nodeName, String attrName, Object value, int maxLevel) {
ArrayList<Dnode> list = new ArrayList<Dnode>();
findByNode(list, nodeName, true, attrName, value, maxLevel);
if (list.size() >= 1) {
return list.get(0);
}
return null;
}
/**
* Find all the nodes that match the nodeName.
*
*/
public List<Dnode> findAll(String nodeName, int maxLevel) {
int level = -1;
if (maxLevel > 0) {
level = this.level + maxLevel;
}
return findAll(nodeName, null, null, level);
}
/**
* Find all the nodes that match the nodeName and attribute value.
*/
public List<Dnode> findAll(String nodeName, String attrName, Object value, int maxLevel) {
if (nodeName == null && attrName == null) {
throw new RuntimeException("You can not have both nodeName and attrName null");
}
ArrayList<Dnode> list = new ArrayList<Dnode>();
findByNode(list, nodeName, false, attrName, value, maxLevel);
return list;
}
/**
* Used for recursive calling.
*/
private void findByNode(List<Dnode> list, String node, boolean findOne,String attrName, Object value, int maxLevel) {
if (findOne && list.size() == 1) {
return;
}
if (node == null || node.equals(nodeName)) {
if (attrName == null || value.equals(getAttribute(attrName))) {
list.add(this);
if (findOne) {
return;
}
}
}
if (maxLevel > 0 && level >= maxLevel) {
// hit max level
} else if (children != null) {
// recursively search the children
for (int i = 0; i < children.size(); i++) {
Dnode child = children.get(i);
child.findByNode(list, node, findOne, attrName, value,maxLevel);
}
}
}
/**
* The attribute names as strings.
*/
public Iterator<String> attributeNames() {
return attrList.keySet().iterator();
}
/**
* Return the attribute for a given name.
*/
public String getAttribute(String name) {
return attrList.get(name);
}
/**
* Returns an Attribute as a String.
* <p>
* Will throw a ClassCastException if the attribute is not a String.
* </p>
*/
public String getStringAttr(String name, String defaultValue) {
Object o = attrList.get(name);
if (o == null){
return defaultValue;
} else {
return o.toString();
}
}
/**
* Set an attribute.
*/
public void setAttribute(String name, String value) {
attrList.put(name, value);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[").append(getNodeName()).append(" ").append(attrList).append("]");
return sb.toString();
}
}
@@ -1,219 +1,202 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
/**
* Parse an xml document into a Dnode tree.
*/
public class DnodeParser extends DefaultHandler {
/**
* The root of the DContent tree.
*/
Dnode root;
/**
* The current node being parsed.
*/
Dnode currentNode;
/**
* The nodeContent buffer.
*/
StringBuilder buffer;
/**
* Used to stack the nodes.
*/
Stack<Dnode> stack = new Stack<Dnode>();
/**
* The class used to construct new nodes. Should be Dnode or a subtype of
* Dnode.
*/
Class<?> nodeClass = Dnode.class;
int depth = 0;
/**
* Trim whitespace from the content.
*/
boolean trimWhitespace = true;
/**
* The name of the tag that contains html content
*/
String contentName;
/**
* The depth of the tag that contains the html content
*/
int contentDepth;
/**
* If true then trim the whitespace from the content.
*/
public boolean isTrimWhitespace() {
return trimWhitespace;
}
/**
* Set whether to trim whitespace from the content.
*/
public void setTrimWhitespace(boolean trimWhitespace) {
this.trimWhitespace = trimWhitespace;
}
/**
* Return the root node of the DContent tree.
*/
public Dnode getRoot() {
return root;
}
/**
* Set the type class of node to be created.
*/
public void setNodeClass(Class<?> nodeClass) {
this.nodeClass = nodeClass;
}
/**
* Create a new Dnode using the nodeClass.
*/
private Dnode createNewNode() {
try {
return (Dnode) nodeClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* process a startElement.
*/
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
super.startElement(uri, localName, qName, attributes);
depth++;
boolean isContent = (contentName != null);
if (isContent){
// must be html content... add the begin tag as content
buffer.append("<").append(localName);
for (int i = 0; i < attributes.getLength(); i++) {
String key = attributes.getLocalName(i);
String val = attributes.getValue(i);
buffer.append(" ").append(key).append("='").append(val).append("'");
}
buffer.append(">");
return;
}
buffer = new StringBuilder();
Dnode node = createNewNode();
node.setNodeName(localName);
for (int i = 0; i < attributes.getLength(); i++) {
String key = attributes.getLocalName(i);
String val = attributes.getValue(i);
node.setAttribute(key, val);
if ("type".equalsIgnoreCase(key) && "content".equalsIgnoreCase(val)) {
// this tag contains html content
// no more nodes until end tag is found
contentName = localName;
contentDepth = depth-1;
}
}
if (root == null) {
root = node;
}
if (currentNode != null) {
currentNode.addChild(node);
}
stack.push(node);
currentNode = node;
}
/**
* append the node content.
*/
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
String s = new String(ch, start, length);
int p = s.indexOf('\r');
int p2 = s.indexOf('\n');
if (p == -1 && p2 > -1) {
// This is probably not an issue but tidys up content
// in my text editor
s = StringHelper.replaceString(s, "\n", "\r\n");
}
buffer.append(s);
}
/**
* process the endElement.
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
depth--;
if (contentName != null){
// is this the end of the content?
if (contentName.equals(localName) && contentDepth == depth){
contentName = null;
} else {
// the html content end tag
buffer.append("</").append(localName).append(">");
}
return;
}
String content = buffer.toString();
buffer.setLength(0);
if (content.length() > 0) {
if (trimWhitespace) {
content = content.trim();
}
if (content.length() > 0) {
currentNode.setNodeContent(content);
}
}
stack.pop();
if (!stack.isEmpty()) {
// get the new currentNode
currentNode = (Dnode) stack.pop();
stack.push(currentNode);
}
}
}
package com.avaje.ebeaninternal.server.lib.util;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.avaje.ebeaninternal.server.lib.util.StringHelper;
/**
* Parse an xml document into a Dnode tree.
*/
public class DnodeParser extends DefaultHandler {
/**
* The root of the DContent tree.
*/
Dnode root;
/**
* The current node being parsed.
*/
Dnode currentNode;
/**
* The nodeContent buffer.
*/
StringBuilder buffer;
/**
* Used to stack the nodes.
*/
Stack<Dnode> stack = new Stack<Dnode>();
/**
* The class used to construct new nodes. Should be Dnode or a subtype of
* Dnode.
*/
Class<?> nodeClass = Dnode.class;
int depth = 0;
/**
* Trim whitespace from the content.
*/
boolean trimWhitespace = true;
/**
* The name of the tag that contains html content
*/
String contentName;
/**
* The depth of the tag that contains the html content
*/
int contentDepth;
/**
* If true then trim the whitespace from the content.
*/
public boolean isTrimWhitespace() {
return trimWhitespace;
}
/**
* Set whether to trim whitespace from the content.
*/
public void setTrimWhitespace(boolean trimWhitespace) {
this.trimWhitespace = trimWhitespace;
}
/**
* Return the root node of the DContent tree.
*/
public Dnode getRoot() {
return root;
}
/**
* Set the type class of node to be created.
*/
public void setNodeClass(Class<?> nodeClass) {
this.nodeClass = nodeClass;
}
/**
* Create a new Dnode using the nodeClass.
*/
private Dnode createNewNode() {
try {
return (Dnode) nodeClass.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* process a startElement.
*/
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
super.startElement(uri, localName, qName, attributes);
depth++;
boolean isContent = (contentName != null);
if (isContent){
// must be html content... add the begin tag as content
buffer.append("<").append(localName);
for (int i = 0; i < attributes.getLength(); i++) {
String key = attributes.getLocalName(i);
String val = attributes.getValue(i);
buffer.append(" ").append(key).append("='").append(val).append("'");
}
buffer.append(">");
return;
}
buffer = new StringBuilder();
Dnode node = createNewNode();
node.setNodeName(localName);
for (int i = 0; i < attributes.getLength(); i++) {
String key = attributes.getLocalName(i);
String val = attributes.getValue(i);
node.setAttribute(key, val);
if ("type".equalsIgnoreCase(key) && "content".equalsIgnoreCase(val)) {
// this tag contains html content
// no more nodes until end tag is found
contentName = localName;
contentDepth = depth-1;
}
}
if (root == null) {
root = node;
}
if (currentNode != null) {
currentNode.addChild(node);
}
stack.push(node);
currentNode = node;
}
/**
* append the node content.
*/
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
String s = new String(ch, start, length);
int p = s.indexOf('\r');
int p2 = s.indexOf('\n');
if (p == -1 && p2 > -1) {
// This is probably not an issue but tidys up content
// in my text editor
s = StringHelper.replaceString(s, "\n", "\r\n");
}
buffer.append(s);
}
/**
* process the endElement.
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
depth--;
if (contentName != null){
// is this the end of the content?
if (contentName.equals(localName) && contentDepth == depth){
contentName = null;
} else {
// the html content end tag
buffer.append("</").append(localName).append(">");
}
return;
}
String content = buffer.toString();
buffer.setLength(0);
if (content.length() > 0) {
if (trimWhitespace) {
content = content.trim();
}
if (content.length() > 0) {
currentNode.setNodeContent(content);
}
}
stack.pop();
if (!stack.isEmpty()) {
// get the new currentNode
currentNode = (Dnode) stack.pop();
stack.push(currentNode);
}
}
}
@@ -1,87 +1,70 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* Parses an XML inputstream returning a Dnode tree.
*/
public class DnodeReader {
public Dnode parseXml(String str) {
try {
ByteArrayOutputStream bao = new ByteArrayOutputStream(str.length());
OutputStreamWriter osw = new OutputStreamWriter(bao);
StringReader sr = new StringReader(str);
int charBufferSize = 1024;
char[] buf = new char[charBufferSize];
int len;
while ((len = sr.read(buf, 0, buf.length)) != -1) {
osw.write(buf, 0, len);
}
sr.close();
osw.flush();
osw.close();
bao.flush();
bao.close();
InputStream is = new ByteArrayInputStream(bao.toByteArray());
return parseXml(is);
} catch (IOException ex){
throw new RuntimeException(ex);
}
}
/**
* Parse the XML inputstream returning the Dnode tree.
*/
public Dnode parseXml(InputStream in) {
try {
InputSource inSource = new InputSource(in);
DnodeParser parser = new DnodeParser();
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(parser);
myReader.parse(inSource);
return parser.getRoot();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package com.avaje.ebeaninternal.server.lib.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* Parses an XML inputstream returning a Dnode tree.
*/
public class DnodeReader {
public Dnode parseXml(String str) {
try {
ByteArrayOutputStream bao = new ByteArrayOutputStream(str.length());
OutputStreamWriter osw = new OutputStreamWriter(bao);
StringReader sr = new StringReader(str);
int charBufferSize = 1024;
char[] buf = new char[charBufferSize];
int len;
while ((len = sr.read(buf, 0, buf.length)) != -1) {
osw.write(buf, 0, len);
}
sr.close();
osw.flush();
osw.close();
bao.flush();
bao.close();
InputStream is = new ByteArrayInputStream(bao.toByteArray());
return parseXml(is);
} catch (IOException ex){
throw new RuntimeException(ex);
}
}
/**
* Parse the XML inputstream returning the Dnode tree.
*/
public Dnode parseXml(InputStream in) {
try {
InputSource inSource = new InputSource(in);
DnodeParser parser = new DnodeParser();
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(parser);
myReader.parse(inSource);
return parser.getRoot();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -1,39 +1,22 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general exception that can be used for multiple purposes.
*/
public class GeneralException extends RuntimeException {
private static final long serialVersionUID = 5783084420007103280L;
public GeneralException(Exception cause) {
super(cause);
}
public GeneralException(String s, Exception cause) {
super(s, cause);
}
public GeneralException(String s) {
super(s);
}
}
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general exception that can be used for multiple purposes.
*/
public class GeneralException extends RuntimeException {
private static final long serialVersionUID = 5783084420007103280L;
public GeneralException(Exception cause) {
super(cause);
}
public GeneralException(String s, Exception cause) {
super(s, cause);
}
public GeneralException(String s) {
super(s);
}
}
@@ -1,40 +1,23 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general exception for invalid data.
*/
public class InvalidDataException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539846L;
public InvalidDataException(Exception cause) {
super(cause);
}
public InvalidDataException(String s, Exception cause) {
super(s, cause);
}
public InvalidDataException(String s) {
super(s);
}
}
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general exception for invalid data.
*/
public class InvalidDataException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539846L;
public InvalidDataException(Exception cause) {
super(cause);
}
public InvalidDataException(String s, Exception cause) {
super(s, cause);
}
public InvalidDataException(String s) {
super(s);
}
}
@@ -1,62 +1,45 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* An Email address with an associated alias.
*/
public class MailAddress {
String alias;
String emailAddress;
/**
* Create an address with an optional alias.
*/
public MailAddress(String alias, String emailAddress){
this.alias = alias;
this.emailAddress = emailAddress;
}
/**
* Return the alias.
* If the alias is null this returns an empty string.
*/
public String getAlias() {
if (alias == null){
return "";
}
return alias;
}
/**
* Return the email address.
*/
public String getEmailAddress(){
return emailAddress;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getAlias()).append(" ").append("<").append(getEmailAddress()).append(">");
return sb.toString();
}
}
package com.avaje.ebeaninternal.server.lib.util;
/**
* An Email address with an associated alias.
*/
public class MailAddress {
String alias;
String emailAddress;
/**
* Create an address with an optional alias.
*/
public MailAddress(String alias, String emailAddress){
this.alias = alias;
this.emailAddress = emailAddress;
}
/**
* Return the alias.
* If the alias is null this returns an empty string.
*/
public String getAlias() {
if (alias == null){
return "";
}
return alias;
}
/**
* Return the email address.
*/
public String getEmailAddress(){
return emailAddress;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getAlias()).append(" ").append("<").append(getEmailAddress()).append(">");
return sb.toString();
}
}
@@ -1,66 +1,49 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* Represents the success or failure of a mail send.
*/
public class MailEvent {
/**
* The error indicating a send failure.
*/
Throwable error;
/**
* The message that was sent.
*/
MailMessage message;
/**
* The message send failed with an error.
*/
public MailEvent(MailMessage message, Throwable error){
this.message = message;
this.error = error;
}
/**
* The message that we attempted to send.
*/
public MailMessage getMailMessage() {
return message;
}
/**
* Returns true if the message was sent successfully.
*/
public boolean wasSuccessful() {
return (error == null);
}
/**
* The error indicating the send failed.
*/
public Throwable getError() {
return error;
}
}
package com.avaje.ebeaninternal.server.lib.util;
/**
* Represents the success or failure of a mail send.
*/
public class MailEvent {
/**
* The error indicating a send failure.
*/
Throwable error;
/**
* The message that was sent.
*/
MailMessage message;
/**
* The message send failed with an error.
*/
public MailEvent(MailMessage message, Throwable error){
this.message = message;
this.error = error;
}
/**
* The message that we attempted to send.
*/
public MailMessage getMailMessage() {
return message;
}
/**
* Returns true if the message was sent successfully.
*/
public boolean wasSuccessful() {
return (error == null);
}
/**
* The error indicating the send failed.
*/
public Throwable getError() {
return error;
}
}
@@ -1,30 +1,13 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* Listens to see if the message was successfully sent.
*/
public interface MailListener {
/**
* Handle the message event.
*/
public void handleEvent(MailEvent event);
}
package com.avaje.ebeaninternal.server.lib.util;
/**
* Listens to see if the message was successfully sent.
*/
public interface MailListener {
/**
* Handle the message event.
*/
public void handleEvent(MailEvent event);
}
@@ -1,176 +1,159 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/**
* A simple test message that can be sent via smtp.
*/
public class MailMessage {
// /**
// * The subject text.
// */
// String subject;
/**
* The body content.
*/
ArrayList<String> bodylines;
/**
* The sender email address.
*/
MailAddress senderAddress;
/**
* The headers.
*/
HashMap<String,String> header = new HashMap<String, String>();
/**
* the recipient of the email.
*/
MailAddress currentRecipient;
/**
* The list of recipients.
*/
ArrayList<MailAddress> recipientList = new ArrayList<MailAddress>();
/**
* Create the message.
*/
public MailMessage() {
bodylines = new ArrayList<String>();
}
/**
* Set the current recipient.
*/
public void setCurrentRecipient(MailAddress currentRecipient){
this.currentRecipient = currentRecipient;
}
/**
* Return the current recipient.
*/
public MailAddress getCurrentRecipient() {
return currentRecipient;
}
/**
* Add a recipient.
*/
public void addRecipient(String alias, String emailAddress){
recipientList.add(new MailAddress(alias, emailAddress));
}
/**
* Set the sender details.
*/
public void setSender(String alias, String senderEmail){
this.senderAddress = new MailAddress(alias, senderEmail);
}
/**
* Return the sender address.
*/
public MailAddress getSender() {
return senderAddress;
}
/**
* Return the recipient list.
*/
public Iterator<MailAddress> getRecipientList() {
return recipientList.iterator();
}
/**
* add a header to the message.
*/
public void addHeader(String key, String val) {
header.put(key, val);
}
/**
* Set the subject text.
*/
public void setSubject(String subject){
addHeader("Subject", subject);
}
/**
* Return the subject text.
*/
public String getSubject() {
return getHeader("Subject");
}
/**
* Add text to the body.
*/
public void addBodyLine(String line) {
bodylines.add(line);
}
/**
* Return the body text.
*/
public Iterator<String> getBodyLines() {
return bodylines.iterator();
}
/**
* Return the headers.
*/
public Iterator<String> getHeaderFields() {
return header.keySet().iterator();
}
/**
* Return a given header.
*/
public String getHeader(String key) {
return header.get(key);
}
public String toString() {
StringBuilder sb = new StringBuilder(100);
sb.append("Sender: " + senderAddress + "\tRecipient: " + recipientList + "\n");
Iterator<String> hi = header.keySet().iterator();
while (hi.hasNext()) {
String key = hi.next();
String hline = key + ": " + header.get(key) + "\n";
sb.append(hline);
}
sb.append("\n");
Iterator<String> e = bodylines.iterator();
while (e.hasNext()) {
sb.append(e.next()).append("\n");
}
return sb.toString();
}
}
package com.avaje.ebeaninternal.server.lib.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
/**
* A simple test message that can be sent via smtp.
*/
public class MailMessage {
// /**
// * The subject text.
// */
// String subject;
/**
* The body content.
*/
ArrayList<String> bodylines;
/**
* The sender email address.
*/
MailAddress senderAddress;
/**
* The headers.
*/
HashMap<String,String> header = new HashMap<String, String>();
/**
* the recipient of the email.
*/
MailAddress currentRecipient;
/**
* The list of recipients.
*/
ArrayList<MailAddress> recipientList = new ArrayList<MailAddress>();
/**
* Create the message.
*/
public MailMessage() {
bodylines = new ArrayList<String>();
}
/**
* Set the current recipient.
*/
public void setCurrentRecipient(MailAddress currentRecipient){
this.currentRecipient = currentRecipient;
}
/**
* Return the current recipient.
*/
public MailAddress getCurrentRecipient() {
return currentRecipient;
}
/**
* Add a recipient.
*/
public void addRecipient(String alias, String emailAddress){
recipientList.add(new MailAddress(alias, emailAddress));
}
/**
* Set the sender details.
*/
public void setSender(String alias, String senderEmail){
this.senderAddress = new MailAddress(alias, senderEmail);
}
/**
* Return the sender address.
*/
public MailAddress getSender() {
return senderAddress;
}
/**
* Return the recipient list.
*/
public Iterator<MailAddress> getRecipientList() {
return recipientList.iterator();
}
/**
* add a header to the message.
*/
public void addHeader(String key, String val) {
header.put(key, val);
}
/**
* Set the subject text.
*/
public void setSubject(String subject){
addHeader("Subject", subject);
}
/**
* Return the subject text.
*/
public String getSubject() {
return getHeader("Subject");
}
/**
* Add text to the body.
*/
public void addBodyLine(String line) {
bodylines.add(line);
}
/**
* Return the body text.
*/
public Iterator<String> getBodyLines() {
return bodylines.iterator();
}
/**
* Return the headers.
*/
public Iterator<String> getHeaderFields() {
return header.keySet().iterator();
}
/**
* Return a given header.
*/
public String getHeader(String key) {
return header.get(key);
}
public String toString() {
StringBuilder sb = new StringBuilder(100);
sb.append("Sender: " + senderAddress + "\tRecipient: " + recipientList + "\n");
Iterator<String> hi = header.keySet().iterator();
while (hi.hasNext()) {
String key = hi.next();
String hline = key + ": " + header.get(key) + "\n";
sb.append(hline);
}
sb.append("\n");
Iterator<String> e = bodylines.iterator();
while (e.hasNext()) {
sb.append(e.next()).append("\n");
}
return sb.toString();
}
}
@@ -1,231 +1,214 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Sends simple MailMessages via smtp.
*/
public class MailSender implements Runnable {
private static final Logger logger = Logger.getLogger(MailSender.class.getName());
int traceLevel = 0;
Socket sserver;
String server;
BufferedReader in;
OutputStreamWriter out;
MailMessage message;
MailListener listener = null;
private static final int SMTP_PORT = 25;
/**
* Create for a given mail server.
*/
public MailSender(String server) {
this.server = server;
}
/**
* Set the listener to handle MessageEvents.
*/
public void setMailListener(MailListener listener){
this.listener = listener;
}
/**
* Send the message.
*/
public void run() {
send(message);
}
/**
* Send the message in a background thread.
*/
public void sendInBackground(MailMessage message){
this.message = message;
Thread thread = new Thread(this);
thread.start();
}
/**
* Send the message in the current thread.
*/
public void send(MailMessage message){
try {
Iterator<MailAddress> i = message.getRecipientList();
while (i.hasNext()) {
MailAddress recipientAddress = (MailAddress) i.next();
sserver = new Socket(server, SMTP_PORT);
send(message, sserver, recipientAddress);
sserver.close();
if (listener != null){
MailEvent event = new MailEvent(message, null);
listener.handleEvent(event);
}
}
} catch (Exception ex) {
if (listener != null){
MailEvent event = new MailEvent(message, ex);
listener.handleEvent(event);
} else {
logger.log(Level.SEVERE, null, ex);
}
}
}
private void send(MailMessage message, Socket sserver, MailAddress recipientAddress) throws IOException {
// A bit convoluted, but doesn't depend on DNS in any way...
InetAddress localhost = sserver.getLocalAddress();
String localaddress = localhost.getHostAddress();
MailAddress sender = message.getSender();
message.setCurrentRecipient(recipientAddress);
// Mandatory header fields, Date and From
if (message.getHeader("Date") == null){
message.addHeader("Date", new java.util.Date().toString());
}
if (message.getHeader("From") == null){
message.addHeader("From", sender.getAlias() + " <" + sender.getEmailAddress() + ">");
}
//if (message.getHeader("From") == null){
message.addHeader("To", recipientAddress.getAlias() + " <" + recipientAddress.getEmailAddress() + ">");
//}
out = new OutputStreamWriter(sserver.getOutputStream());
in = new BufferedReader(new InputStreamReader(sserver.getInputStream()));
String sintro = readln();
if (!sintro.startsWith("220")) { // 220
logger.fine("SmtpSender: intro==" + sintro);
return;
}
writeln("EHLO " + localaddress);
if (!expect250()) {
return;
}
writeln("MAIL FROM:<" + sender.getEmailAddress() + ">");
if (!expect250()) {
return;
}
writeln("RCPT TO:<" + recipientAddress.getEmailAddress() + ">");
if (!expect250()){
return;
}
writeln("DATA");
while (true) { // may be multiple 250 replies pending from server
String line = readln();
if (line.startsWith("3"))
break; // ready to send
if (!line.startsWith("2")) {
logger.fine("SmtpSender.send reponse to DATA: " + line);
return;
}
}
Iterator<String> hi = message.getHeaderFields();
while (hi.hasNext()) {
String key = (String) hi.next();
writeln(key + ": " + message.getHeader(key));
}
writeln(""); // end of header;
Iterator<String> e = message.getBodyLines();
while (e.hasNext()) {
String bline = (String) e.next();
if (bline.startsWith(".")) {
bline = "." + bline;
}
writeln(bline);
}
writeln(".");
expect250();
writeln("QUIT");
}
private boolean expect250() throws IOException {
String line = readln();
if (!line.startsWith("2")) {
logger.info("SmtpSender.expect250: " + line);
return false;
}
return true;
}
private void writeln(String s) throws IOException {
if (traceLevel > 2){
logger.fine("From client: " + s);
}
out.write(s + "\r\n");
out.flush();
}
private String readln() throws IOException {
String line = in.readLine();
if (traceLevel > 1){
logger.fine("From server: " + line);
}
return line;
}
/**
* Set the trace level.
*/
public void setTraceLevel(int traceLevel){
this.traceLevel = traceLevel;
}
/**
* Return the hostname of the local machine.
*/
public String getLocalHostName() {
try {
InetAddress ipaddress = InetAddress.getLocalHost();
String localHost = ipaddress.getHostName();
if (localHost == null) {
return "localhost";
} else {
return localHost;
}
} catch (UnknownHostException e) {
return "localhost";
}
}
}
package com.avaje.ebeaninternal.server.lib.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Sends simple MailMessages via smtp.
*/
public class MailSender implements Runnable {
private static final Logger logger = Logger.getLogger(MailSender.class.getName());
int traceLevel = 0;
Socket sserver;
String server;
BufferedReader in;
OutputStreamWriter out;
MailMessage message;
MailListener listener = null;
private static final int SMTP_PORT = 25;
/**
* Create for a given mail server.
*/
public MailSender(String server) {
this.server = server;
}
/**
* Set the listener to handle MessageEvents.
*/
public void setMailListener(MailListener listener){
this.listener = listener;
}
/**
* Send the message.
*/
public void run() {
send(message);
}
/**
* Send the message in a background thread.
*/
public void sendInBackground(MailMessage message){
this.message = message;
Thread thread = new Thread(this);
thread.start();
}
/**
* Send the message in the current thread.
*/
public void send(MailMessage message){
try {
Iterator<MailAddress> i = message.getRecipientList();
while (i.hasNext()) {
MailAddress recipientAddress = (MailAddress) i.next();
sserver = new Socket(server, SMTP_PORT);
send(message, sserver, recipientAddress);
sserver.close();
if (listener != null){
MailEvent event = new MailEvent(message, null);
listener.handleEvent(event);
}
}
} catch (Exception ex) {
if (listener != null){
MailEvent event = new MailEvent(message, ex);
listener.handleEvent(event);
} else {
logger.log(Level.SEVERE, null, ex);
}
}
}
private void send(MailMessage message, Socket sserver, MailAddress recipientAddress) throws IOException {
// A bit convoluted, but doesn't depend on DNS in any way...
InetAddress localhost = sserver.getLocalAddress();
String localaddress = localhost.getHostAddress();
MailAddress sender = message.getSender();
message.setCurrentRecipient(recipientAddress);
// Mandatory header fields, Date and From
if (message.getHeader("Date") == null){
message.addHeader("Date", new java.util.Date().toString());
}
if (message.getHeader("From") == null){
message.addHeader("From", sender.getAlias() + " <" + sender.getEmailAddress() + ">");
}
//if (message.getHeader("From") == null){
message.addHeader("To", recipientAddress.getAlias() + " <" + recipientAddress.getEmailAddress() + ">");
//}
out = new OutputStreamWriter(sserver.getOutputStream());
in = new BufferedReader(new InputStreamReader(sserver.getInputStream()));
String sintro = readln();
if (!sintro.startsWith("220")) { // 220
logger.fine("SmtpSender: intro==" + sintro);
return;
}
writeln("EHLO " + localaddress);
if (!expect250()) {
return;
}
writeln("MAIL FROM:<" + sender.getEmailAddress() + ">");
if (!expect250()) {
return;
}
writeln("RCPT TO:<" + recipientAddress.getEmailAddress() + ">");
if (!expect250()){
return;
}
writeln("DATA");
while (true) { // may be multiple 250 replies pending from server
String line = readln();
if (line.startsWith("3"))
break; // ready to send
if (!line.startsWith("2")) {
logger.fine("SmtpSender.send reponse to DATA: " + line);
return;
}
}
Iterator<String> hi = message.getHeaderFields();
while (hi.hasNext()) {
String key = (String) hi.next();
writeln(key + ": " + message.getHeader(key));
}
writeln(""); // end of header;
Iterator<String> e = message.getBodyLines();
while (e.hasNext()) {
String bline = (String) e.next();
if (bline.startsWith(".")) {
bline = "." + bline;
}
writeln(bline);
}
writeln(".");
expect250();
writeln("QUIT");
}
private boolean expect250() throws IOException {
String line = readln();
if (!line.startsWith("2")) {
logger.info("SmtpSender.expect250: " + line);
return false;
}
return true;
}
private void writeln(String s) throws IOException {
if (traceLevel > 2){
logger.fine("From client: " + s);
}
out.write(s + "\r\n");
out.flush();
}
private String readln() throws IOException {
String line = in.readLine();
if (traceLevel > 1){
logger.fine("From server: " + line);
}
return line;
}
/**
* Set the trace level.
*/
public void setTraceLevel(int traceLevel){
this.traceLevel = traceLevel;
}
/**
* Return the hostname of the local machine.
*/
public String getLocalHostName() {
try {
InetAddress ipaddress = InetAddress.getLocalHost();
String localHost = ipaddress.getHostName();
if (localHost == null) {
return "localhost";
} else {
return localHost;
}
} catch (UnknownHostException e) {
return "localhost";
}
}
}
@@ -1,80 +1,63 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
import java.util.LinkedHashMap;
/**
* Utility String class that supports String manipulation functions.
*/
public class MapFromString {
LinkedHashMap<String,String> map = new LinkedHashMap<String,String>();
String mapToString;
int stringLength;
int keyStart = 0;
int eqPos = 0;
int valEnd = 0;
public static LinkedHashMap<String,String> parse(String mapToString) {
MapFromString c = new MapFromString(mapToString);
return c.parse();
}
private MapFromString(String mapToString) {
if (mapToString.charAt(0) == '{'){
mapToString = mapToString.substring(1);
}
if (mapToString.charAt(mapToString.length()-1) == '}'){
mapToString = mapToString.substring(0, mapToString.length()-1);
}
this.mapToString = mapToString;
this.stringLength = mapToString.length();
}
private LinkedHashMap<String,String> parse() {
while(findNext()){
}
return map;
}
private boolean findNext() {
if (keyStart > stringLength){
return false;
}
eqPos = mapToString.indexOf("=",keyStart);
if (eqPos == -1){
throw new RuntimeException("No = after "+keyStart);
}
valEnd = mapToString.indexOf(", ",eqPos);
if (valEnd == -1){
valEnd = mapToString.length();
}
// check that the next valEnd occurs after the next eqPos
String keyValue = mapToString.substring(keyStart,eqPos);
String valValue = mapToString.substring(eqPos+1,valEnd);
map.put(keyValue, valValue);
keyStart = valEnd + 2;
return true;
}
}
package com.avaje.ebeaninternal.server.lib.util;
import java.util.LinkedHashMap;
/**
* Utility String class that supports String manipulation functions.
*/
public class MapFromString {
LinkedHashMap<String,String> map = new LinkedHashMap<String,String>();
String mapToString;
int stringLength;
int keyStart = 0;
int eqPos = 0;
int valEnd = 0;
public static LinkedHashMap<String,String> parse(String mapToString) {
MapFromString c = new MapFromString(mapToString);
return c.parse();
}
private MapFromString(String mapToString) {
if (mapToString.charAt(0) == '{'){
mapToString = mapToString.substring(1);
}
if (mapToString.charAt(mapToString.length()-1) == '}'){
mapToString = mapToString.substring(0, mapToString.length()-1);
}
this.mapToString = mapToString;
this.stringLength = mapToString.length();
}
private LinkedHashMap<String,String> parse() {
while(findNext()){
}
return map;
}
private boolean findNext() {
if (keyStart > stringLength){
return false;
}
eqPos = mapToString.indexOf("=",keyStart);
if (eqPos == -1){
throw new RuntimeException("No = after "+keyStart);
}
valEnd = mapToString.indexOf(", ",eqPos);
if (valEnd == -1){
valEnd = mapToString.length();
}
// check that the next valEnd occurs after the next eqPos
String keyValue = mapToString.substring(keyStart,eqPos);
String valValue = mapToString.substring(eqPos+1,valEnd);
map.put(keyValue, valValue);
keyStart = valEnd + 2;
return true;
}
}
@@ -1,57 +1,40 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Helper methods to determine the mime type based on a file name.
*/
public class MimeTypeHelper {
/**
* Return the mimeType for a given file path.
* This will extract the file extension, and then use that
* to look up an appropriate mime type (from the mimetypes.props file).
*
* To add a new mime type, add it to the mimetype.props file.
*/
public static String getMimeType(String filePath) {
int lastPeriod = filePath.lastIndexOf(".");
if (lastPeriod > -1) {
filePath = filePath.substring(lastPeriod+1);
}
try {
return resources.getString(filePath.toLowerCase());
} catch (MissingResourceException e) {
return null;
//String m = "Unable to locate mimetype for ["+filePath.toLowerCase()+"] in mimetypes.properties";
//throw new NotFoundException(m);
}
}
private static ResourceBundle resources = ResourceBundle.getBundle("com.avaje.lib.util.mimetypes");
};
package com.avaje.ebeaninternal.server.lib.util;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Helper methods to determine the mime type based on a file name.
*/
public class MimeTypeHelper {
/**
* Return the mimeType for a given file path.
* This will extract the file extension, and then use that
* to look up an appropriate mime type (from the mimetypes.props file).
*
* To add a new mime type, add it to the mimetype.props file.
*/
public static String getMimeType(String filePath) {
int lastPeriod = filePath.lastIndexOf(".");
if (lastPeriod > -1) {
filePath = filePath.substring(lastPeriod+1);
}
try {
return resources.getString(filePath.toLowerCase());
} catch (MissingResourceException e) {
return null;
//String m = "Unable to locate mimetype for ["+filePath.toLowerCase()+"] in mimetypes.properties";
//throw new NotFoundException(m);
}
}
private static ResourceBundle resources = ResourceBundle.getBundle("com.avaje.lib.util.mimetypes");
};
@@ -1,40 +1,23 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general exception where data is not found.
*/
public class NotFoundException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539845L;
public NotFoundException(Exception cause) {
super(cause);
}
public NotFoundException(String s, Exception cause) {
super(s, cause);
}
public NotFoundException(String s) {
super(s);
}
}
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general exception where data is not found.
*/
public class NotFoundException extends RuntimeException
{
static final long serialVersionUID = 7061559938704539845L;
public NotFoundException(Exception cause) {
super(cause);
}
public NotFoundException(String s, Exception cause) {
super(s, cause);
}
public NotFoundException(String s) {
super(s);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,32 +1,15 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general string parsing exception.
*/
public class StringParsingException extends RuntimeException {
static final long serialVersionUID = -3070423471260426402L;
public StringParsingException(String message) {
super(message);
}
};
package com.avaje.ebeaninternal.server.lib.util;
/**
* A general string parsing exception.
*/
public class StringParsingException extends RuntimeException {
static final long serialVersionUID = -3070423471260426402L;
public StringParsingException(String message) {
super(message);
}
};
@@ -1,108 +1,91 @@
/**
* Copyright (C) 2006 Robin Bygrave
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.avaje.ebeaninternal.server.lib.util;
/**
* Builds a string from a stack trace.
* <p>
* Generally used to flatten a stack trace into a single string
* removing \r\n and limiting the size of any given stack.
* </p>
*/
public class ThrowablePrinter {
private static final String atString = " at ";
private String newLineChar = "\\r\\n";
private int maxStackTraceLines = 3;
/**
* Set the maximum number of lines in any one part of
* the stack trace. This is not the total maximum.
*/
public void setMaxStackTraceLines(int maxStackTraceLines) {
this.maxStackTraceLines = maxStackTraceLines;
}
/**
* Set the new line character used to replace \r\n with.
* This is useful so that the stack is placed on a single line
* in a log file.
*/
public void setNewLineChar(String newLineChar) {
this.newLineChar = newLineChar;
}
/**
* Convert the error into a string representation.
* <p>
* Replaces the \r\n and limits the stack lines.
* </p>
*/
public String print(Throwable e) {
StringBuffer sb = new StringBuffer();
printThrowable(sb, e, false);
String line = sb.toString();
line = StringHelper.replaceString(line, "\r", "\\r");
line = StringHelper.replaceString(line, "\n", "\\n");
return line;
}
/**
* Recursively output the Throwable stack trace to the log.
*
* @param sb the buffer to write the stack trace to
* @param e the source throwable
* @param isCause flag to indicate if this is the top level throwable or a
* cause
*/
protected void printThrowable(StringBuffer sb, Throwable e, boolean isCause) {
if (e != null) {
if (isCause) {
sb.append("Caused by: ");
}
sb.append(e.getClass().getName());
sb.append(":");
sb.append(e.getMessage()).append(newLineChar);
StackTraceElement[] ste = e.getStackTrace();
int outputStackLines = ste.length;
int notShownCount = 0;
if (ste.length > maxStackTraceLines) {
outputStackLines = maxStackTraceLines;
notShownCount = ste.length - outputStackLines;
}
for (int i = 0; i < outputStackLines; i++) {
sb.append(atString);
sb.append(ste[i].toString()).append(newLineChar);
}
if (notShownCount > 0) {
sb.append(" ... ");
sb.append(notShownCount);
sb.append(" more").append(newLineChar);
}
Throwable cause = e.getCause();
if (cause != null) {
printThrowable(sb, cause, true);
}
}
}
}
package com.avaje.ebeaninternal.server.lib.util;
/**
* Builds a string from a stack trace.
* <p>
* Generally used to flatten a stack trace into a single string
* removing \r\n and limiting the size of any given stack.
* </p>
*/
public class ThrowablePrinter {
private static final String atString = " at ";
private String newLineChar = "\\r\\n";
private int maxStackTraceLines = 3;
/**
* Set the maximum number of lines in any one part of
* the stack trace. This is not the total maximum.
*/
public void setMaxStackTraceLines(int maxStackTraceLines) {
this.maxStackTraceLines = maxStackTraceLines;
}
/**
* Set the new line character used to replace \r\n with.
* This is useful so that the stack is placed on a single line
* in a log file.
*/
public void setNewLineChar(String newLineChar) {
this.newLineChar = newLineChar;
}
/**
* Convert the error into a string representation.
* <p>
* Replaces the \r\n and limits the stack lines.
* </p>
*/
public String print(Throwable e) {
StringBuffer sb = new StringBuffer();
printThrowable(sb, e, false);
String line = sb.toString();
line = StringHelper.replaceString(line, "\r", "\\r");
line = StringHelper.replaceString(line, "\n", "\\n");
return line;
}
/**
* Recursively output the Throwable stack trace to the log.
*
* @param sb the buffer to write the stack trace to
* @param e the source throwable
* @param isCause flag to indicate if this is the top level throwable or a
* cause
*/
protected void printThrowable(StringBuffer sb, Throwable e, boolean isCause) {
if (e != null) {
if (isCause) {
sb.append("Caused by: ");
}
sb.append(e.getClass().getName());
sb.append(":");
sb.append(e.getMessage()).append(newLineChar);
StackTraceElement[] ste = e.getStackTrace();
int outputStackLines = ste.length;
int notShownCount = 0;
if (ste.length > maxStackTraceLines) {
outputStackLines = maxStackTraceLines;
notShownCount = ste.length - outputStackLines;
}
for (int i = 0; i < outputStackLines; i++) {
sb.append(atString);
sb.append(ste[i].toString()).append(newLineChar);
}
if (notShownCount > 0) {
sb.append(" ... ");
sb.append(notShownCount);
sb.append(" more").append(newLineChar);
}
Throwable cause = e.getCause();
if (cause != null) {
printThrowable(sb, cause, true);
}
}
}
}