*** empty log message ***

This commit is contained in:
Eric J. Bowersox 2001-01-31 20:55:37 +00:00
parent cb2d194940
commit 946f3fb493
205 changed files with 297131 additions and 0 deletions

264829
etc/webster2.dict Normal file

File diff suppressed because it is too large Load Diff

2
lib/README.lib Normal file
View File

@ -0,0 +1,2 @@
When you download the MySQL JDBC driver, put the "mysql.jar" file in this
directory.

4
setup/context-add.xml Normal file
View File

@ -0,0 +1,4 @@
<Context path="/venice"
docBase="/home/erbo/venice"
crossContext="false" debug="0" reloadable="true" trusted="false">
</Context>

1429
setup/database.sql Normal file

File diff suppressed because it is too large Load Diff

4
setup/tomcat.policy.add Normal file
View File

@ -0,0 +1,4 @@
grant codebase "file:/home/erbo/venice" {
permission java.security.AllPermission;
};

View File

@ -0,0 +1,115 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import org.w3c.dom.*;
public class DOMElementHelper
{
private Element elt; // element housed by this helper class
public DOMElementHelper(Element elt)
{
this.elt = elt;
} // end constructor
protected void finalize()
{
elt = null;
} // end finalize
private static String getTextOfElement(Element e)
{
NodeList kids = e.getChildNodes();
if (kids==null)
return null; // no text?
StringBuffer b = null;
for (int i=0; i<kids.getLength(); i++)
{ // look for an ELEMENT_NODE node matching the desired name
Node t = kids.item(i);
if ((t.getNodeType()==Node.TEXT_NODE) || (t.getNodeType()==Node.CDATA_SECTION_NODE))
{ // append to the string under construction
if (b==null)
b = new StringBuffer();
else
b.append(' ');
b.append(t.getNodeValue());
} // end if
} // end for
if (b==null)
return null; // no TEXT nodes
else
return b.toString(); // return the concatenation
} // end getTextOfElement
public Element getElement()
{
return elt;
} // end getElement
public Element getSubElement(String name)
{
NodeList kids = elt.getChildNodes();
if (kids==null)
return null; // no children?
for (int i=0; i<kids.getLength(); i++)
{ // look for an ELEMENT_NODE node matching the desired name
Node t = kids.item(i);
if ((t.getNodeType()==Node.ELEMENT_NODE) && (t.getNodeName().equals(name)))
return (Element)t;
} // end for
return null; // not found
} // end getSubElement
public String getElementText()
{
return getTextOfElement(elt);
} // end getElementText
public String getSubElementText(String name)
{
Element se = getSubElement(name);
if (se==null)
return null;
else
return getTextOfElement(se);
} // end getSubElementText
public boolean hasChildElement(String name)
{
Element tmp = getSubElement(name);
return (tmp==null) ? false : true;
} // end hasChildElement
} // end DOMElementHelper

View File

@ -0,0 +1,64 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
public class ServletMultipartException extends Exception
{
// Attributes
private Exception e = null; // internal "root cause" exception
public ServletMultipartException()
{
super();
} // end constructor
public ServletMultipartException(String msg)
{
super(msg);
} // end constructor
public ServletMultipartException(Exception e)
{
super(e.getMessage());
this.e = e;
} // end constructor
public ServletMultipartException(String msg, Exception e)
{
super(msg);
this.e = e;
} // end constructor
protected void finalize() throws Throwable
{
e = null;
super.finalize();
} // end finalize
public Exception getException()
{
return e;
} // end getException
} // end class ServletMultipartException

View File

@ -0,0 +1,379 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.*;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
// This class was built in a process I call "Java Junkyard Wars," in which I put together
// a bunch of APIs in ways that their designers would never have anticipated. It's
// absolutely bodge-tastic!
public class ServletMultipartHandler
{
private MimeMultipart multipart; // holds all the multipart data
private Hashtable param_byname; // parameters by name
private Vector param_order; // parameters in order
class ServletDataSource implements DataSource
{
private ServletRequest request;
private InputStream istm = null;
public ServletDataSource(ServletRequest request)
{
this.request = request;
} // end constructor
public InputStream getInputStream() throws IOException
{
if (istm==null)
istm = request.getInputStream();
return istm;
} // end getInputStream
public OutputStream getOutputStream() throws IOException
{
throw new IOException("tried to get OutputStream on servlet input?!?!?");
} // end getOutputStream
public String getContentType()
{
return request.getContentType();
} // end getContentType
public String getName()
{
return "servlet";
} // end getName
} // end class ServletDataSource
static class MultipartDataValue implements Blob
{
private byte[] actual_data; // the actual data we contain
public MultipartDataValue(MimeBodyPart part) throws MessagingException, IOException
{
InputStream in = part.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] copybuf = new byte[1024];
int ct = in.read(copybuf);
while (ct>=0)
{ // do a simple read and write
if (ct>0)
out.write(copybuf,0,ct);
ct = in.read(copybuf);
} // end while
in.close();
actual_data = out.toByteArray();
out.close();
} // end constructor
public long length()
{
return actual_data.length;
} // end length
public byte[] getBytes(long pos, int length)
{
byte[] rc = new byte[length];
System.arraycopy(actual_data,(int)pos,rc,0,length);
return rc;
} // end getBytes
public InputStream getBinaryStream()
{
return new ByteArrayInputStream(actual_data);
} // end getBinaryStream
public long position(byte[] pattern, long start) throws SQLException
{
throw new SQLException("function not implemented");
} // end position
public long position(Blob pattern, long start) throws SQLException
{
return position(pattern.getBytes(0,(int)(pattern.length())),start);
} // end position
} // end class MultipartDataValue
class MultipartParameter
{
private MimeBodyPart part; // the actual body part data
private String name; // the parameter name
private String filename; // the filename
private MultipartDataValue cached_value = null;
public MultipartParameter(MimeBodyPart part) throws MessagingException
{
this.part = part; // save part reference
// Parse the Content-Disposition header.
String[] cdstr = part.getHeader("Content-Disposition");
ContentDisposition cdisp = new ContentDisposition(cdstr[0]);
name = cdisp.getParameter("name");
filename = cdisp.getParameter("filename");
if (filename!=null)
{ // Strip off everything but the base filename, if the browser happened to pass that.
int sep = filename.lastIndexOf('\\');
if (sep>=0)
filename = filename.substring(sep+1);
sep = filename.lastIndexOf('/');
if (sep>=0)
filename = filename.substring(sep+1);
} // end if
} // end constructor
public String getName()
{
return name;
} // end getName
public boolean isFile()
{
return (filename!=null);
} // end isFile
public String getValue()
{
if (filename!=null)
return filename;
try
{ // Retrieve the part's actual content and convert it to a String. (Since non-file
// fields are of type text/plain, the Object "val" should actually be a String, in
// which case the toString() call is actually a no-op. But this is safe.)
Object val = part.getContent();
return val.toString();
} // end try
catch (Exception e)
{ // turn any exception returns here into null returns
return null;
} // end catch
} // end getValue
public String getContentType()
{
try
{ // pass through to the interior part
return part.getContentType();
} // end try
catch (Exception e)
{ // just dump a null on error
return null;
} // end catch
} // end getContentType
public int getSize()
{
try
{ // pass through to the interior part
return part.getSize();
} // end try
catch (Exception e)
{ // just dump a -1 on error
return -1;
} // end catch
} // end getSize
public MultipartDataValue getContent() throws ServletMultipartException
{
if (filename==null)
return null;
if (cached_value==null)
{ // we don't have the value cached yet
try
{ // extract the value
cached_value = new MultipartDataValue(part);
} // end try
catch (MessagingException me)
{ // translate exception here
throw new ServletMultipartException("Error getting data content: " + me.getMessage(),me);
} // end catch
catch (IOException ioe)
{ // translate exception here
throw new ServletMultipartException("Error getting data content: " + ioe.getMessage(),ioe);
} // end catch
} // end if
return cached_value;
} // end getContent
} // end class MultipartParameter
public ServletMultipartHandler(ServletRequest request) throws ServletMultipartException
{
if (!canHandle(request))
throw new ServletMultipartException("not a multipart/form-data request");
try
{ // build the MimeMultipart based on the ServletDataSource
multipart = new MimeMultipart(new ServletDataSource(request));
int count = multipart.getCount();
// allocate the multipart parameters and slot them into our arrays
param_byname = new Hashtable();
param_order = new Vector();
for (int i=0; i<count; i++)
{ // create the MultipartParameter structures and stash them for later use
MultipartParameter parm = new MultipartParameter((MimeBodyPart)(multipart.getBodyPart(i)));
param_byname.put(parm.getName(),parm);
param_order.addElement(parm);
} // end count
} // end try
catch (MessagingException me)
{ // translate a MessagingException into the nicer ServletMultipartException
throw new ServletMultipartException("Error parsing request data: " + me.getMessage(),me);
} // end catch
} // end constructor
/**
* Returns <CODE>true</CODE> if the given <CODE>ServletRequest</CODE> can be handled by
* the <CODE>ServletMultipartHandler</CODE>, <CODE>false</CODE> if not.
*
* @param request The <CODE>ServletRequest</CODE> to be checked.
* @return <CODE>true</CODE> if the given <CODE>ServletRequest</CODE> can be handled by
* the <CODE>ServletMultipartHandler</CODE>, <CODE>false</CODE> if not.
*/
public static boolean canHandle(ServletRequest request)
{
String ctype = request.getContentType();
return (ctype.startsWith("multipart/form-data"));
} // end canHandle
public Enumeration getNames()
{
Vector tmp_vector = new Vector();
Enumeration enum = param_order.elements();
while (enum.hasMoreElements())
{ // add each name to the temporary vector
MultipartParameter parm = (MultipartParameter)(enum.nextElement());
tmp_vector.addElement(parm.getName());
} // end while
return tmp_vector.elements(); // and enumerate it
} // end getNames
public boolean isFileParam(String name)
{
MultipartParameter parm = (MultipartParameter)(param_byname.get(name));
if (parm==null)
return false;
else
return parm.isFile();
} // end isFileParam
public String getValue(String name)
{
MultipartParameter parm = (MultipartParameter)(param_byname.get(name));
if (parm==null)
return null;
else
return parm.getValue();
} // end getValue
public String getContentType(String name)
{
MultipartParameter parm = (MultipartParameter)(param_byname.get(name));
if (parm==null)
return null;
else
return parm.getContentType();
} // end getContentType
public int getContentSize(String name)
{
MultipartParameter parm = (MultipartParameter)(param_byname.get(name));
if (parm==null)
return -1;
else
return parm.getSize();
} // end getContentSize
public Blob getFileContentBlob(String name) throws ServletMultipartException
{
MultipartParameter parm = (MultipartParameter)(param_byname.get(name));
if (parm==null)
return null;
else
return parm.getContent();
} // end getFileContentBlob
public InputStream getFileContentStream(String name) throws ServletMultipartException
{
MultipartParameter parm = (MultipartParameter)(param_byname.get(name));
if (parm==null)
return null;
MultipartDataValue val = parm.getContent();
return val.getBinaryStream();
} // end getFileContentStream
} // end class ServletMultipartHandler

View File

@ -0,0 +1,122 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
public class StringUtil
{
public static String encodeStringSQL(String str)
{
if (str==null)
return null;
int ndx = str.indexOf('\'');
if (ndx<0)
return str;
StringBuffer buf = new StringBuffer();
while (ndx>=0)
{ // convert each single quote mark to a pair of them
if (ndx>0)
buf.append(str.substring(0,ndx));
buf.append("''");
str = str.substring(ndx+1);
ndx = str.indexOf('\'');
} // end while
buf.append(str);
return buf.toString();
} // end encodeStringSQL
public static String encodeHTML(String str)
{
if (str==null)
return null;
StringBuffer buf = new StringBuffer();
for (int i=0; i<str.length(); i++)
{ // loop through the string encoding each character in turn
switch (str.charAt(i))
{
case '"':
buf.append("&quot;");
break;
case '&':
buf.append("&amp;");
break;
case '<':
buf.append("&lt;");
break;
case '>':
buf.append("&gt;");
break;
default:
buf.append(str.charAt(i));
break;
} // end switch
} // end for
return buf.toString();
} // end encodeHTML
public static boolean isStringEmpty(String s)
{
return ((s==null) || (s.length()==0));
} // end isStringEmpty
public static String replaceAllInstances(String base, String find, String replace)
{
String work = base;
int ndx = work.indexOf(find);
if (ndx<0)
return work; // trivial case
StringBuffer b = new StringBuffer();
while (ndx>=0)
{ // break off the first part of the string, then insert the replacement
if (ndx>0)
b.append(work.substring(0,ndx));
b.append(replace);
// break off the tail end
ndx += find.length();
if (ndx==work.length())
work = null;
else
work = work.substring(ndx);
// do the next find
if (work!=null)
ndx = work.indexOf(find);
else
ndx = -1;
} // end while
if (work!=null)
b.append(work);
return b.toString();
} // end replaceAllInstances
} // end class StringUtil

View File

@ -0,0 +1,132 @@
package com.silverwrist.util.test;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.silverwrist.util.*;
public class FormDataTest extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Form Test</TITLE></HEAD><BODY>");
out.println("<H1>Form Test</H1>");
out.println("<FORM METHOD=POST ENCTYPE=\"multipart/form-data\" ACTION=\"/venice/testformdata\">");
out.println("Text field: <INPUT TYPE=TEXT NAME=\"text\" VALUE=\"foo\" SIZE=32 MAXLENGTH=128><P>");
out.println("File field: <INPUT TYPE=FILE NAME=\"file\" SIZE=32 MAXLENGTH=255><P>");
out.println("<INPUT TYPE=SUBMIT VALUE=\"sumbit\">");
out.println("</FORM></BODY></HTML>");
} // end doGet
private void old_doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
TestMultiHandler tmh = null;
String errmsg = null;
int count = -1;
try
{ // attempt to launch the multi handler
tmh = new TestMultiHandler(request);
count = tmh.getCount();
} // end try
catch (IOException e)
{ // we got an error from the parser
errmsg = e.getMessage();
} // end catch
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Form Test Results</TITLE></HEAD><BODY>");
out.println("<H1>Form Test Results</H1>");
if (errmsg==null)
out.println("Success!<P>");
else
out.println("ERROR: " + errmsg + "<P>");
out.println("Data count was: " + String.valueOf(count) + "<P>");
out.println("<PRE>");
tmh.dump(out);
out.println("</PRE>");
out.println("<A HREF=\"/venice/testformdata\">Go back.</A>");
out.println("</BODY></HTML>");
} // end old_doPost
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
final String save_dir = "/home/erbo";
String errmsg = null;
ServletMultipartHandler smh = null;
boolean file_check = false;
String text_value = null;
String file_name = null;
String file_type = null;
try
{ // create the multipart handler
smh = new ServletMultipartHandler(request);
text_value = smh.getValue("text");
file_check = smh.isFileParam("file");
if (file_check)
{ // copy out to file
file_name = smh.getValue("file");
file_type = smh.getContentType("file");
if ((file_name!=null) && (file_name.length()>0))
{ // build the file name and save it
FileOutputStream stm = new FileOutputStream(save_dir + "/" + file_name);
InputStream in = smh.getFileContentStream("file");
byte[] copybuf = new byte[1024];
int ct = in.read(copybuf);
while (ct>=0)
{ // copy loop...
if (ct>0)
stm.write(copybuf,0,ct);
ct = in.read(copybuf);
} // end while
stm.close();
in.close();
} // end if
} // end if
} // end try
catch (ServletMultipartException e)
{ // load error message
errmsg = e.getMessage();
} // end catch
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Form Test Results</TITLE></HEAD><BODY>");
out.println("<H1>Form Test Results</H1>");
if (errmsg==null)
{ // print data
out.println("Text value: " + text_value + "<P>");
if (file_check)
{ // get file name and type
out.println("File name: " + file_name + "<P>");
out.println("File type: " + file_type + "<P>");
out.println("Saved to directory: " + save_dir + "<P>");
} // end if
else
out.println("Not a file.<P>");
} // end if
else
out.println("ERROR: " + errmsg + "<P>");
out.println("<A HREF=\"/venice/testformdata\">Go back.</A>");
out.println("</BODY></HTML>");
} // end doPost
} // end class FormDataTest

View File

@ -0,0 +1,121 @@
package com.silverwrist.util.test;
import java.io.*;
import java.util.*;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
public class TestMultiHandler
{
private MimeMultipart multipart;
private int count;
private Vector params;
static class ServletDataSource implements DataSource
{
private ServletRequest request;
private InputStream istm = null;
public ServletDataSource(ServletRequest request)
{
this.request = request;
} // end constructor
public InputStream getInputStream() throws IOException
{
if (istm==null)
istm = request.getInputStream();
return istm;
} // end getInputStream
public OutputStream getOutputStream() throws IOException
{
throw new IOException("tried to get OutputStream on servlet input?!?!?");
} // end getOutputStream
public String getContentType()
{
return request.getContentType();
} // end getContentType
public String getName()
{
return "servlet";
} // end getName
} // end class ServletDataSource
public TestMultiHandler(ServletRequest request) throws IOException
{
if (!canHandle(request))
throw new UnsupportedOperationException("data type doesn't match");
try
{ // OK, this is the tricky part...
ServletDataSource ds = new ServletDataSource(request);
multipart = new MimeMultipart(ds);
count = multipart.getCount();
params = new Vector(count);
// OK, that's enough for now
} // end try
catch (MessagingException e)
{ // better run like hell, 'cos this may not work
throw new IOException("Got MessagingException: " + e.getMessage());
} // end catch
} // end constructor
public static boolean canHandle(ServletRequest request)
{
String ctype = request.getContentType();
return (ctype.startsWith("multipart/form-data"));
} // end canHandle
public int getCount()
{
return count;
} // end getCount
public void dump(PrintWriter out)
{
try
{ // print out all parts
int ct = multipart.getCount();
out.println("Number of parts: " + String.valueOf(ct));
for (int i=0; i<ct; i++)
{ // loop through all the parts
out.println("--- PART " + String.valueOf(i) + " ---");
MimeBodyPart part = (MimeBodyPart)(multipart.getBodyPart(i));
out.println("got it");
String foo = part.getContentType();
out.println("Content type: " + foo);
foo = part.getDisposition();
out.println("Content disposition: " + foo);
String[] disphdr = part.getHeader("Content-Disposition");
for (int j=0; j<disphdr.length; j++)
out.println("Content-Disposition header[" + String.valueOf(j) + "]: " + disphdr[j]);
} // end for
} // end try
catch (MessagingException e)
{ // whoops!
out.println("THREW MessagingException: " + e.getMessage());
} // end catch
} // end dump
} // end class TestMultiHandler

View File

@ -0,0 +1,46 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice;
public class ValidationException extends VeniceException
{
public ValidationException()
{
super();
} // end constructor
public ValidationException(String msg)
{
super(msg);
} // end constructor
public ValidationException(Exception e)
{
super(e);
} // end constructor
public ValidationException(String msg, Exception e)
{
super(msg,e);
} // end constructor
} // end class ValidationException

View File

@ -0,0 +1,64 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice;
public class VeniceException extends Exception
{
// Attributes
private Exception e = null; // internal "root cause" exception
public VeniceException()
{
super();
} // end constructor
public VeniceException(String msg)
{
super(msg);
} // end constructor
public VeniceException(Exception e)
{
super(e.getMessage());
this.e = e;
} // end constructor
public VeniceException(String msg, Exception e)
{
super(msg);
this.e = e;
} // end constructor
protected void finalize() throws Throwable
{
e = null;
super.finalize();
} // end finalize
public Exception getException()
{
return e;
} // end getException
} // end class VeniceException

View File

@ -0,0 +1,46 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public class AccessError extends com.silverwrist.venice.VeniceException
{
public AccessError()
{
super();
} // end constructor
public AccessError(String msg)
{
super(msg);
} // end constructor
public AccessError(Exception e)
{
super(e);
} // end constructor
public AccessError(String msg, Exception e)
{
super(msg,e);
} // end constructor
} // end class AccessError

View File

@ -0,0 +1,23 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public interface AdminOperations
{
// TODO: fill this in
} // end interface AdminOperations

View File

@ -0,0 +1,50 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.List;
public interface CategoryDescriptor
{
public abstract int getCategoryID();
public abstract int getNumLevels();
public abstract int getIDAtLevel(int level);
public abstract String getTitleAtLevel(int level);
public abstract List getSubCategories() throws DataException;
public abstract CategoryDescriptor getSuperCategory(int levels);
public abstract CategoryDescriptor getParentCategory();
public abstract int getLinkedCategoryID();
public abstract boolean isSymbolicLink();
public abstract CategoryDescriptor getLinkedCategory() throws DataException;
public abstract boolean equals(Object obj);
public abstract int hashCode();
public abstract String toString();
} // end interface CategoryDescriptor

View File

@ -0,0 +1,112 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.Date;
import java.util.List;
public interface ConferenceContext
{
public static final int GET_ALL = 0;
public static final int DISPLAY_NEW = 1;
public static final int DISPLAY_ACTIVE = 2;
public static final int DISPLAY_ALL = 3;
public static final int DISPLAY_HIDDEN = 4;
public static final int DISPLAY_ARCHIVED = 5;
public static final int SORT_TOPICID = 0;
public static final int SORT_NUMBER = 1;
public static final int SORT_NAME = 2;
public static final int SORT_UNREAD = 3;
public static final int SORT_TOTAL = 4;
public static final int SORT_DATE = 5;
public abstract int getConfID();
public abstract String getName();
public abstract String getDescription();
public abstract Date getCreationDate();
public abstract Date getLastUpdateDate();
public abstract List getAliases() throws DataException;
public abstract List getHosts() throws DataException;
public abstract boolean canReadConference();
public abstract boolean canPostToConference();
public abstract boolean canCreateTopic();
public abstract boolean canChangeConference();
public abstract int getReadLevel() throws DataException, AccessError;
public abstract int getPostLevel() throws DataException, AccessError;
public abstract int getCreateLevel() throws DataException, AccessError;
public abstract int getHideLevel() throws DataException, AccessError;
public abstract int getNukeLevel() throws DataException, AccessError;
public abstract int getChangeLevel() throws DataException, AccessError;
public abstract int getDeleteLevel() throws DataException, AccessError;
public abstract void setSecurityLevels(int read, int post, int create, int hide, int nuke,
int change, int delete) throws DataException, AccessError;
public abstract void setName(String val) throws DataException, AccessError;
public abstract void setDescription(String val) throws DataException, AccessError;
public abstract void addAlias(String alias) throws DataException, AccessError;
public abstract void removeAlias(String alias) throws DataException, AccessError;
public abstract void addMember(int uid, boolean as_host) throws DataException, AccessError;
public abstract void removeMember(int uid) throws DataException, AccessError;
public abstract int getSIGGrantedLevel() throws DataException, AccessError;
public abstract void setSIGGrantedLevel(int new_level) throws DataException, AccessError;
public abstract short getSequence() throws DataException, AccessError;
public abstract void setSequence(short seq) throws DataException, AccessError;
public abstract boolean getHideList() throws DataException, AccessError;
public abstract void setHideList(boolean flag) throws DataException, AccessError;
public abstract String getDefaultPseud();
public abstract void setDefaultPseud(String val) throws DataException;
public abstract boolean anyUnread();
public abstract List getTopicList(int get_option, int sort_option) throws DataException, AccessError;
public abstract TopicContext getTopic(short number) throws DataException, AccessError;
} // end interface ConferenceContext

View File

@ -0,0 +1,93 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import org.w3c.dom.*;
import com.silverwrist.venice.VeniceException;
public class ConfigException extends VeniceException
{
// Attributes
private Node faulty_sect = null; // section of the configuration at fault
public ConfigException()
{
super();
} // end constructor
public ConfigException(String msg)
{
super(msg);
} // end constructor
public ConfigException(Exception e)
{
super(e);
} // end constructor
public ConfigException(String msg, Exception e)
{
super(msg,e);
} // end constructor
public ConfigException(Node faulty_sect)
{
super("Error in <" + faulty_sect.getNodeName() + "/> section of configuration!");
this.faulty_sect = faulty_sect;
} // end constructor
public ConfigException(String msg, Node faulty_sect)
{
super(msg);
this.faulty_sect = faulty_sect;
} // end constructor
public ConfigException(Exception e, Node faulty_sect)
{
super("Error in <" + faulty_sect.getNodeName() + "/> section of configuration - " + e.getMessage(),e);
this.faulty_sect = faulty_sect;
} // end constructor
public ConfigException(String msg, Exception e, Node faulty_sect)
{
super(msg,e);
this.faulty_sect = faulty_sect;
} // end constructor
protected void finalize() throws Throwable
{
faulty_sect = null;
super.finalize();
} // end finalize
public Node getFaultySect()
{
return faulty_sect;
} // end getFaultySect
} // end class ConfigException

View File

@ -0,0 +1,123 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.Date;
import java.sql.Connection;
public interface ContactInfo
{
public abstract int getContactID();
public abstract String getGivenName();
public abstract void setGivenName(String name);
public abstract String getFamilyName();
public abstract void setFamilyName(String name);
public abstract char getMiddleInitial();
public abstract void setMiddleInitial(char in);
public abstract String getNamePrefix();
public abstract void setNamePrefix(String p);
public abstract String getNameSuffix();
public abstract void setNameSuffix(String s);
public abstract String getCompany();
public abstract void setCompany(String c);
public abstract String getAddressLine1();
public abstract void setAddressLine1(String addr);
public abstract String getAddressLine2();
public abstract void setAddressLine2(String addr);
public abstract String getLocality();
public abstract void setLocality(String city);
public abstract String getRegion();
public abstract void setRegion(String state);
public abstract String getPostalCode();
public abstract void setPostalCode(String zip);
public abstract String getCountry();
public abstract void setCountry(String c);
public abstract String getPhone();
public abstract void setPhone(String num);
public abstract String getFax();
public abstract void setFax(String num);
public abstract String getMobile();
public abstract void setMobile(String num);
public abstract String getEmail();
public abstract void setEmail(String addr);
public abstract String getPhotoURL();
public abstract void setPhotoURL(String addr);
public abstract String getURL();
public abstract void setURL(String addr);
public abstract boolean getPrivateAddress();
public abstract void setPrivateAddress(boolean flag);
public abstract boolean getPrivatePhone();
public abstract void setPrivatePhone(boolean flag);
public abstract boolean getPrivateFax();
public abstract void setPrivateFax(boolean flag);
public abstract boolean getPrivateEmail();
public abstract void setPrivateEmail(boolean flag);
public abstract int getOwnerUID();
public abstract int getOwnerSIGID();
public abstract Date getLastUpdate();
public abstract boolean getModified();
} // end interface ContactInfo

View File

@ -0,0 +1,26 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public interface Country
{
public abstract String getCode();
public abstract String getName();
} // end interface Country

View File

@ -0,0 +1,46 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public class DataException extends com.silverwrist.venice.VeniceException
{
public DataException()
{
super();
} // end constructor
public DataException(String msg)
{
super(msg);
} // end constructor
public DataException(Exception e)
{
super(e);
} // end constructor
public DataException(String msg, Exception e)
{
super(msg,e);
} // end constructor
} // end class DataException

View File

@ -0,0 +1,46 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public class EmailException extends com.silverwrist.venice.VeniceException
{
public EmailException()
{
super();
} // end constructor
public EmailException(String msg)
{
super(msg);
} // end constructor
public EmailException(Exception e)
{
super(e);
} // end constructor
public EmailException(String msg, Exception e)
{
super(msg,e);
} // end constructor
} // end class EmailException

View File

@ -0,0 +1,36 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public interface FrontPageViewConfig
{
public abstract int getNumRows();
public abstract int getNumColumns();
public abstract String getPartID(int row, int column);
public abstract void setPartID(int row, int column, String partid);
public abstract String getParameter(int row, int column);
public abstract void setParameter(int row, int column, String param);
public abstract boolean getModified();
} // end interface FrontPageViewConfig

View File

@ -0,0 +1,75 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
public class IDUtils
{
/**
* The list of valid characters in Venice identifiers other than alphanumerics.
*/
private static final String EXTRA_VALID = "-_~*'$";
public static boolean isValidVeniceID(String id)
{
if ((id==null) || (id.length()==0))
return false; // null values and null strings are NEVER valid
for (int i=0; i<id.length(); i++)
{ // test each character in turn
char c = id.charAt(i);
if ((c>='A') && (c<='Z'))
continue; // upper-case letters are OK
if ((c>='a') && (c<='z'))
continue; // lower-case letters are OK
if ((c>='0') && (c<='9'))
continue; // digits are OK
if (EXTRA_VALID.indexOf(c)<0)
return false;
} // end for
return true; // all tests passed - ship it!
} // end isValidVeniceID
public static boolean isValidEmailAddress(String addr)
{
try
{ // take advantage of the JavaMail address parser
InternetAddress tmp = new InternetAddress(addr);
} // end try
catch (AddressException e)
{ // if we get an AddressException, it's not valid, is it?
return false;
} // end catch
return true; // if get here, it's valid
} // end isValidEmailAddress
public static boolean isValidConfirmationNumber(int num)
{
return ((num>=1000000) && (num<=9999999));
} // end isValidConfirmationNumber
} // end class IDUtils

View File

@ -0,0 +1,64 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public class InternalStateError extends RuntimeException
{
// Attributes
private Exception e = null; // internal "root cause" exception
public InternalStateError()
{
super();
} // end constructor
public InternalStateError(String msg)
{
super(msg);
} // end constructor
public InternalStateError(Exception e)
{
super(e.getMessage());
this.e = e;
} // end constructor
public InternalStateError(String msg, Exception e)
{
super(msg);
this.e = e;
} // end constructor
protected void finalize() throws Throwable
{
e = null;
super.finalize();
} // end finalize
public Exception getException()
{
return e;
} // end getException
} // end class InternalStateError

View File

@ -0,0 +1,26 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public interface Language
{
public abstract String getCode();
public abstract String getName();
} // end interface Language

View File

@ -0,0 +1,147 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.BitSet;
import java.util.Date;
import java.util.List;
public interface SIGContext
{
public static final int HIDE_NONE = 0;
public static final int HIDE_DIRECTORY = 1;
public static final int HIDE_BOTH = 2;
public abstract int getSIGID();
public abstract String getName();
public abstract String getAlias();
public abstract boolean isMember();
public abstract boolean isAdmin();
public abstract boolean isPublicSIG();
public abstract int getCategoryID();
public abstract CategoryDescriptor getCategory() throws DataException;
public abstract String getSynopsis();
public abstract int getHostUID();
public abstract UserProfile getHostProfile() throws DataException;
public abstract String getLanguageCode();
public abstract String getLanguageFullName();
public abstract String getRules();
public abstract Date getCreationDate();
public abstract Date getLastAccessDate();
public abstract Date getLastUpdateDate();
public abstract ContactInfo getContactInfo() throws DataException;
public abstract void putContactInfo(ContactInfo ci) throws DataException, AccessError;
public abstract BitSet getFeatures();
public abstract void setFeatures(BitSet feature_set, BitSet mask) throws DataException, AccessError;
public abstract List getSIGFeaturesList();
public abstract String getDefaultApplet();
public abstract void setName(String name) throws DataException, AccessError;
public abstract void setAlias(String alias) throws DataException, AccessError;
public abstract void setCategoryID(int catid) throws DataException, AccessError;
public abstract void setCategory(CategoryDescriptor cat) throws DataException, AccessError;
public abstract void setSynopsis(String synopsis) throws DataException, AccessError;
public abstract void setLanguage(String language) throws DataException, AccessError;
public abstract void setRules(String rules) throws DataException, AccessError;
public abstract int getHideMode();
public abstract void setHideMode(int mode) throws DataException, AccessError;
public abstract boolean getMembersOnly();
public abstract void setMembersOnly(boolean flag) throws DataException, AccessError;
public abstract short getInitialFeatureIndex();
public abstract void setInitialFeatureIndex(short ndx) throws DataException, AccessError;
public abstract String getJoinKey() throws DataException, AccessError;
public abstract void setJoinKey(String key) throws DataException, AccessError;
public abstract int getReadLevel() throws DataException, AccessError;
public abstract int getWriteLevel() throws DataException, AccessError;
public abstract int getCreateLevel() throws DataException, AccessError;
public abstract int getDeleteLevel() throws DataException, AccessError;
public abstract int getJoinLevel() throws DataException, AccessError;
public abstract void setSecurityLevels(int read, int write, int create, int delete, int join)
throws DataException, AccessError;
public abstract boolean canAdministerSIG();
public abstract boolean canModifyProfile();
public abstract boolean isAdminSIG();
public abstract void join(String joinkey) throws DataException, AccessError;
public abstract void unjoin() throws DataException, AccessError;
public abstract int getMemberCount() throws DataException;
public abstract boolean canUnjoin();
public abstract boolean canJoin();
public abstract List getConferences() throws DataException, AccessError;
public abstract ConferenceContext getConferenceContext(int confid) throws DataException, AccessError;
public abstract ConferenceContext getConferenceContext(String alias) throws DataException, AccessError;
public abstract ConferenceContext createConference(String name, String alias, String description,
boolean pvt, boolean hide_list)
throws DataException, AccessError;
public abstract boolean canCreateConference();
} // end interface SIGContext

View File

@ -0,0 +1,32 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public interface SIGFeature
{
public abstract int getFeatureCode();
public abstract String getSymbol();
public abstract String getName();
public abstract String getApplet();
public abstract int getSequence();
} // end interface SIGFeature

View File

@ -0,0 +1,40 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public interface SearchMode
{
public static final int FIELD_SIG_NAME = 0;
public static final int FIELD_SIG_SYNOPSIS = 1;
public static final int FIELD_USER_NAME = 2;
public static final int FIELD_USER_DESCRIPTION = 3;
public static final int FIELD_USER_GIVEN_NAME = 4;
public static final int FIELD_USER_FAMILY_NAME = 5;
public static final int SEARCH_PREFIX = 0;
public static final int SEARCH_SUBSTRING = 1;
public static final int SEARCH_REGEXP = 2;
} // end interface SearchMode

View File

@ -0,0 +1,216 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.io.*;
import javax.xml.parsers.*;
import org.apache.log4j.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.silverwrist.util.DOMElementHelper;
public class Startup
{
/*--------------------------------------------------------------------------------
* Static data values
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(Startup.class.getName());
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
private Startup()
{ // this class cannot be created
} // end constructor
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private static Document loadConfiguration(String configname) throws ConfigException
{
try
{ // create a simple DOM parser by using the Java XML parsing API
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
fac.setNamespaceAware(false);
fac.setValidating(false);
DocumentBuilder parser = fac.newDocumentBuilder();
// access the config file and parse it into our config data tree
File configfile = new File(configname);
Document rc = parser.parse(configfile);
if (logger.isDebugEnabled())
logger.debug("configuration loaded successfully");
return rc;
} // end try
catch (FactoryConfigurationError e1)
{ // if the document builder factory could not be created
logger.fatal("Parser factory configuration error: " + e1.getMessage(),e1);
throw new ConfigException("XML parser factory could not be created - " + e1.getMessage());
} // end catch
catch (ParserConfigurationException e2)
{ // if the XML parser itself could not be created
logger.fatal("Parser configuration error: " + e2.getMessage(),e2);
throw new ConfigException("XML parser could not be created - " + e2.getMessage(),e2);
} // end catch
catch (SAXException e3)
{ // if the XML parser choked on our document
if (e3 instanceof SAXParseException)
{ // we have a detailed message - make a proper exception
SAXParseException e3a = (SAXParseException)e3;
logger.fatal("Config file error [" + configname + ":" + e3a.getLineNumber() + ","
+ e3a.getColumnNumber() + "]: " + e3a.getMessage(),e3a);
throw new ConfigException("Configuration file error: " + e3a.getMessage() + " at line "
+ e3a.getLineNumber() + ", column " + e3a.getColumnNumber(),e3a);
} // end if
else
{ // generic exception - just send up a simple error message
logger.fatal("Config file error [" + configname + "]: " + e3.getMessage(),e3);
throw new ConfigException("Configuration file error - " + e3.getMessage(),e3);
} // end else
} // end catch
catch (IOException e4)
{ // error reading the config file itself off the disk
logger.fatal("IO error reading config: " + e4.getMessage(),e4);
throw new ConfigException("unable to read config file \"" + configname + "\" - " + e4.getMessage(),e4);
} // end catch
} // end loadConfiguration
private static String getEngineClassName(Document config) throws ConfigException
{
// Make sure the configuration is valid...
Element root = config.getDocumentElement();
if (!(root.getTagName().equals("venice-config")))
{ // not the correct root tag name
logger.fatal("config document is not a <venice-config/> document (root tag: <"
+ root.getTagName() + "/>)");
throw new ConfigException("document is not a <venice-config/> document",root);
} // end if
// Get the <engine/> section.
DOMElementHelper root_h = new DOMElementHelper(root);
Element engine_sect = root_h.getSubElement("engine");
if (engine_sect==null)
{ // no <engine/> section - bail out now!
logger.fatal("config document has no <engine/> section");
throw new ConfigException("no <engine/> section found in config file",root);
} // end if
// Get the classname out of that section.
DOMElementHelper engine_sect_h = new DOMElementHelper(engine_sect);
String rc = engine_sect_h.getSubElementText("classname");
if (rc==null)
{ // no <classname/> specified - bail out now!
logger.fatal("config document <engine/> section has no <classname/>");
throw new ConfigException("no <classname/> found in <engine/> section",engine_sect);
} // end if
return rc;
} // end getEngineClassName
/*--------------------------------------------------------------------------------
* External static methods (global functions)
*--------------------------------------------------------------------------------
*/
public static VeniceEngine createEngine(String configname) throws ConfigException, DataException
{
// load the configuration data
Document config = loadConfiguration(configname);
// find the classname of the engine
String cname = getEngineClassName(config);
if (logger.isDebugEnabled())
logger.debug("Venice engine classname: " + cname);
try
{ // attempt to load the engine class
Class engine_class = Class.forName(cname);
// now create a new Venice engine (cast to the external interface)
VeniceEngine engine = (VeniceEngine)(engine_class.newInstance());
if (logger.isDebugEnabled())
logger.debug("VeniceEngine created successfully");
// initialize the engine
engine.initialize(config);
// and return it
return engine;
} // end try
catch (ClassNotFoundException e1)
{ // the class was not found
logger.fatal("Venice engine class \"" + cname + "\" not found",e1);
throw new ConfigException("Invalid engine classname: " + cname);
} // end catch
catch (IllegalAccessException e2)
{ // could not access constructor or something
logger.fatal("Can't access \"" + cname + "\" constructor: " + e2.getMessage(),e2);
throw new ConfigException("Unable to create classname: " + cname);
} // end catch
catch (InstantiationException e3)
{ // could not create the instance
logger.fatal("Can't create instance of \"" + cname + "\": " + e3.getMessage(),e3);
throw new ConfigException("Unable to create classname: " + cname);
} // end catch
catch (ExceptionInInitializerError e4)
{ // some exception while initializing class
logger.fatal("Exception while initializing \"" + cname + "\": " + e4.getMessage(),e4);
throw new ConfigException("Unable to create classname: " + cname);
} // end catch
catch (SecurityException e5)
{ // security violation somewhere
logger.fatal("Security violation on \"" + cname + "\": " + e5.getMessage(),e5);
throw new ConfigException("Unable to create classname: " + cname);
} // end catch
catch (ClassCastException e6)
{ // engine could not be cast to VeniceEngine interface type
logger.fatal("\"" + cname + "\" is not of type VeniceEngine",e6);
throw new ConfigException("Invalid engine classname: " + cname);
} // end catch
} // end createEngine
} // end class Startup

View File

@ -0,0 +1,67 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.Date;
import java.util.List;
public interface TopicContext
{
public abstract void refresh() throws DataException;
public abstract int getTopicID();
public abstract short getTopicNumber();
public abstract String getName();
public abstract int getUnreadMessages();
public abstract int getTotalMessages();
public abstract Date getLastUpdateDate();
public abstract int getCreatorUID();
public abstract boolean isFrozen();
public abstract boolean isArchived();
public abstract Date getCreatedDate();
public abstract boolean isHidden();
public abstract boolean isDeleted();
public abstract boolean canFreeze();
public abstract boolean canArchive();
public abstract void setFrozen(boolean flag) throws DataException, AccessError;
public abstract void setArchived(boolean flag) throws DataException, AccessError;
public abstract void setHidden(boolean flag) throws DataException;
public abstract int getFirstUnreadMessage();
public abstract void setUnreadMessages(int count) throws DataException;
public abstract void fixSeen() throws DataException;
} // end interface TopicContext

View File

@ -0,0 +1,92 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.List;
public interface UserContext extends SearchMode
{
public abstract int getUID();
public abstract String getUserName();
public abstract int getContactID();
public abstract String getDescription();
public abstract boolean isLoggedIn();
public abstract boolean isEmailVerified();
public abstract void authenticate(String username, String password)
throws AccessError, DataException;
public abstract void confirmEmail(int conf_num) throws AccessError, DataException;
public abstract void resendEmailConfirmation() throws DataException, EmailException;
public abstract ContactInfo getContactInfo() throws DataException;
public abstract boolean putContactInfo(ContactInfo ci) throws DataException, EmailException;
public abstract UserProfile getProfile(String xusername) throws DataException;
public abstract UserProfile getProfile(int xuid) throws DataException;
public abstract void setPassword(String password, String reminder) throws DataException;
public abstract void setDescription(String new_descr) throws DataException;
public abstract FrontPageViewConfig getFrontPageViewConfig(int max_cols) throws DataException;
public abstract void putFrontPageViewConfig(FrontPageViewConfig cfg) throws DataException;
public abstract List getMemberSIGs() throws DataException;
public abstract SIGContext getSIGContext(int sigid) throws DataException;
public abstract SIGContext getSIGContext(String alias) throws DataException;
public abstract List getRootCategoryList() throws DataException;
public abstract CategoryDescriptor getCategoryDescriptor(int catid) throws DataException;
public abstract List searchForSIGs(int field, int mode, String term, int offset, int count)
throws DataException;
public abstract int getSearchSIGCount(int field, int mode, String term) throws DataException;
public abstract List getSIGsInCategory(int catid, int offset, int count) throws DataException;
public abstract List getSIGsInCategory(CategoryDescriptor cat, int offset, int count) throws DataException;
public abstract int getNumSIGsInCategory(int catid) throws DataException;
public abstract int getNumSIGsInCategory(CategoryDescriptor cat) throws DataException;
public abstract List searchForCategories(int mode, String term, int offset, int count) throws DataException;
public abstract int getSearchCategoryCount(int mode, String term) throws DataException;
public abstract SIGContext createSIG(String name, String alias, String language, String synopsis,
String rules, String joinkey, int hide_mode)
throws DataException, AccessError;
public abstract boolean canCreateSIG();
} // end interface UserContext

View File

@ -0,0 +1,40 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
public interface UserFound
{
public abstract int getUID();
public abstract String getName();
public abstract String getDescription();
public abstract String getGivenName();
public abstract String getFamilyName();
public abstract String getLocality();
public abstract String getRegion();
public abstract String getCountry();
public abstract int getLevel();
} // end interface UserFound

View File

@ -0,0 +1,74 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.Date;
public interface UserProfile
{
public abstract int getUID();
public abstract String getUserName();
public abstract String getGivenName();
public abstract String getFamilyName();
public abstract char getMiddleInitial();
public abstract String getNamePrefix();
public abstract String getNameSuffix();
public abstract String getCompany();
public abstract String getAddressLine1();
public abstract String getAddressLine2();
public abstract String getLocality();
public abstract String getRegion();
public abstract String getPostalCode();
public abstract String getCountry();
public abstract String getFullCountry();
public abstract String getPhone();
public abstract String getFax();
public abstract String getMobile();
public abstract String getEmail();
public abstract String getPhotoURL();
public abstract String getURL();
public abstract Date getCreateDate();
public abstract Date getLastLoginDate();
public abstract Date getLastUpdate();
public abstract String getDescription();
} // end interface UserProfile

View File

@ -0,0 +1,68 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core;
import java.util.BitSet;
import java.util.List;
import org.w3c.dom.Document;
import com.silverwrist.venice.htmlcheck.HTMLChecker;
public interface VeniceEngine extends SearchMode
{
public abstract void initialize(Document config) throws ConfigException, DataException;
public abstract int getNumFeatures();
public abstract BitSet getAllFeaturesMask();
public abstract List getCountryList() throws DataException;
public abstract List getLanguageList() throws DataException;
public abstract String getNameOfCountry(String code);
public abstract UserContext createUserContext(String remote_addr) throws DataException;
public abstract String getEmailAddressForUser(String username) throws DataException, AccessError;
public abstract void sendPasswordReminder(String username)
throws DataException, AccessError, EmailException;
public abstract UserContext createNewAccount(String remote_addr, String username, String password,
String reminder) throws DataException, AccessError;
public abstract boolean aliasExists(String alias, int exist_sigid);
public abstract boolean isValidCategoryID(int catid);
public abstract List searchForUsers(int field, int mode, String term, int offset, int count)
throws DataException;
public abstract int getSearchUserCount(int field, int mode, String term) throws DataException;
public abstract int getStdNumSearchResults();
public abstract boolean isEmailAddressBanned(String email);
public abstract boolean confAliasExists(String alias);
public abstract HTMLChecker getPreviewChecker();
public abstract HTMLChecker getEscapingChecker();
} // end interface VeniceEngine

View File

@ -0,0 +1,577 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.*;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.core.*;
class CategoryDescriptorImpl implements CategoryDescriptor, Cloneable
{
/*--------------------------------------------------------------------------------
* Internal class for saving category segments
*--------------------------------------------------------------------------------
*/
static class CatSegment
{
private int id;
private String name;
CatSegment(int id, String name)
{
this.id = id;
this.name = name;
} // end constructor
public int getID()
{
return id;
} // end getID
public String getName()
{
return name;
} // end getName
} // end class CatSegment
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(CategoryDescriptorImpl.class.getName());
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DataPool datapool; // used for doing database lookups
private Vector cats; // the actual category segments
private int symlink = -1; // if our category is actually a symlink
private boolean do_hide = true; // do we hide subcategories marked hide_dir?
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
CategoryDescriptorImpl(DataPool datapool, int catid, boolean do_hide) throws DataException
{
this.datapool = datapool;
cats = new Vector();
this.do_hide = do_hide;
if (catid<0)
return; // this is a "top" category
Connection conn = null;
try
{ // get a connection and a prepared statement
conn = datapool.getConnection();
doFillFromTop(conn,catid);
} // end try
catch (SQLException e)
{ // remap to DataException
throw new DataException("Unable to load category descriptor: " + e.getMessage(),e);
} // end catch
finally
{ // make sure and release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end constructor
protected CategoryDescriptorImpl(DataPool datapool, Connection conn, int catid, boolean do_hide)
throws SQLException, DataException
{
this.datapool = datapool;
cats = new Vector();
this.do_hide = do_hide;
if (catid<0)
return; // this is a "top" category
doFillFromTop(conn,catid);
} // end constructor
protected CategoryDescriptorImpl(DataPool datapool, int id, int symlink, String name, boolean do_hide)
{
this.datapool = datapool;
this.cats = new Vector();
this.symlink = symlink;
this.do_hide = do_hide;
this.cats.add(new CatSegment(id,name));
this.cats.trimToSize();
} // end constructor
protected CategoryDescriptorImpl(CategoryDescriptorImpl other, int copy_levels)
{
this.datapool = other.datapool;
this.cats = new Vector();
this.symlink = ((copy_levels==other.cats.size()) ? other.symlink : -1);
this.do_hide = other.do_hide;
if (copy_levels>0)
{ // copy the references to the objects directly
for (int i=0; i<copy_levels; i++)
this.cats.add(other.cats.get(i));
this.cats.trimToSize();
} // end if
} // end constructor
protected CategoryDescriptorImpl(CategoryDescriptorImpl other, int id, int symlink, String name)
{
this.datapool = other.datapool;
this.cats = new Vector();
this.symlink = symlink;
this.do_hide = other.do_hide;
// copy the references to the objects directly
for (int i=0; i<other.cats.size(); i++)
this.cats.add(other.cats.get(i));
this.cats.add(new CatSegment(id,name));
this.cats.trimToSize();
} // end constructor
/*--------------------------------------------------------------------------------
* finalize() function
*--------------------------------------------------------------------------------
*/
protected void finalize()
{
datapool = null;
cats = null;
} // end finalize
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private void doFillFromTop(Connection conn, int catid) throws SQLException, DataException
{
PreparedStatement stmt = conn.prepareStatement("SELECT parent, symlink, name "
+ "FROM refcategory WHERE catid = ?;");
int curr_catid = catid;
while (curr_catid!=-1)
{ // get the category reference for this level
stmt.setInt(1,curr_catid);
ResultSet rs = stmt.executeQuery();
if (!(rs.next())) // unable to read database
throw new DataException("category #" + String.valueOf(catid) + " could not be resolved");
// Save off the symbolic link value, if this category is a symlink.
int symlink_field = rs.getInt("symlink");
if (symlink_field!=-1)
{ // handle saving our symlink value - can only occur at END of path
if (cats.size()>0)
throw new InternalStateError("invalid symlink in category table (" + String.valueOf(curr_catid)
+ " => " + String.valueOf(symlink_field) + ")");
symlink = symlink_field;
} // end if
cats.add(0,new CatSegment(curr_catid,rs.getString("name")));
curr_catid = rs.getInt("parent");
} // end while
cats.trimToSize(); // shrink vector down to size
} // end doFillFromTop
/*--------------------------------------------------------------------------------
* Implementations from interface CategoryDescriptor
*--------------------------------------------------------------------------------
*/
public int getCategoryID()
{
if (cats.size()>0)
return ((CatSegment)(cats.lastElement())).getID();
else
return -1;
} // end getCategoryID
public int getNumLevels()
{
return cats.size();
} // end getNumLevels
public int getIDAtLevel(int level)
{
return ((CatSegment)(cats.get(level))).getID();
} // end getIDAtLevel
public String getTitleAtLevel(int level)
{
return ((CatSegment)(cats.get(level))).getName();
} // end getTitleAtLevel
public List getSubCategories() throws DataException
{
if (symlink!=-1)
{ // "snap" the symlink before getting subcategories
CategoryDescriptorImpl real_obj = new CategoryDescriptorImpl(datapool,symlink,do_hide);
return real_obj.getSubCategories();
} // end if
Connection conn = null;
Vector rc = new Vector();
try
{ // get a connection and create a statement
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT catid, symlink, name FROM refcategory WHERE parent = ");
sql.append(getCategoryID());
if (do_hide)
sql.append(" AND hide_dir = 0");
sql.append(';');
// run the database query
ResultSet rs = stmt.executeQuery(sql.toString());
while (rs.next())
{ // turn data values into CategoryDescriptor objects
CategoryDescriptor ncd = new CategoryDescriptorImpl(this,rs.getInt("catid"),rs.getInt("symlink"),
rs.getString("name"));
rc.add(ncd);
} // end while
} // end try
catch (SQLException e)
{ // remap to DataException
throw new DataException("Unable to load subcategories: " + e.getMessage(),e);
} // end catch
finally
{ // make sure and release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
// wrap the vector in a ReadOnlyVector object
return new ReadOnlyVector(rc);
} // end getSubCategories
public CategoryDescriptor getSuperCategory(int levels)
{
if ((levels<0) || (levels>(cats.size()-1)))
throw new IndexOutOfBoundsException("invalid supercategory level value");
return new CategoryDescriptorImpl(this,levels);
} // end getSuperCategory
public CategoryDescriptor getParentCategory()
{
return getSuperCategory(cats.size()-1);
} // end getParentCategory
public int getLinkedCategoryID()
{
if (symlink!=-1)
return symlink;
else
return getCategoryID();
} // end getLinkedCategoryID
public boolean isSymbolicLink()
{
return (symlink!=-1);
} // end isSymbolicLink
public CategoryDescriptor getLinkedCategory() throws DataException
{
if (symlink!=-1)
return new CategoryDescriptorImpl(datapool,symlink,do_hide);
else
return this;
} // end getLinkedCategory
public boolean equals(Object obj)
{
if (obj==null)
return false;
if (obj instanceof CategoryDescriptor)
{ // this is something we can compare to directly
CategoryDescriptor other = (CategoryDescriptor)obj;
return (other.getLinkedCategoryID()==getLinkedCategoryID());
} // end if
// compare string values
return obj.toString().equals(toString());
} // end equals
public int hashCode()
{
if (symlink!=-1)
return symlink;
else
return getCategoryID();
} // end hashCode
public String toString()
{
StringBuffer buf = new StringBuffer();
Iterator it = cats.iterator();
while (it.hasNext())
{ // concatenate all the parts together
CatSegment seg = (CatSegment)(it.next());
if (buf.length()>0)
buf.append(": ");
buf.append(seg.getName());
} // end while
return buf.toString();
} // end toString
public Object clone()
{
return new CategoryDescriptorImpl(this,cats.size());
} // end clone
/*--------------------------------------------------------------------------------
* Static operations for use within implementation package
*--------------------------------------------------------------------------------
*/
static List getTopLevelCategoryList(DataPool datapool, boolean do_hide) throws DataException
{
Connection conn = null;
Vector rc = new Vector();
try
{ // get a connection and create a statement
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT catid, symlink, name FROM refcategory WHERE parent = -1");
if (do_hide)
sql.append(" AND hide_dir = 0");
sql.append(';');
// run the database query
ResultSet rs = stmt.executeQuery(sql.toString());
while (rs.next())
{ // turn data values into CategoryDescriptor objects
CategoryDescriptor ncd = new CategoryDescriptorImpl(datapool,rs.getInt("catid"),rs.getInt("symlink"),
rs.getString("name"),do_hide);
rc.add(ncd);
} // end while
} // end try
catch (SQLException e)
{ // remap to DataException
throw new DataException("Unable to load subcategories: " + e.getMessage(),e);
} // end catch
finally
{ // make sure and release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
// wrap the vector in a ReadOnlyVector object
return new ReadOnlyVector(rc);
} // end getTopLevelCategoryList
static List searchForCategories(DataPool datapool, boolean do_hide, boolean search_all, int mode,
String term, int offset, int count) throws DataException
{
if (logger.isDebugEnabled())
logger.debug("Category search: mode = " + String.valueOf(mode) + ", term '" + term + "', offset = "
+ String.valueOf(offset) + ", count = " + String.valueOf(count));
Vector rc = new Vector();
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT catid FROM refcategory WHERE name ");
switch (mode)
{ // compose SQL in different ways depending on the search term
case SearchMode.SEARCH_PREFIX:
sql.append("LIKE '").append(SQLUtil.encodeStringWildcards(term)).append("%'");
break;
case SearchMode.SEARCH_SUBSTRING:
sql.append("LIKE '%").append(SQLUtil.encodeStringWildcards(term)).append("%'");
break;
case SearchMode.SEARCH_REGEXP:
sql.append("REGEXP '").append(SQLUtil.encodeString(term)).append('\'');
break;
default:
throw new DataException("invalid search mode specified");
} // end switch
if (do_hide)
sql.append(" AND hide_dir = 0");
if (!search_all)
sql.append(" AND hide_search = 0");
sql.append(" ORDER BY parent, name LIMIT ").append(offset).append(", ").append(count+1).append(';');
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
// launch the search!
ResultSet rs = stmt.executeQuery(sql.toString());
int[] rc_raw = new int[count+1];
int n = 0;
while (rs.next()) // just read off the matching CATIDs for now
rc_raw[n++] = rs.getInt("catid");
for (int i=0; i<n; i++)
{ // convert all the simple category IDs into full-blown CategoryDescriptor objects
CategoryDescriptor tmp = new CategoryDescriptorImpl(datapool,conn,rc_raw[i],do_hide);
rc.add(tmp);
} // end for
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error reading SIG entries: " + e.getMessage(),e);
throw new DataException("unable to retrieve user SIG information: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
return new ReadOnlyVector(rc);
} // end searchForCategories
static int getSearchCategoryCount(DataPool datapool, boolean do_hide, boolean search_all, int mode,
String term) throws DataException
{
if (logger.isDebugEnabled())
logger.debug("Category search: mode = " + String.valueOf(mode) + ", term '" + term + "'");
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT COUNT(*) AS total FROM refcategory WHERE name ");
switch (mode)
{ // compose SQL in different ways depending on the search term
case SearchMode.SEARCH_PREFIX:
sql.append("LIKE '").append(SQLUtil.encodeStringWildcards(term)).append("%'");
break;
case SearchMode.SEARCH_SUBSTRING:
sql.append("LIKE '%").append(SQLUtil.encodeStringWildcards(term)).append("%'");
break;
case SearchMode.SEARCH_REGEXP:
sql.append("REGEXP '").append(SQLUtil.encodeString(term)).append('\'');
break;
default:
throw new DataException("invalid search mode specified");
} // end switch
if (do_hide)
sql.append(" AND hide_dir = 0");
if (!search_all)
sql.append(" AND hide_search = 0");
sql.append(';');
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
// launch the search!
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new InternalStateError("getSearchCategoryCount search failure (MUST have 1 row!)");
return rs.getInt("total");
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error reading SIG entries: " + e.getMessage(),e);
throw new DataException("unable to retrieve user SIG information: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end getSearchCategoryCount
} // end class CategoryDescriptorImpl

View File

@ -0,0 +1,32 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.*;
public interface ConferenceBackend extends SIGBackend
{
public abstract int realConfID();
public abstract boolean userCanHide();
public abstract void touchRead(Connection conn) throws SQLException;
public abstract String realConfAlias();
} // end interface ConferenceBackend

View File

@ -0,0 +1,958 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.*;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.DefaultLevels;
import com.silverwrist.venice.core.*;
class ConferenceCoreData implements ConferenceData
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(ConferenceCoreData.class.getName());
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private int refcount = 1; // object reference count
private EngineBackend engine; // pointer to engine back end
private DataPool datapool; // pointer to data pool
private int confid; // ID of this conference
private java.util.Date create_date; // creation date of this conference
private java.util.Date last_update; // last update date of conference
private int read_level; // access level required to read conference contents
private int post_level; // access level required to post messages
private int create_level; // access level required to create new topics
private int hide_level; // access level required to hide posts/archive topics
private int nuke_level; // access level required to delete topics/scribble/nuke posts
private int change_level; // access level required to modify conference profile
private int delete_level; // access level required to delete conference
private int top_topic; // the highest topic number in the conference
private String name; // the name of the conference
private String description; // the conference's description
private String cached_alias = null; // the cached alias (for getAnAlias)
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
ConferenceCoreData(EngineBackend engine, DataPool datapool, int confid) throws DataException
{
if (logger.isDebugEnabled())
logger.debug("new ConferenceCoreData for conference " + String.valueOf(confid));
this.engine = engine;
this.datapool = datapool;
this.confid = confid;
Connection conn = null;
try
{ // get a database connection from this object
conn = datapool.getConnection();
// get the conference basic data from the database
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT * FROM confs WHERE confid = ");
sql.append(confid).append(';');
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new DataException("Conference #" + String.valueOf(confid) + " does not exist in the database.");
loadData(rs); // load the conference data
} // end try
catch (SQLException e)
{ // translate into a nicer DataException
logger.error("DB error reading conference data: " + e.getMessage(),e);
throw new DataException("unable to load conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end constructor
protected ConferenceCoreData(EngineBackend engine, DataPool datapool, int confid, java.util.Date created,
boolean pvt, String name, String descr)
{
if (logger.isDebugEnabled())
logger.debug("new ConferenceCoreData for NEW conference " + String.valueOf(confid));
this.engine = engine;
this.datapool = datapool;
this.confid = confid;
this.create_date = created;
this.last_update = null;
this.read_level = DefaultLevels.newConferenceRead(pvt);
this.post_level = DefaultLevels.newConferencePost(pvt);
this.create_level = DefaultLevels.newConferenceCreate(pvt);
this.hide_level = DefaultLevels.newConferenceHide();
this.nuke_level = DefaultLevels.newConferenceNuke();
this.change_level = DefaultLevels.newConferenceChange();
this.delete_level = DefaultLevels.newConferenceDelete();
this.top_topic = 0;
this.name = name;
this.description = descr;
} // end constructor
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private synchronized void loadData(ResultSet rs) throws SQLException
{
// "confid" field is skipped
create_date = SQLUtil.getFullDateTime(rs,"createdate");
last_update = SQLUtil.getFullDateTime(rs,"lastupdate");
read_level = rs.getInt("read_lvl");
post_level = rs.getInt("post_lvl");
create_level = rs.getInt("create_lvl");
hide_level = rs.getInt("hide_lvl");
nuke_level = rs.getInt("nuke_lvl");
change_level = rs.getInt("change_lvl");
delete_level = rs.getInt("delete_lvl");
top_topic = rs.getInt("top_topic");
name = rs.getString("name");
description = rs.getString("descr");
// "icon_url" and "color" fields are skipped
} // end loadData
private synchronized void touchUpdate(Connection conn) throws SQLException
{
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE confs SET lastupdate = '");
java.util.Date now = new java.util.Date();
sql.append(SQLUtil.encodeDate(now)).append("' WHERE confid = ").append(confid).append(';');
stmt.executeUpdate(sql.toString());
last_update = now;
} // end touchUpdate
/*--------------------------------------------------------------------------------
* Implementations from interface ReferencedData
*--------------------------------------------------------------------------------
*/
public int rd_addRef()
{
return ++refcount;
} // end rd_addRef()
public int rd_release()
{
return --refcount;
} // end rd_release
public boolean rd_unreferenced()
{
return (refcount<=0);
} // end rd_unreferenced
/*--------------------------------------------------------------------------------
* Implementations from interface ConferenceData
*--------------------------------------------------------------------------------
*/
public int getID()
{
return confid;
} // end getID
public String getName()
{
return name;
} // end getName
public String getDescription()
{
return description;
} // end getDescription
public java.util.Date getCreationDate()
{
return create_date;
} // end getCreationDate
public java.util.Date getLastUpdateDate()
{
return last_update;
} // end getLastUpdate
public List getAliases() throws DataException
{
Connection conn = null;
Vector rc = new Vector();
try
{ // get a database connection from this object
conn = datapool.getConnection();
// get a list of all aliases
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT alias FROM confalias WHERE confid = ");
sql.append(confid).append(" ORDER BY alias;");
// execute the query
ResultSet rs = stmt.executeQuery(sql.toString());
while (rs.next())
rc.add(rs.getString(1));
} // end try
catch (SQLException e)
{ // translate into a nicer DataException
logger.error("DB error reading conference data: " + e.getMessage(),e);
throw new DataException("unable to load conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
return new ReadOnlyVector(rc);
} // end getAlias
public List getHosts() throws DataException
{
Connection conn = null;
Vector rc = new Vector();
try
{ // get a database connection from this object
conn = datapool.getConnection();
// get a list of all hosts (with user info)
Statement stmt = conn.createStatement();
StringBuffer sql =
new StringBuffer("SELECT u.uid, u.username, u.description, c.given_name, c.family_name, "
+ "c.locality, c.region, c.country FROM users u, contacts c, confmember m "
+ "WHERE u.contactid = c.contactid AND u.uid = m.uid AND m.confid = ");
sql.append(confid).append(" AND m.granted_lvl >= ").append(DefaultLevels.hostPrivsConference());
sql.append(" ORDER BY u.username;");
// execute the query
ResultSet rs = stmt.executeQuery(sql.toString());
while (rs.next())
{ // create the UserFound
UserFound uf = new UserFoundImpl(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),
rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8));
rc.add(uf);
} // end while
} // end try
catch (SQLException e)
{ // translate into a nicer DataException
logger.error("DB error reading conference hosts: " + e.getMessage(),e);
throw new DataException("unable to load conference hosts: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
return new ReadOnlyVector(rc);
} // end getHosts
public boolean canReadConference(int level)
{
return (level>=read_level);
} // end canReadConference
public boolean canPostToConference(int level)
{
return (level>=post_level);
} // end canReadConference
public boolean canCreateTopic(int level)
{
return (level>=create_level);
} // end canCreateTopic
public boolean canChangeConference(int level)
{
return (level>=change_level);
} // end canChangeConference
public int getReadLevel()
{
return read_level;
} // end getReadLevel
public int getPostLevel()
{
return post_level;
} // end getPostLevel
public int getCreateLevel()
{
return create_level;
} // end getCreateLevel
public int getHideLevel()
{
return hide_level;
} // end getHideLevel
public int getNukeLevel()
{
return nuke_level;
} // end getNukeLevel
public int getChangeLevel()
{
return change_level;
} // end getChangeLevel
public int getDeleteLevel()
{
return delete_level;
} // end getDeleteLevel
public synchronized void setSecurityLevels(SIGBackend sig, int read, int post, int create, int hide,
int nuke, int change, int delete) throws DataException
{
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
try
{ // get a database connection
conn = datapool.getConnection();
// create the SQL statement
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE confs SET read_lvl = ");
sql.append(read).append(", post_lvl = ").append(post).append(", create_lvl = ").append(create);
sql.append(", hide_lvl = ").append(hide).append(", nuke_lvl = ").append(nuke).append(", change_lvl = ");
sql.append(change).append(", delete_lvl = ").append(delete).append(", lastupdate = '");
java.util.Date now = new java.util.Date();
sql.append(SQLUtil.encodeDate(now)).append("' WHERE confid = ").append(confid).append(';');
// execute the update
stmt.executeUpdate(sql.toString());
// save copies of the data in our local variables
read_level = read;
post_level = post;
create_level = create;
hide_level = hide;
nuke_level = nuke;
change_level = change;
delete_level = delete;
last_update = now;
// create an audit record reflecting the change
ar = new AuditRecord(AuditRecord.CONF_SECURITY,sig.realUID(),sig.userRemoteAddress(),sig.realSIGID(),
"conf=" + String.valueOf(confid));
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference data: " + e.getMessage(),e);
throw new DataException("unable to save conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setSecurityLevels
public synchronized void setName(SIGBackend sig, String val) throws DataException
{
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
try
{ // get a database connection
conn = datapool.getConnection();
// create the SQL statement
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE confs SET name = '");
sql.append(SQLUtil.encodeString(val)).append("', lastupdate = '");
java.util.Date now = new java.util.Date();
sql.append(SQLUtil.encodeDate(now)).append("' WHERE confid = ").append(confid).append(';');
// execute the update
stmt.executeUpdate(sql.toString());
// save copies of the data in our local variables
name = val;
last_update = now;
// create an audit record reflecting the change
ar = new AuditRecord(AuditRecord.CONF_SECURITY,sig.realUID(),sig.userRemoteAddress(),sig.realSIGID(),
"conf=" + String.valueOf(confid));
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference data: " + e.getMessage(),e);
throw new DataException("unable to save conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setName
public synchronized void setDescription(String val) throws DataException
{
Connection conn = null; // database connection
try
{ // get a database connection
conn = datapool.getConnection();
// create the SQL statement
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE confs SET descr = '");
sql.append(SQLUtil.encodeString(val)).append("', lastupdate = '");
java.util.Date now = new java.util.Date();
sql.append(SQLUtil.encodeDate(now)).append("' WHERE confid = ").append(confid).append(';');
// execute the update
stmt.executeUpdate(sql.toString());
// save copies of the data in our local variables
description = val;
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference data: " + e.getMessage(),e);
throw new DataException("unable to save conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setDescription
public synchronized void addAlias(SIGBackend sig, String alias) throws DataException
{
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES confalias WRITE;");
try
{ // first check to see if the alias already exists
StringBuffer sql = new StringBuffer("SELECT confid FROM confalias WHERE alias = '");
String alias_encode = SQLUtil.encodeString(alias);
sql.append(alias_encode).append("';");
ResultSet rs = stmt.executeQuery(sql.toString());
if (rs.next())
{ // already exists...but is it in this conference or a different one?
if (confid==rs.getInt(1))
return; // this conference - this is a no-op
throw new DataException("The alias \"" + alias + "\" is already in use by a different conference.");
} // end if
// now add it!
sql.setLength(0);
sql.append("INSERT INTO confalias (confid, alias) VALUES (").append(confid).append(", '");
sql.append(alias_encode).append("');");
stmt.executeUpdate(sql.toString());
} // end try
finally
{ // make sure we unlock the tables before we go
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
// set the database's update date and generate a new audit record
touchUpdate(conn);
ar = new AuditRecord(AuditRecord.CONF_ALIAS,sig.realUID(),sig.userRemoteAddress(),sig.realSIGID(),
"conf=" + String.valueOf(confid),"add=" + alias);
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference alias: " + e.getMessage(),e);
throw new DataException("unable to save conference alias: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end addAlias
public synchronized void removeAlias(SIGBackend sig, String alias) throws DataException
{
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
try
{ // get a database connection
conn = datapool.getConnection();
boolean did_it = false;
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES confalias WRITE;");
try
{ // first check to see how many aliases there are
StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM confalias WHERE confid = ");
sql.append(confid).append(';');
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new InternalStateError("removeAlias query screwup - must be at least ONE row!");
int alias_count = rs.getInt(1);
if (alias_count<=0)
throw new InternalStateError("removeAlias database failure - detected less than one alias!");
if (alias_count==1)
{ // OK, there's only one alias - make sure it ain't the one we're trying to remove!
sql.setLength(0);
sql.append("SELECT alias FROM confalias WHERE confid = ").append(confid).append(" AND alias = '");
sql.append(SQLUtil.encodeString(alias)).append("';");
rs = stmt.executeQuery(sql.toString());
if (rs.next()) // it is - that would be bad, throw an error!
throw new DataException("The conference must have at least one alias.");
return; // but if it isn't, we're not going to succeed in removing it anyway
} // end if
// OK, go delete the row (or not, if this alias is not in the table)
sql.setLength(0);
sql.append("DELETE FROM confalias WHERE confid = ").append(confid).append("AND alias = '");
sql.append(SQLUtil.encodeString(alias)).append("';");
did_it = (stmt.executeUpdate(sql.toString())>0);
} // end try
finally
{ // make sure we unlock the tables before we go
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
if (did_it)
{ // set the database's update date and generate a new audit record
touchUpdate(conn);
if (cached_alias.equals(alias))
cached_alias = null; // also release the cached alias and force a re-get
ar = new AuditRecord(AuditRecord.CONF_ALIAS,sig.realUID(),sig.userRemoteAddress(),sig.realSIGID(),
"conf=" + String.valueOf(confid),"remove=" + alias);
} // end if
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference alias: " + e.getMessage(),e);
throw new DataException("unable to save conference alias: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end removeAlias
public synchronized void setMembership(SIGBackend sig, int uid, int grant_level) throws DataException
{
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
try
{ // get a database connection
conn = datapool.getConnection();
boolean did_it = false;
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES confmember WRITE;");
try
{ // how we go about this depends on whether we're adding or removing
StringBuffer sql = new StringBuffer();
if (grant_level>=0)
{ // see whether the user is in the table yet...
sql.append("SELECT granted_lvl FROM confmember WHERE confid = ").append(confid);
sql.append(" AND uid = ").append(uid).append(';');
ResultSet rs = stmt.executeQuery(sql.toString());
sql.setLength(0);
if (rs.next())
{ // just poke the new level value in
sql.append("UPDATE confmember SET granted_lvl = ").append(grant_level).append(" WHERE confid = ");
sql.append(confid).append(" AND uid = ").append(uid).append(';');
} // end if
else
{ // need to insert a new row...
sql.append("INSERT INTO confmember (confid, uid, granted_lvl) VALUES (").append(confid);
sql.append(", ").append(uid).append(", ").append(grant_level).append(");");
} // end else
stmt.executeUpdate(sql.toString());
did_it = true;
} // end if
else
{ // just try to delete this row from the table (if possible)
sql.append("DELETE FROM confmember WHERE confid = ").append(confid).append(" AND uid = ");
sql.append(uid).append(';');
did_it = (stmt.executeUpdate(sql.toString())>0);
} // end else
} // end try
finally
{ // make sure we unlock the tables before we go
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
if (did_it)
{ // set the database's update date and generate a new audit record
touchUpdate(conn);
ar = new AuditRecord(AuditRecord.CONF_MEMBERSHIP,sig.realUID(),sig.userRemoteAddress(),sig.realSIGID(),
"conf=" + String.valueOf(confid),"uid=" + String.valueOf(uid),
"level=" + String.valueOf(grant_level));
} // end if
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference data: " + e.getMessage(),e);
throw new DataException("unable to save conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setMembership
public boolean canHideTopics(int level)
{
return (level>=hide_level);
} // end canHideTopics
public synchronized String getAnAlias() throws DataException
{
if (cached_alias!=null)
return cached_alias;
Connection conn = null;
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// create the SQL statement and execute it
StringBuffer sql = new StringBuffer("SELECT alias FROM confalias WHERE confid = ");
sql.append(confid).append(" LIMIT 1;");
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new DataException("unable to find alias for conference");
cached_alias = rs.getString(1);
return cached_alias;
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error retrieving conference data: " + e.getMessage(),e);
throw new DataException("unable to get conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end getAnAlias
/*--------------------------------------------------------------------------------
* External static operations (usable only from within package)
*--------------------------------------------------------------------------------
*/
static ReturnConfSeq createConference(EngineBackend engine, SIGBackend sig, DataPool datapool, String name,
String alias, String description, boolean pvt, boolean hide_list,
int host_uid) throws DataException
{
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
int new_confid; // new conference ID
short new_sequence; // new sequence number
java.util.Date created; // date/time conference created
if (logger.isDebugEnabled())
logger.debug("createConference entry");
try
{ // start by locking all the tables we need
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES confs WRITE, sigtoconf WRITE, confalias WRITE, confmember WRITE;");
try
{ // first check on the alias availability
StringBuffer sql = new StringBuffer("SELECT confid FROM confalias WHERE alias = '");
String alias_encode = SQLUtil.encodeString(alias);
sql.append(alias_encode).append("';");
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
ResultSet rs = stmt.executeQuery(sql.toString());
if (rs.next()) // already used - this is bogus!
throw new DataException("The alias \"" + alias + "\" is already in use by a different conference.");
// compute our new sequence number
sql.setLength(0);
sql.append("SELECT MAX(sequence) FROM sigtoconf WHERE sigid = ").append(sig.realSIGID()).append(';');
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new InternalStateError("bogus query in createConference - must return at least 1 row!");
new_sequence = (short)(rs.getShort(1) + 100);
// insert the record into the conferences table!
sql.setLength(0);
sql.append("INSERT INTO confs (createdate, read_lvl, post_lvl, create_lvl, hide_lvl, nuke_lvl, "
+ "change_lvl, delete_lvl, top_topic, name, descr) VALUES ('");
created = new java.util.Date();
sql.append(SQLUtil.encodeDate(created)).append("', ").append(DefaultLevels.newConferenceRead(pvt));
sql.append(", ").append(DefaultLevels.newConferencePost(pvt)).append(", ");
sql.append(DefaultLevels.newConferenceCreate(pvt)).append(", ");
sql.append(DefaultLevels.newConferenceHide()).append(", ").append(DefaultLevels.newConferenceNuke());
sql.append(", ").append(DefaultLevels.newConferenceChange()).append(", ");
sql.append(DefaultLevels.newConferenceDelete()).append(", 0, '").append(SQLUtil.encodeString(name));
sql.append("', '").append(SQLUtil.encodeString(description)).append("');");
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
stmt.executeUpdate(sql.toString());
// Get the new conference ID.
rs = stmt.executeQuery("SELECT LAST_INSERT_ID();");
if (!(rs.next()))
throw new InternalStateError("bogus query in createConference - must get new confid!");
new_confid = rs.getInt(1);
// Make the insert into the confalias table to give the conference an alias.
sql.setLength(0);
sql.append("INSERT INTO confalias (confid, alias) VALUES (").append(new_confid).append(", '");
sql.append(alias_encode).append("');");
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
stmt.executeUpdate(sql.toString());
// Link the SIG to the conference by adding a row to sigtoconf.
sql.setLength(0);
sql.append("INSERT INTO sigtoconf (sigid, confid, sequence, hide_list) VALUES (");
sql.append(sig.realSIGID()).append(", ").append(new_confid).append(", ").append(new_sequence);
sql.append(", ").append(hide_list ? '1' : '0').append(");");
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
stmt.executeUpdate(sql.toString());
// Make the specified UID the host of this new conference.
sql.setLength(0);
sql.append("INSERT INTO confmember (confid, uid, granted_lvl) VALUES (").append(new_confid);
sql.append(", ").append(host_uid).append(", ").append(DefaultLevels.hostConference()).append(");");
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
stmt.executeUpdate(sql.toString());
} // end try
finally
{ // unlock the tables before we go
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
// create an audit record indicating we were successful
ar = new AuditRecord(AuditRecord.CREATE_CONF,sig.realUID(),sig.userRemoteAddress(),sig.realSIGID(),
"confid=" + String.valueOf(new_confid),"name=" + name,"alias=" + alias);
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error creating SIG: " + e.getMessage(),e);
throw new DataException("unable to create SIG: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
// Create a new ConferenceCoreData object representing this conference and register it with the
// engine's conference data object cache.
ConferenceCoreData conf = new ConferenceCoreData(engine,datapool,new_confid,created,pvt,name,description);
engine.registerNewConference(conf);
return new ReturnConfSeq(conf,new_sequence);
} // end createConference
} // end class ConferenceCoreData

View File

@ -0,0 +1,79 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.util.Date;
import java.util.List;
import com.silverwrist.venice.core.DataException;
public interface ConferenceData extends ReferencedData
{
public abstract int getID();
public abstract String getName();
public abstract String getDescription();
public abstract Date getCreationDate();
public abstract Date getLastUpdateDate();
public abstract List getAliases() throws DataException;
public abstract List getHosts() throws DataException;
public abstract boolean canReadConference(int level);
public abstract boolean canPostToConference(int level);
public abstract boolean canCreateTopic(int level);
public abstract boolean canChangeConference(int level);
public abstract int getReadLevel();
public abstract int getPostLevel();
public abstract int getCreateLevel();
public abstract int getHideLevel();
public abstract int getNukeLevel();
public abstract int getChangeLevel();
public abstract int getDeleteLevel();
public abstract void setSecurityLevels(SIGBackend sig, int read, int post, int create, int hide,
int nuke, int change, int delete) throws DataException;
public abstract void setName(SIGBackend sig, String val) throws DataException;
public abstract void setDescription(String val) throws DataException;
public abstract void addAlias(SIGBackend sig, String alias) throws DataException;
public abstract void removeAlias(SIGBackend sig, String alias) throws DataException;
public abstract void setMembership(SIGBackend sig, int uid, int grant_level) throws DataException;
public abstract boolean canHideTopics(int level);
public abstract String getAnAlias() throws DataException;
} // end interface ConferenceData

View File

@ -0,0 +1,91 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.util.Date;
import java.util.List;
import com.silverwrist.venice.core.DataException;
public interface ConferenceSIGContext extends ReferencedData
{
public abstract int getConfID();
public abstract String getName();
public abstract String getDescription();
public abstract Date getCreationDate();
public abstract Date getLastUpdateDate();
public abstract int getSIGGrantedLevel();
public abstract List getAliases() throws DataException;
public abstract List getHosts() throws DataException;
public abstract boolean canReadConference(int level);
public abstract boolean canPostToConference(int level);
public abstract boolean canCreateTopic(int level);
public abstract boolean canChangeConference(int level);
public abstract int getReadLevel() throws DataException;
public abstract int getPostLevel() throws DataException;
public abstract int getCreateLevel() throws DataException;
public abstract int getHideLevel() throws DataException;
public abstract int getNukeLevel() throws DataException;
public abstract int getChangeLevel() throws DataException;
public abstract int getDeleteLevel() throws DataException;
public abstract void setSecurityLevels(SIGBackend sig, int read, int post, int create, int hide,
int nuke, int change, int delete) throws DataException;
public abstract void setName(SIGBackend sig, String val) throws DataException;
public abstract void setDescription(String val) throws DataException;
public abstract void addAlias(SIGBackend sig, String alias) throws DataException;
public abstract void removeAlias(SIGBackend sig, String alias) throws DataException;
public abstract void setMembership(SIGBackend sig, int uid, int grant_level) throws DataException;
public abstract void setSIGGrantedLevel(SIGBackend sig, int new_level) throws DataException;
public abstract short getSequence();
public abstract void setSequence(short seq) throws DataException;
public abstract boolean getHideList();
public abstract void setHideList(SIGBackend sig, boolean flag) throws DataException;
public abstract boolean canHideTopics(int level);
public abstract String getAnAlias() throws DataException;
} // end interface ConferenceSIGContext

View File

@ -0,0 +1,614 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.*;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.core.*;
class ConferenceSIGContextImpl implements ConferenceSIGContext
{
/*--------------------------------------------------------------------------------
* Inner class used to cache locally-important data
*--------------------------------------------------------------------------------
*/
static class ConfCache
{
String name;
String description;
java.util.Date created;
public ConfCache(String name, String description, java.util.Date created)
{
this.name = name;
this.description = description;
this.created = created;
} // end constructor
public String getName()
{
return name;
} // end getName
public String getDescription()
{
return description;
} // end getDescription
public java.util.Date getCreated()
{
return created;
} // end getCreated
} // end class ConfCache
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(ConferenceSIGContextImpl.class.getName());
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private int refcount = 1; // reference count (within the SIGData)
private EngineBackend engine; // engine object reference
private SIGDataBackend sig; // SIG object reference
private DataPool datapool; // data pool object
private int confid; // ID of this conference
private int level; // level granted in conference to members of the SIG
private short sequence; // sequence number this conference appears in list
private boolean hide_list; // hide the conference in the list?
private ConfCache cache; // cache of locally-important information
private ConferenceData confdata = null; // the inner conference data object
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
ConferenceSIGContextImpl(EngineBackend engine, SIGDataBackend sig, DataPool datapool, int confid)
throws DataException
{
if (logger.isDebugEnabled())
logger.debug("new ConferenceSIGContextImpl(#" + String.valueOf(confid) + ") for SIG # "
+ String.valueOf(sig.realSIGID()));
this.engine = engine;
this.sig = sig;
this.datapool = datapool;
this.confid = confid;
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// Build a monster query! This is like the query for retrieving the ConferenceUserContextImpl
// data, except without the left outer join to the user conference membership table.
StringBuffer sql =
new StringBuffer("SELECT c.createdate, c.name, c.descr, s.granted_lvl, s.sequence, s.hide_list "
+ "FROM sigtoconf s, confs c WHERE s.confid = c.confid AND s.sigid = ");
sql.append(sig.realSIGID()).append(" AND c.confid = ").append(confid).append(';');
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
// Run that monster query!
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new DataException("conference ID#" + String.valueOf(confid) + " not found in SIG#"
+ String.valueOf(sig.realSIGID()));
// fill in the "cache" and "level" indicators
this.cache = new ConfCache(rs.getString(2),rs.getString(3),SQLUtil.getFullDateTime(rs,1));
this.level = rs.getInt(4);
this.sequence = rs.getShort(5);
this.hide_list = rs.getBoolean(6);
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error reading conference entry: " + e.getMessage(),e);
throw new DataException("unable to retrieve conference information: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end constructor
ConferenceSIGContextImpl(EngineBackend engine, SIGDataBackend sig, DataPool datapool,
short sequence, boolean hide_list, ConferenceData cdata)
{
if (logger.isDebugEnabled())
logger.debug("new ConferenceSIGContextImpl(NEW#" + String.valueOf(confid) + ") for SIG # "
+ String.valueOf(sig.realSIGID()));
this.engine = engine;
this.sig = sig;
this.datapool = datapool;
this.confid = cdata.getID();
this.level = 0;
this.sequence = sequence;
this.hide_list = hide_list;
this.cache = null;
cdata.rd_addRef();
this.confdata = cdata;
} // end constructor
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private synchronized ConferenceData getConferenceData() throws DataException
{
if (confdata==null)
{ // attempt to load the ConferenceSIGContext
confdata = engine.getConferenceDataObject(confid);
// clear cache when we get the real confdata
cache = null;
} // end if
return confdata;
} // end getConferenceData
private synchronized ConferenceData getConferenceDataNE()
{
if (confdata==null)
{ // we need to load the ConferenceSIGContext...
try
{ // attempt to load the ConferenceSIGContext
confdata = engine.getConferenceDataObject(confid);
} // end try
catch (DataException e)
{ // there was a data failure loading the conference
logger.error("** Got DataException in getConferenceDataNE: " + e.getMessage(),e);
return null;
} // end catch
// clear cache when we get the real confdata
cache = null;
} // end if
return confdata;
} // end getConferenceDataNE
/*--------------------------------------------------------------------------------
* Implementations from interface ReferencedData
*--------------------------------------------------------------------------------
*/
public int rd_addRef()
{
return ++refcount;
} // end rd_addRef
public int rd_release()
{
return --refcount;
} // end rd_release
public boolean rd_unreferenced()
{
return (refcount<=0);
} // end rd_unreferences
/*--------------------------------------------------------------------------------
* Implementations from interface ConferenceSIGContext
*--------------------------------------------------------------------------------
*/
public int getConfID()
{
return confid;
} // end getConfID
public String getName()
{
if (cache!=null)
return cache.getName();
ConferenceData c = getConferenceDataNE();
if (c!=null)
return c.getName();
else
return null;
} // end getName
public String getDescription()
{
if (cache!=null)
return cache.getDescription();
ConferenceData c = getConferenceDataNE();
if (c!=null)
return c.getDescription();
else
return null;
} // end getDescription
public java.util.Date getCreationDate()
{
if (cache!=null)
return cache.getCreated();
ConferenceData c = getConferenceDataNE();
if (c!=null)
return c.getCreationDate();
else
return null;
} // end getCreationDate
public java.util.Date getLastUpdateDate()
{
ConferenceData c = getConferenceDataNE();
if (c!=null)
return c.getLastUpdateDate();
else
return null;
} // end getLastUpdateDate
public int getSIGGrantedLevel()
{
return level;
} // end getSIGGrantedLevel
public List getAliases() throws DataException
{
return getConferenceData().getAliases();
} // end getAliases
public List getHosts() throws DataException
{
return getConferenceData().getHosts();
} // end getHosts
public boolean canReadConference(int level)
{
ConferenceData c = getConferenceDataNE();
if (c==null)
return false;
if (level<this.level)
return c.canReadConference(this.level);
else
return c.canReadConference(level);
} // end canReadConference
public boolean canPostToConference(int level)
{
ConferenceData c = getConferenceDataNE();
if (c==null)
return false;
if (level<this.level)
return c.canPostToConference(this.level);
else
return c.canPostToConference(level);
} // end canPostToConference
public boolean canCreateTopic(int level)
{
ConferenceData c = getConferenceDataNE();
if (c==null)
return false;
if (level<this.level)
return c.canCreateTopic(this.level);
else
return c.canCreateTopic(level);
} // end canCreateTopic
public boolean canChangeConference(int level)
{
ConferenceData c = getConferenceDataNE();
if (c==null)
return false;
if (level<this.level)
return c.canChangeConference(this.level);
else
return c.canChangeConference(level);
} // end canChangeConference
public int getReadLevel() throws DataException
{
return getConferenceData().getReadLevel();
} // end getReadLevel
public int getPostLevel() throws DataException
{
return getConferenceData().getPostLevel();
} // end getPostLevel
public int getCreateLevel() throws DataException
{
return getConferenceData().getCreateLevel();
} // end getCreateLevel
public int getHideLevel() throws DataException
{
return getConferenceData().getHideLevel();
} // end getHideLevel
public int getNukeLevel() throws DataException
{
return getConferenceData().getNukeLevel();
} // end getNukeLevel
public int getChangeLevel() throws DataException
{
return getConferenceData().getChangeLevel();
} // end getChangeLevel
public int getDeleteLevel() throws DataException
{
return getConferenceData().getDeleteLevel();
} // end getDeleteLevel
public synchronized void setSecurityLevels(SIGBackend sig, int read, int post, int create, int hide,
int nuke, int change, int delete) throws DataException
{
getConferenceData().setSecurityLevels(sig,read,post,create,hide,nuke,change,delete);
} // end setSecurityLevels
public synchronized void setName(SIGBackend sig, String val) throws DataException
{
getConferenceData().setName(sig,val);
} // end setName
public synchronized void setDescription(String val) throws DataException
{
getConferenceData().setDescription(val);
} // end setDescription
public synchronized void addAlias(SIGBackend sig, String alias) throws DataException
{
getConferenceData().addAlias(sig,alias);
} // end addAlias
public synchronized void removeAlias(SIGBackend sig, String alias) throws DataException
{
getConferenceData().removeAlias(sig,alias);
} // end removeAlias
public synchronized void setMembership(SIGBackend sig, int uid, int grant_level) throws DataException
{
getConferenceData().setMembership(sig,uid,grant_level);
} // end setMembership
public synchronized void setSIGGrantedLevel(SIGBackend sig, int new_level) throws DataException
{
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
try
{ // get a database connection
conn = datapool.getConnection();
// create the SQL statement
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE sigtoconf SET granted_lvl = ");
sql.append(new_level).append(" WHERE sigid = ").append(this.sig.realSIGID()).append(" AND confid = ");
sql.append(confid).append(';');
// execute the update
stmt.executeUpdate(sql.toString());
// save copies of the data in our local variables
level = new_level;
// create an audit record reflecting the change
ar = new AuditRecord(AuditRecord.CONF_SECURITY,sig.realUID(),sig.userRemoteAddress(),sig.realSIGID(),
"conf=" + String.valueOf(confid));
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference data: " + e.getMessage(),e);
throw new DataException("unable to save conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setSIGGrantedLevel
public short getSequence()
{
return sequence;
} // end getSequence
public synchronized void setSequence(short seq) throws DataException
{
Connection conn = null; // database connection
try
{ // get a database connection
conn = datapool.getConnection();
// create the SQL statement
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE sigtoconf SET sequence = ");
sql.append(seq).append(" WHERE sigid = ").append(this.sig.realSIGID()).append(" AND confid = ");
sql.append(confid).append(';');
// execute the update
stmt.executeUpdate(sql.toString());
// save copies of the data in our local variables
sequence = seq;
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference data: " + e.getMessage(),e);
throw new DataException("unable to save conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setSequence
public boolean getHideList()
{
return hide_list;
} // end getHideList
public void setHideList(SIGBackend sig, boolean flag) throws DataException
{
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
try
{ // get a database connection
conn = datapool.getConnection();
// create the SQL statement
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE sigtoconf SET hide_list = ");
sql.append(hide_list ? '1' : '0').append(" WHERE sigid = ").append(this.sig.realSIGID());
sql.append(" AND confid = ").append(confid).append(';');
// execute the update
stmt.executeUpdate(sql.toString());
// save copies of the data in our local variables
hide_list = flag;
// create an audit record reflecting the change
ar = new AuditRecord(AuditRecord.CONF_SECURITY,sig.realUID(),sig.userRemoteAddress(),sig.realSIGID(),
"conf=" + String.valueOf(confid));
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error storing conference data: " + e.getMessage(),e);
throw new DataException("unable to save conference data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setHideList
public boolean canHideTopics(int level)
{
ConferenceData c = getConferenceDataNE();
if (c==null)
return false;
if (level<this.level)
return c.canHideTopics(this.level);
else
return c.canHideTopics(level);
} // end canHideTopics
public String getAnAlias() throws DataException
{
return getConferenceData().getAnAlias();
} // end getAnAlias
} // end class ConferenceSIGContextImpl

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,694 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.*;
import java.util.*;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.db.*;
class ContactInfoImpl implements ContactInfo, Stashable
{
// Attributes
private int contactid; // ID of this contact record (-1 = new)
private String given_name; // given name ("first name")
private String family_name; // family name ("last name")
private char middle_initial; // middle initial (natch)
private String prefix; // prefix (Mr., Ms., Prof., Dr., etc.)
private String suffix; // suffix (Jr., III, etc.)
private String company; // company name
private String addr1; // address line 1
private String addr2; // address line 2
private String locality; // locality ("city")
private String region; // region ("state")
private String postal_code; // postal code ("ZIP code")
private String country; // 2-character ISO 3166 country code
private String phone; // voice phone number
private String fax; // facsimile (fax) number
private String mobile; // mobile phone (cellphone) number
private String email; // email address
private String photo_url; // URL of user photo
private String url; // URL of user's homepage
private boolean private_addr; // are addr1 and addr2 hidden?
private boolean private_phone; // are phone and mobile hidden?
private boolean private_fax; // is fax hidden?
private boolean private_email; // is email hidden?
private int owner_uid; // UID that owns this contact record
private int owner_sigid; // SIGID this contact record is in (-1 for none)
private java.util.Date last_update; // date of last update
private boolean is_modified = false; // have we modified this ContactInfo?
/**
* Constructs a new blank <CODE>ContactInfoImpl</CODE> object.
*
* @param owner_uid UID that owns this object.
*/
ContactInfoImpl(int owner_uid)
{
makeEmpty(owner_uid,-1);
} // end constructor
/**
* Constructs a new blank <CODE>ContactInfoImpl</CODE> object.
*
* @param owner_uid UID that owns this object.
* @param owner_sigid SIGID that owns this object.
*/
ContactInfoImpl(int owner_uid, int owner_sigid)
{
makeEmpty(owner_uid,owner_sigid);
} // end constructor
/**
* Loads a <CODE>ContactInfoImpl</CODE> object out of the database.
*
* @param dp Database connection pool to get a Venice database connection from.
* @param contactid ID of the contact to load.
* @exception DataException The contact could not be loaded for some reason.
*/
ContactInfoImpl(DataPool dp, int contactid) throws DataException
{
Connection conn = null;
try
{ // get a connection and call loadData
conn = dp.getConnection();
loadData(conn,contactid);
} // end try
catch (SQLException e)
{ // turn SQLExceptions at this level into DataExceptions
throw new DataException("Unable to look up contact info: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
dp.releaseConnection(conn);
} // end finally
} // end constructor
private void makeEmpty(int owner_uid, int owner_sigid)
{
this.contactid = -1;
this.given_name = null;
this.family_name = null;
this.middle_initial = ' ';
this.prefix = null;
this.suffix = null;
this.company = null;
this.addr1 = null;
this.addr2 = null;
this.locality = null;
this.region = null;
this.postal_code = null;
this.country = null;
this.phone = null;
this.fax = null;
this.mobile = null;
this.email = null;
this.photo_url = null;
this.url = null;
this.private_addr = false;
this.private_phone = false;
this.private_fax = false;
this.private_email = false;
this.owner_uid = owner_uid;
this.owner_sigid = owner_sigid;
this.last_update = null;
} // end makeEmpty
private void loadData(Connection conn, int contactid) throws DataException
{
try
{ // do a simple SELECT in contacts to look this up
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT * FROM contacts WHERE contactid = ");
sql.append(contactid).append(';');
ResultSet rs = stmt.executeQuery(sql.toString());
if (rs.next())
{ // do a mad orgy of saving off field values
this.contactid = rs.getInt("contactid");
given_name = rs.getString("given_name");
family_name = rs.getString("family_name");
String blort = rs.getString("middle_init");
if ((blort!=null) && (blort.length()>0))
middle_initial = blort.charAt(0);
else
middle_initial = ' ';
prefix = rs.getString("prefix");
suffix = rs.getString("suffix");
company = rs.getString("company");
addr1 = rs.getString("addr1");
addr2 = rs.getString("addr2");
locality = rs.getString("locality");
region = rs.getString("region");
postal_code = rs.getString("pcode");
country = rs.getString("country");
phone = rs.getString("phone");
fax = rs.getString("fax");
mobile = rs.getString("mobile");
email = rs.getString("email");
private_addr = rs.getBoolean("pvt_addr");
private_phone = rs.getBoolean("pvt_phone");
private_fax = rs.getBoolean("pvt_fax");
private_email = rs.getBoolean("pvt_email");
owner_uid = rs.getInt("owner_uid");
owner_sigid = rs.getInt("owner_sigid");
photo_url = rs.getString("photo_url");
url = rs.getString("url");
last_update = SQLUtil.getFullDateTime(rs,"lastupdate");
} // end if
else // contact was not found
throw new DataException("Contact was not found.");
} // end try
catch (SQLException e)
{ // map all SQLExceptions into DataExceptions
throw new DataException("Unable to look up contact info: " + e.getMessage(),e);
} // end catch
} // end loadData
public int getContactID()
{
return contactid;
} // end getContactID
public String getGivenName()
{
return given_name;
} // end getGivenName
public void setGivenName(String name)
{
if ((name!=null) && (name.length()>64))
given_name = name.substring(0,64);
else
given_name = name;
is_modified = true;
} // end setGivenName
public String getFamilyName()
{
return family_name;
} // end getFamilyName
public void setFamilyName(String name)
{
if ((name!=null) && (name.length()>64))
family_name = name.substring(0,64);
else
family_name = name;
is_modified = true;
} // end setFamilyName
public char getMiddleInitial()
{
return middle_initial;
} // end getMiddleInitial
public void setMiddleInitial(char in)
{
middle_initial = in;
is_modified = true;
} // end setMiddleInitial
public String getNamePrefix()
{
return prefix;
} // end getNamePrefix
public void setNamePrefix(String p)
{
if ((p!=null) && (p.length()>8))
prefix = p.substring(0,8);
else
prefix = p;
is_modified = true;
} // end setNamePrefix
public String getNameSuffix()
{
return suffix;
} // end getNameSuffix
public void setNameSuffix(String s)
{
if ((s!=null) && (s.length()>16))
suffix = s.substring(0,16);
else
suffix = s;
is_modified = true;
} // end setNameSuffix
public String getCompany()
{
return company;
} // end getCompany
public void setCompany(String c)
{
if ((c!=null) && (c.length()>255))
company = c.substring(0,255);
else
company = c;
is_modified = true;
} // end setCompany
public String getAddressLine1()
{
return addr1;
} // end getAddressLine1
public void setAddressLine1(String addr)
{
if ((addr!=null) && (addr.length()>255))
addr1 = addr.substring(0,255);
else
addr1 = addr;
is_modified = true;
} // end setAddressLine1
public String getAddressLine2()
{
return addr2;
} // end getAddressLine2
public void setAddressLine2(String addr)
{
if ((addr!=null) && (addr.length()>255))
addr2 = addr.substring(0,255);
else
addr2 = addr;
is_modified = true;
} // end setAddressLine2
public String getLocality()
{
return locality;
} // end getLocality
public void setLocality(String city)
{
if ((city!=null) && (city.length()>64))
locality = city.substring(0,64);
else
locality = city;
is_modified = true;
} // end setLocality
public String getRegion()
{
return region;
} // end getRegion
public void setRegion(String state)
{
if ((state!=null) && (state.length()>64))
region = state.substring(0,64);
else
region = state;
is_modified = true;
} // end setRegion
public String getPostalCode()
{
return postal_code;
} // end getPostalCode
public void setPostalCode(String zip)
{
if ((zip!=null) && (zip.length()>16))
postal_code = zip.substring(0,16);
else
postal_code = zip;
is_modified = true;
} // end setPostalCode
public String getCountry()
{
return country;
} // end getCountry
public void setCountry(String c)
{
if ((c!=null) && (c.length()>2))
country = c.substring(0,2);
else
country = c;
is_modified = true;
} // end setCountry
public String getPhone()
{
return phone;
} // end getPhone
public void setPhone(String num)
{
if ((num!=null) && (num.length()>32))
phone = num.substring(0,32);
else
phone = num;
is_modified = true;
} // end setPhone
public String getFax()
{
return fax;
} // end getFax
public void setFax(String num)
{
if ((num!=null) && (num.length()>32))
fax = num.substring(0,32);
else
fax = num;
is_modified = true;
} // end setFax
public String getMobile()
{
return mobile;
} // end getMobile
public void setMobile(String num)
{
if ((num!=null) && (num.length()>32))
mobile = num.substring(0,32);
else
mobile = num;
is_modified = true;
} // end setMobile
public String getEmail()
{
return email;
} // end getEmail
public void setEmail(String addr)
{
if ((addr!=null) && (addr.length()>255))
email = addr.substring(0,255);
else
email = addr;
is_modified = true;
} // end setEmail
public String getPhotoURL()
{
return photo_url;
} // end getPhotoURL
public void setPhotoURL(String addr)
{
if ((addr!=null) && (addr.length()>255))
photo_url = addr.substring(0,255);
else
photo_url = addr;
is_modified = true;
} // end setPhotoURL
public String getURL()
{
return url;
} // end getURL
public void setURL(String addr)
{
if ((addr!=null) && (addr.length()>255))
url = addr.substring(0,255);
else
url = addr;
is_modified = true;
} // end setURL
public boolean getPrivateAddress()
{
return private_addr;
} // end getPrivateAddress
public void setPrivateAddress(boolean flag)
{
private_addr = flag;
is_modified = true;
} // end setPrivateAddress
public boolean getPrivatePhone()
{
return private_phone;
} // end getPrivatePhone
public void setPrivatePhone(boolean flag)
{
private_phone = flag;
is_modified = true;
} // end setPrivatePhone
public boolean getPrivateFax()
{
return private_fax;
} // end getPrivateFax
public void setPrivateFax(boolean flag)
{
private_fax = flag;
is_modified = true;
} // end setPrivateFax
public boolean getPrivateEmail()
{
return private_email;
} // end getPrivateEmail
public void setPrivateEmail(boolean flag)
{
private_email = flag;
is_modified = true;
} // end setPrivateEmail
public int getOwnerUID()
{
return owner_uid;
} // end getOwnerUID
public int getOwnerSIGID()
{
return owner_sigid;
} // end getOwnerSIGID
public java.util.Date getLastUpdate()
{
return last_update;
} // end getLastUpdate
public boolean getModified()
{
return is_modified;
} // end getModified
public int getStashableUID()
{
return getOwnerUID();
} // end getStashableUID
public void stash(Connection conn) throws DataException, SQLException
{
java.util.Date update = null;
Statement stmt = conn.createStatement();
StringBuffer buf;
if (contactid>=0)
{ // this involves updating an existing record
buf = new StringBuffer("UPDATE contacts SET given_name = ");
buf.append(SQLUtil.encodeStringArg(given_name)).append(", family_name = ");
buf.append(SQLUtil.encodeStringArg(family_name)).append(", middle_init = ");
if (middle_initial==' ')
buf.append("NULL");
else
buf.append('\'').append(middle_initial).append('\'');
buf.append(", prefix = ").append(SQLUtil.encodeStringArg(prefix));
buf.append(", suffix = ").append(SQLUtil.encodeStringArg(suffix));
buf.append(", company = ").append(SQLUtil.encodeStringArg(company));
buf.append(", addr1 = ").append(SQLUtil.encodeStringArg(addr1));
buf.append(", addr2 = ").append(SQLUtil.encodeStringArg(addr2));
buf.append(", locality = ").append(SQLUtil.encodeStringArg(locality));
buf.append(", region = ").append(SQLUtil.encodeStringArg(region));
buf.append(", pcode = ").append(SQLUtil.encodeStringArg(postal_code));
buf.append(", country = ").append(SQLUtil.encodeStringArg(country));
buf.append(", phone = ").append(SQLUtil.encodeStringArg(phone));
buf.append(", fax = ").append(SQLUtil.encodeStringArg(fax));
buf.append(", mobile = ").append(SQLUtil.encodeStringArg(mobile));
buf.append(", email = ").append(SQLUtil.encodeStringArg(email));
buf.append(", pvt_addr = ").append(private_addr ? '1' : '0');
buf.append(", pvt_phone = ").append(private_phone ? '1' : '0');
buf.append(", pvt_fax = ").append(private_fax ? '1' : '0');
buf.append(", pvt_email = ").append(private_email ? '1' : '0');
buf.append(", photo_url = ").append(SQLUtil.encodeStringArg(photo_url));
buf.append(", url = ").append(SQLUtil.encodeStringArg(url)).append(", lastupdate = '");
update = new java.util.Date();
buf.append(SQLUtil.encodeDate(update)).append("' WHERE contactid = ").append(contactid).append(';');
stmt.executeUpdate(buf.toString());
} // end if
else
{ // this involves creating a new record
if (owner_sigid>=0)
stmt.executeUpdate("LOCK TABLES contacts WRITE, sigs WRITE;");
else
stmt.executeUpdate("LOCK TABLES contacts WRITE, users WRITE;");
try
{ // insert contact record data
buf = new StringBuffer("INSERT INTO contacts (given_name, family_name, middle_init, prefix, "
+ "suffix, company, addr1, addr2, locality, region, pcode, country, "
+ "phone, fax, mobile, email, pvt_addr, pvt_phone, pvt_fax, pvt_email, "
+ "owner_uid, owner_sigid, photo_url, url, lastupdate) VALUES (");
buf.append(SQLUtil.encodeStringArg(given_name)).append(", ");
buf.append(SQLUtil.encodeStringArg(family_name)).append(", ");
if (middle_initial==' ')
buf.append("NULL, ");
else
buf.append('\'').append(middle_initial).append("', ");
buf.append(SQLUtil.encodeStringArg(prefix)).append(", ");
buf.append(SQLUtil.encodeStringArg(suffix)).append(", ");
buf.append(SQLUtil.encodeStringArg(company)).append(", ");
buf.append(SQLUtil.encodeStringArg(addr1)).append(", ");
buf.append(SQLUtil.encodeStringArg(addr2)).append(", ");
buf.append(SQLUtil.encodeStringArg(locality)).append(", ");
buf.append(SQLUtil.encodeStringArg(region)).append(", ");
buf.append(SQLUtil.encodeStringArg(postal_code)).append(", ");
buf.append(SQLUtil.encodeStringArg(country)).append(", ");
buf.append(SQLUtil.encodeStringArg(phone)).append(", ");
buf.append(SQLUtil.encodeStringArg(fax)).append(", ");
buf.append(SQLUtil.encodeStringArg(mobile)).append(", ");
buf.append(SQLUtil.encodeStringArg(email)).append(", ");
buf.append(private_addr ? '1' : '0').append(", ");
buf.append(private_phone ? '1' : '0').append(", ");
buf.append(private_fax ? '1' : '0').append(", ");
buf.append(private_email ? '1' : '0').append(", ");
buf.append(owner_uid).append(", ").append(owner_sigid).append(", ");
buf.append(SQLUtil.encodeStringArg(photo_url)).append(", ");
buf.append(SQLUtil.encodeStringArg(url)).append(", '");
update = new java.util.Date();
buf.append(SQLUtil.encodeDate(update)).append("');");
stmt.executeUpdate(buf.toString());
// now read back the contact ID we just added
int new_contactid;
ResultSet rs = stmt.executeQuery("SELECT LAST_INSERT_ID() AS blort;");
if (rs.next())
new_contactid = rs.getInt("blort");
else
throw new DataException("unable to read back new contact ID");
// and patch the database table so we know what our contact ID is
buf.setLength(0);
if (owner_sigid>=0)
{ // update the SIGS table
buf.append("UPDATE sigs SET contactid = ").append(new_contactid).append(" WHERE sigid = ");
buf.append(owner_sigid).append(';');
} // end if
else
{ // update the USERS table
buf.append("UPDATE users SET contactid = ").append(new_contactid).append(" WHERE uid = ");
buf.append(owner_uid).append(';');
} // end else
stmt.executeUpdate(buf.toString());
contactid = new_contactid; // save link
} // end try
finally
{ // make sure the tables get unlocked
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
} // end else
last_update = update; // save last update date
is_modified = false;
} // end stash
} // end class ContactInfoImpl

View File

@ -0,0 +1,69 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.util.BitSet;
import java.util.List;
import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.htmlcheck.HTMLChecker;
import com.silverwrist.venice.core.DataException;
public interface EngineBackend
{
public static final int HTMLC_POST_BODY = 0;
public static final int HTMLC_POST_PSEUD = 1;
public static final int HTMLC_PREVIEW_BODY = 2;
public static final int HTMLC_ESCAPE_BODY_PSEUD = 3;
public abstract SimpleEmailer createEmailer();
public abstract String getStockMessage(String key);
public abstract int getNewConfirmationNumber();
public abstract String getCountryNameForCode(String code);
public abstract String getLanguageNameForCode(String code);
public abstract SIGData getSIGDataObject(int sigid) throws DataException;
public abstract BitSet getLockedFeaturesMask();
public abstract List getSIGFeatureSet(BitSet enabled_features, int level, boolean read_privs);
public abstract String getAppletForFeature(int code);
public abstract boolean isValidInitialFeatureIndex(short ndx);
public abstract BitSet getDefaultFeaturesMask();
public abstract void registerNewSIG(SIGData sig);
public abstract int getFeatureIndexBySymbol(String symbol);
public abstract boolean canAccessFeature(String symbol, int level, boolean has_read);
public abstract ConferenceData getConferenceDataObject(int confid) throws DataException;
public abstract void saveAuditRecord(AuditRecord ar);
public abstract void registerNewConference(ConferenceData conf);
public abstract HTMLChecker createCheckerObject(int type);
} // end interface EngineBackend

View File

@ -0,0 +1,273 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.*;
import java.util.*;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.db.*;
class FrontPageViewConfigImpl implements FrontPageViewConfig, Stashable
{
private int my_uid;
private int num_cols;
private Vector v_parts = new Vector();
private Vector v_params = new Vector();
private boolean is_modified = false;
FrontPageViewConfigImpl(Connection conn, int uid, int max_cols) throws DataException, SQLException
{
my_uid = uid;
num_cols = max_cols;
StringBuffer sql = new StringBuffer("SELECT row, col, partid, param FROM topconfig WHERE uid = ");
sql.append(uid).append(';');
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql.toString());
while (rs.next())
{ // make sure the column is in range first
int col = rs.getInt("col");
if ((col>=0) && (col<num_cols))
{ // get the row and find out how far down we have to go in the vector
int row = rs.getInt("row");
if (row>=0)
{ // now look for the right arrays to store into
String[] a_part = null;
String[] a_param = null;
if (row>=v_parts.size())
{ // need to extend the vector contents
while (row>=v_parts.size())
{ // append new arrays onto the config
a_part = new String[num_cols];
a_param = new String[num_cols];
for (int i=0; i<num_cols; i++)
{ // nuke the new arrays
a_part[i] = null;
a_param[i] = null;
} // end for
v_parts.addElement(a_part);
v_params.addElement(a_param);
} // end while
} // end if
else
{ // just fetch the existing arrays
a_part = (String[])(v_parts.elementAt(row));
a_param = (String[])(v_params.elementAt(row));
} // end else
// and now save off the recordset data
a_part[col] = rs.getString("partid");
a_param[col] = rs.getString("param");
} // end if
} // end if
} // end while
} // end constructor
public int getNumRows()
{
return v_parts.size();
} // end getNumRows
public int getNumColumns()
{
return num_cols;
} // end getNumCols
public String getPartID(int row, int column)
{
if ((row<0) || (row>=v_parts.size()))
throw new IndexOutOfBoundsException("invalid row specified to FrontPageViewConfig.getPartID");
if ((column<0) || (column>=num_cols))
throw new IndexOutOfBoundsException("invalid column specified to FrontPageViewConfig.getPartID");
String[] array = (String[])(v_parts.elementAt(row));
return array[column];
} // end getPartID
public void setPartID(int row, int column, String partid)
{
if (row<0)
throw new IndexOutOfBoundsException("invalid row specified to FrontPageViewConfig.setPartID");
if ((column<0) || (column>=num_cols))
throw new IndexOutOfBoundsException("invalid column specified to FrontPageViewConfig.setPartID");
String[] a_part = null;
String[] a_param = null;
if (row>=v_parts.size())
{ // need to extend the vector contents
while (row>=v_parts.size())
{ // append new arrays onto the config
a_part = new String[num_cols];
a_param = new String[num_cols];
for (int i=0; i<num_cols; i++)
{ // nuke the new arrays
a_part[i] = null;
a_param[i] = null;
} // end for
v_parts.addElement(a_part);
v_params.addElement(a_param);
} // end while
} // end if
else // just fetch the existing array
a_part = (String[])(v_parts.elementAt(row));
a_part[column] = partid;
is_modified = true;
} // end setPartID
public String getParameter(int row, int column)
{
if ((row<0) || (row>=v_params.size()))
throw new IndexOutOfBoundsException("invalid row specified to FrontPageViewConfig.getParameter");
if ((column<0) || (column>=num_cols))
throw new IndexOutOfBoundsException("invalid column specified to FrontPageViewConfig.getParameter");
String[] array = (String[])(v_params.elementAt(row));
return array[column];
} // end getParameter
public void setParameter(int row, int column, String param)
{
if (row<0)
throw new IndexOutOfBoundsException("invalid row specified to FrontPageViewConfig.setParameter");
if ((column<0) || (column>=num_cols))
throw new IndexOutOfBoundsException("invalid column specified to FrontPageViewConfig.setParameter");
String[] a_part = null;
String[] a_param = null;
if (row>=v_parts.size())
{ // need to extend the vector contents
while (row>=v_parts.size())
{ // append new arrays onto the config
a_part = new String[num_cols];
a_param = new String[num_cols];
for (int i=0; i<num_cols; i++)
{ // nuke the new arrays
a_part[i] = null;
a_param[i] = null;
} // end for
v_parts.addElement(a_part);
v_params.addElement(a_param);
} // end while
} // end if
else // just fetch the existing array
a_param = (String[])(v_params.elementAt(row));
a_param[column] = param;
is_modified = true;
} // end setParameter
public boolean getModified()
{
return is_modified;
} // end getModified
public int getStashableUID()
{
return my_uid;
} // end getStashableUID
public void stash(Connection conn) throws SQLException
{
StringBuffer buf = new StringBuffer();
for (int row=0; row<v_parts.size(); row++)
{ // retrieve the row arrays first
String[] a_part = (String[])(v_parts.elementAt(row));
String[] a_param = (String[])(v_params.elementAt(row));
for (int col=0; col<num_cols; col++)
{ // add to the list as long as the part isn't NULL
if (a_part[col]!=null)
{ // append this set of values to the INSERT we're going to make later
if (buf.length()==0)
buf.append("INSERT INTO topconfig (uid, row, col, partid, param) VALUES ");
else
buf.append(", ");
buf.append('(').append(my_uid).append(", ").append(row).append(", ").append(col).append(", ");
buf.append(SQLUtil.encodeStringArg(a_part[col])).append(", ");
buf.append(SQLUtil.encodeStringArg(a_param[col])).append(')');
} // end if
} // end for (each column)
} // end for (each row)
String insert_cmd = null;
if (buf.length()>0)
{ // we've got the insert command
buf.append(';');
insert_cmd = buf.toString();
buf.setLength(0);
} // end if
// now create the DELETE command
buf.append("DELETE FROM topconfig WHERE uid = ").append(my_uid).append(';');
// we need to lock the topconfig table while we do this
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES topconfig WRITE;");
try
{ // delete all existing records
stmt.executeUpdate(buf.toString());
// now insert the new records
if (insert_cmd!=null)
stmt.executeUpdate(insert_cmd);
} // end try
finally
{ // make sure to unlock the tables when we're done
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
} // end stash
} // end class FrontPageViewConfigImpl

View File

@ -0,0 +1,73 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.util.*;
class ReadOnlyVector extends AbstractList
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Vector my_vec; // local vector
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
ReadOnlyVector(Vector vec)
{
my_vec = vec;
my_vec.trimToSize();
} // end constructor
/*--------------------------------------------------------------------------------
* finalize() method
*--------------------------------------------------------------------------------
*/
protected void finalize() throws Throwable
{
my_vec = null;
super.finalize();
} // end finalize
/*--------------------------------------------------------------------------------
* Implementations from superclass AbstractList
*--------------------------------------------------------------------------------
*/
public Object get(int index)
{
return my_vec.elementAt(index);
} // end get
public int size()
{
return my_vec.size();
} // end size
} // end class ReadOnlyVector

View File

@ -0,0 +1,28 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
public interface ReferencedData
{
public abstract int rd_addRef();
public abstract int rd_release();
public abstract boolean rd_unreferenced();
} // end interface ReferencedData

View File

@ -0,0 +1,59 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
class ReturnConfSeq
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private ConferenceData conf;
private short sequence;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
ReturnConfSeq(ConferenceData conf, short sequence)
{
this.conf = conf;
this.sequence = sequence;
} // end constructor
/*--------------------------------------------------------------------------------
* External operations (usable only inside package)
*--------------------------------------------------------------------------------
*/
ConferenceData getConference()
{
return conf;
} // end getConference
short getSequence()
{
return sequence;
} // end getSequence
} // end class ReturnConfSeq

View File

@ -0,0 +1,36 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import com.silverwrist.venice.core.DataException;
public interface SIGBackend extends UserBackend
{
public abstract int realSIGID();
public abstract boolean userHideHiddenConferences();
public abstract int realSIGLevel();
public abstract ConferenceSIGContext getConferenceDataObject(int confid) throws DataException;
public abstract boolean userCanCreateSubobjects();
public abstract String realSIGAlias();
} // end interface SIGBackend

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,139 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.util.BitSet;
import java.util.Date;
import java.util.List;
import com.silverwrist.venice.core.AccessError;
import com.silverwrist.venice.core.ContactInfo;
import com.silverwrist.venice.core.DataException;
public interface SIGData extends ReferencedData
{
public abstract int getID();
public abstract String getName();
public abstract String getAlias();
public abstract boolean isPublicSIG();
public abstract int getCategoryID();
public abstract String getSynopsis();
public abstract int getHostUID();
public abstract String getLanguage();
public abstract String getRules();
public abstract int getContactID();
public abstract Date getCreationDate();
public abstract Date getLastAccessDate();
public abstract Date getLastUpdateDate();
public abstract void testMembership(int level, boolean is_member) throws AccessError;
public abstract boolean checkMembership(int level, boolean is_member);
public abstract boolean canReadSIGSubObjects(int level);
public abstract boolean canModifySIGProfile(int level);
public abstract boolean canCreateSIGSubObjects(int level);
public abstract boolean canDeleteSIG(int level);
public abstract boolean canJoinSIG(int uid, int level);
public abstract void putContactInfo(UserBackend user, ContactInfo ci) throws DataException;
public abstract BitSet getFeatureSet();
public abstract void putFeatureSet(UserBackend user, BitSet set) throws DataException;
public abstract List getSIGFeaturesList(int level);
public abstract String getDefaultApplet();
public abstract void setName(UserBackend user, String name) throws DataException;
public abstract void setAlias(UserBackend user, String alias) throws DataException;
public abstract void setCategoryID(UserBackend user, int catid) throws DataException;
public abstract void setSynopsis(String synopsis) throws DataException;
public abstract void setLanguage(String language) throws DataException;
public abstract void setRules(String rules) throws DataException;
public abstract void touch() throws DataException;
public abstract boolean getHideDirectory();
public abstract boolean getHideSearch();
public abstract void setHideFlags(UserBackend user, boolean directory, boolean search) throws DataException;
public abstract boolean getMembersOnly();
public abstract void setMembersOnly(UserBackend user, boolean flag) throws DataException;
public abstract short getInitialFeatureIndex();
public abstract void setInitialFeatureIndex(short ndx) throws DataException;
public abstract String getJoinKey() throws DataException;
public abstract void setJoinKey(UserBackend user, String key) throws DataException;
public abstract int getReadLevel();
public abstract int getWriteLevel();
public abstract int getCreateLevel();
public abstract int getDeleteLevel();
public abstract int getJoinLevel();
public abstract void setSecurityLevels(UserBackend user, int read, int write, int create, int delete,
int join) throws DataException;
public abstract boolean isAdminSIG();
public abstract void setMembership(UserBackend user, int uid, int grant_level, boolean locked,
boolean hidden) throws DataException;
public abstract int getMemberCount(boolean include_hidden) throws DataException;
public abstract boolean isFeaturePresent(String symbol);
public abstract ConferenceSIGContext getConferenceDataObject(int confid) throws DataException;
public abstract ConferenceSIGContext createConference(SIGBackend sig, String name, String alias,
String description, boolean pvt, boolean hide_list)
throws DataException;
} // end interface SIGData

View File

@ -0,0 +1,24 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
public interface SIGDataBackend
{
public abstract int realSIGID();
} // end interface SIGDataBackend

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,129 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import com.silverwrist.venice.core.EmailException;
import com.silverwrist.venice.core.InternalStateError;
class SimpleEmailer
{
private Session session; // the email session
private MimeMessage msg; // the message being composed
public SimpleEmailer(Properties props, javax.mail.Session session)
{
this.session = session;
msg = new MimeMessage(session);
try
{ // set the X-Mailer header
msg.setHeader("X-Mailer",(String)(props.get("com.silverwrist.venice.email.mailer")));
} // end try
catch (Exception e)
{ // do nothing - we don't really care about this too much
} // end catch
try
{ // set the From address on the message
msg.setFrom(InternetAddress.getLocalAddress(session));
} // end try
catch (MessagingException me)
{ // this should be impossible
throw new InternalStateError("condition should not apply to message here",me);
} // end catch
} // end constructor
public void setTo(String to) throws EmailException
{
try
{ // create an Internet address and set the recipient to it
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO,address);
} // end try
catch (AddressException e1)
{ // the address was somehow invalid
throw new EmailException("invalid email recipient address",e1);
} // end catch
catch (MessagingException e2)
{ // msg.setRecipients should NOT be throwing a MessageException here!
throw new InternalStateError("condition should not apply to message here",e2);
} // end catch
} // end setTo
public void setSubject(String subject)
{
try
{ // set the mail message subject
msg.setSubject(subject);
} // end try
catch (MessagingException e2)
{ // msg.setSubject should NOT be throwing a MessageException here!
throw new InternalStateError("condition should not apply to message here",e2);
} // end catch
} // end setSubject
public void setText(String text)
{
try
{ // set the mail message subject
msg.setText(text);
} // end try
catch (MessagingException e2)
{ // msg.setText should NOT be throwing a MessageException here!
throw new InternalStateError("condition should not apply to message here",e2);
} // end catch
} // end setText
public void send() throws EmailException
{
try
{ // attempt to send the transport message
Transport.send(msg);
} // end try
catch (SendFailedException e1)
{ // convert this exception into an EmailException
throw new EmailException("send of the email message failed: " + e1.getMessage(),e1);
} // end catch
catch (MessagingException e2)
{ // msg.setText should NOT be throwing a MessageException here!
throw new InternalStateError("condition should not apply to message here",e2);
} // end catch
} // end send
} // end class SimpleEmailer

View File

@ -0,0 +1,30 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.Connection;
import java.sql.SQLException;
import com.silverwrist.venice.core.DataException;
public interface Stashable
{
public abstract int getStashableUID();
public abstract void stash(Connection conn) throws DataException, SQLException;
} // end interface Stashable

View File

@ -0,0 +1,785 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.*;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.core.*;
class TopicUserContextImpl implements TopicContext
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(TopicUserContextImpl.class.getName());
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private EngineBackend engine;
private ConferenceBackend conf;
private DataPool datapool;
private int topicid;
private short topicnum;
private int creator_uid;
private int top_message;
private boolean frozen;
private boolean archived;
private java.util.Date created;
private java.util.Date lastupdate;
private String name;
private boolean hidden;
private int unread;
private boolean deleted = false;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
protected TopicUserContextImpl(EngineBackend engine, ConferenceBackend conf, DataPool datapool, int topicid,
short topicnum, int creator_uid, int top_message, boolean frozen,
boolean archived, java.util.Date created, java.util.Date lastupdate,
String name, boolean hidden, int unread)
{
this.engine = engine;
this.conf = conf;
this.datapool = datapool;
this.topicid = topicid;
this.topicnum = topicnum;
this.creator_uid = creator_uid;
this.top_message = top_message;
this.frozen = frozen;
this.archived = archived;
this.created = created;
this.lastupdate = lastupdate;
this.name = name;
this.hidden = hidden;
this.unread = unread;
} // end TopicUserContextImpl
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private static ResultSet queryByTopic(Statement stmt, int topicid, int uid) throws SQLException
{
StringBuffer sql =
new StringBuffer("SELECT t.topicid, t.num, t.creator_uid, t.top_message, t.frozen, t.archived, "
+ "t.createdate, t.lastupdate, t.name, IFNULL(s.hidden,0) AS hidden, "
+ "(t.top_message - IFNULL(s.last_message,-1)) AS unread FROM topics t "
+ "LEFT JOIN topicsettings s ON t.topicid = s.topicid AND s.uid = ");
sql.append(uid).append(" WHERE t.topicid = ").append(topicid).append(';');
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
return stmt.executeQuery(sql.toString());
} // end queryByTopic
private void makeDeleted()
{
top_message = -1;
frozen = false;
archived = false;
created = null;
lastupdate = null;
name = null;
hidden = false;
unread = -1;
deleted = true;
} // end if
/*--------------------------------------------------------------------------------
* Implementatuions from interface TopicContext
*--------------------------------------------------------------------------------
*/
public void refresh() throws DataException
{
if (logger.isDebugEnabled())
logger.debug("refreshing topic ID " + String.valueOf(topicid));
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// perform a requery of the database
ResultSet rs = queryByTopic(stmt,topicid,conf.realUID());
if (rs.next())
{ // update the fields that are capable of changing
top_message = rs.getInt(4);
frozen = rs.getBoolean(5);
archived = rs.getBoolean(6);
lastupdate = SQLUtil.getFullDateTime(rs,8);
hidden = rs.getBoolean(10);
unread = rs.getInt(11);
} // end if
else // this topic must have been deleted - fsck it
makeDeleted();
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error reading topic data: " + e.getMessage(),e);
throw new DataException("unable to retrieve topic information: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end refresh
public int getTopicID()
{
return topicid;
} // end getTopicID
public short getTopicNumber()
{
return topicnum;
} // end getTopicNumber
public String getName()
{
return name;
} // end getName
public int getUnreadMessages()
{
return unread;
} // end getUnreadMessages
public int getTotalMessages()
{
return top_message + 1;
} // end getTotalMessages
public java.util.Date getLastUpdateDate()
{
return lastupdate;
} // end getLastUpdateDate
public int getCreatorUID()
{
return creator_uid;
} // end getCreatorUID
public boolean isFrozen()
{
return frozen;
} // end isFrozen
public boolean isArchived()
{
return archived;
} // end isArchived
public java.util.Date getCreatedDate()
{
return created;
} // end getCreatedDate
public boolean isHidden()
{
return hidden;
} // end isHidden
public boolean isDeleted()
{
return deleted;
} // end isDeleted
public boolean canFreeze()
{
return conf.userCanHide();
} // end canFreeze
public boolean canArchive()
{
return conf.userCanHide();
} // end canArchive
public void setFrozen(boolean flag) throws DataException, AccessError
{
if ((frozen==flag) || deleted)
return; // no-op
if (!(conf.userCanHide()))
{ // you can't freeze the topic!
logger.error("user cannot change frozen status of topic");
throw new AccessError("You are not permitted to freeze or unfreeze this topic.");
} // end if
Connection conn = null; // pooled database connection
AuditRecord ar = null; // audit record indicating success
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// create the SQL statement to freeze or unfreeze the topic
StringBuffer sql = new StringBuffer("UPDATE topics SET frozen = ");
sql.append(flag ? '1' : '0').append(" WHERE topicid = ").append(topicid).append(';');
if (stmt.executeUpdate(sql.toString())>0)
{ // success! save the flag and generate an audit record
frozen = flag;
ar = new AuditRecord(AuditRecord.TOPIC_FREEZE,conf.realUID(),conf.userRemoteAddress(),
conf.realSIGID(),"conf=" + String.valueOf(conf.realConfID()) + ",topic="
+ String.valueOf(topicid),flag ? "freeze" : "unfreeze");
} // end if
else // somebody else must have deleted this topic
makeDeleted();
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error setting topic data: " + e.getMessage(),e);
throw new DataException("unable to set topic frozen status: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setFrozen
public void setArchived(boolean flag) throws DataException, AccessError
{
if ((archived==flag) || deleted)
return; // no-op
if (!(conf.userCanHide()))
{ // you can't archive the topic!
logger.error("user cannot change archived status of topic");
throw new AccessError("You are not permitted to archive or unarchive this topic.");
} // end if
Connection conn = null; // pooled database connection
AuditRecord ar = null; // audit record indicating success
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// create the SQL statement to freeze or unfreeze the topic
StringBuffer sql = new StringBuffer("UPDATE topics SET archived = ");
sql.append(flag ? '1' : '0').append(" WHERE topicid = ").append(topicid).append(';');
if (stmt.executeUpdate(sql.toString())>0)
{ // success! save the flag and generate an audit record
archived = flag;
ar = new AuditRecord(AuditRecord.TOPIC_ARCHIVE,conf.realUID(),conf.userRemoteAddress(),
conf.realSIGID(),"conf=" + String.valueOf(conf.realConfID()) + ",topic="
+ String.valueOf(topicid),flag ? "archive" : "unarchive");
} // end if
else // somebody else must have deleted this topic
makeDeleted();
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error setting topic data: " + e.getMessage(),e);
throw new DataException("unable to set topic archived status: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setArchived
public void setHidden(boolean flag) throws DataException
{
if ((hidden==flag) || deleted)
return; // no-op
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES topicsettings WRITE, topics READ;");
try
{ // start by trying to see if we can update topicsettings directly
StringBuffer sql = new StringBuffer("UPDATE topicsettings SET hidden = ");
sql.append(flag ? '1' : '0').append(" WHERE topicid = ").append(topicid).append(" AND uid = ");
sql.append(conf.realUID()).append(';');
if (stmt.executeUpdate(sql.toString())>0)
{ // that was all we needed - just save the flag and exit
hidden = flag;
return;
} // end if
// OK, check: Is the topic still there?!?
sql.setLength(0);
sql.append("SELECT topicid from topics WHERE topicid = ").append(topicid).append(';');
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
{ // the topic's been deleted - bail out
makeDeleted();
return;
} // end if
// OK, just insert a new row into topicsettings, why dontcha...
sql.setLength(0);
sql.append("INSERT INTO topicsettings (topicid, uid, hidden) VALUES (").append(topicid).append(", ");
sql.append(conf.realUID()).append(", ").append(flag ? '1' : '0').append(");");
stmt.executeUpdate(sql.toString());
hidden = flag; // successful completion
} // end try
finally
{ // unlock the tables before we go
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error setting topic data: " + e.getMessage(),e);
throw new DataException("unable to set topic hidden status: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setHidden
public int getFirstUnreadMessage()
{
if (unread==0)
return -1;
else
return top_message - (unread - 1);
} // end getFirstUnreadMessage
public void setUnreadMessages(int count) throws DataException
{
if (count>(top_message+1)) // constrain count to [0, top_message+1]
count = top_message + 1;
else if (count<0)
count = 0;
if ((count==unread) || deleted)
return; // no-op
int last_msg = top_message - count;
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES confsettings WRITE, topicsettings WRITE, topics READ;");
try
{ // start by trying to see if we can update topicsettings directly
StringBuffer sql = new StringBuffer("UPDATE topicsettings SET last_message = ");
sql.append(last_msg).append(" WHERE topicid = ").append(topicid).append(" AND uid = ");
sql.append(conf.realUID()).append(';');
if (stmt.executeUpdate(sql.toString())>0)
{ // that was all we needed - just save the flag and exit
conf.touchRead(conn);
unread = count;
return;
} // end if
// OK, check: Is the topic still there?!?
sql.setLength(0);
sql.append("SELECT topicid from topics WHERE topicid = ").append(topicid).append(';');
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
{ // the topic's been deleted - bail out
makeDeleted();
return;
} // end if
// OK, just insert a new row into topicsettings, why dontcha...
sql.setLength(0);
sql.append("INSERT INTO topicsettings (topicid, uid, last_message) VALUES (").append(topicid);
sql.append(", ").append(conf.realUID()).append(", ").append(last_msg).append(");");
stmt.executeUpdate(sql.toString());
conf.touchRead(conn);
unread = count; // successful completion
} // end try
finally
{ // unlock the tables before we go
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error setting topic data: " + e.getMessage(),e);
throw new DataException("unable to set topic hidden status: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setUnreadMessages
public void fixSeen() throws DataException
{
setUnreadMessages(0);
} // end fixSeen
/*--------------------------------------------------------------------------------
* External operations usable only from within the package
*--------------------------------------------------------------------------------
*/
static List getTopicList(EngineBackend engine, ConferenceBackend conf, DataPool datapool, int get_option,
int sort_option) throws DataException
{
if (logger.isDebugEnabled())
logger.debug("getTopicList for conf # " + String.valueOf(conf.realConfID()) + ", user #"
+ String.valueOf(conf.realUID()));
Vector rc = new Vector(); // return from this function
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// Figure out what the "where" clause of the SQL statement will be. This is in addition to a
// WHERE t.confid = (confid) that is always present. (Some of these WHERE specifiers refer to
// computed fields of the SELECT.)
String where_clause;
switch (get_option)
{
case ConferenceContext.GET_ALL:
where_clause = null; // no filtering options
break;
case ConferenceContext.DISPLAY_NEW:
where_clause = "hidden = 0 AND unread > 0"; // only non-hidden topics w/unread messages
break;
case ConferenceContext.DISPLAY_ACTIVE:
where_clause = "t.archived = 0 AND hidden = 0"; // only non-hidden, non-archived topics
break;
case ConferenceContext.DISPLAY_ALL:
where_clause = "t.archived = 0 AND hidden = 0"; // only non-hidden, non-archived topics
break;
case ConferenceContext.DISPLAY_HIDDEN:
where_clause = "hidden = 1"; // only hidden topics
break;
case ConferenceContext.DISPLAY_ARCHIVED:
where_clause = "t.archived = 1 AND hidden = 0"; // only non-hidden, archived topics
break;
default:
logger.error("ACK! get_option (" + String.valueOf(get_option) + ") is bogus!");
throw new DataException("Invalid retrieval option specified.");
} // end switch
// Figure out what the "order by" clause of the SQL statement will be. In the case of
// DISPLAY_NEW mode, this will be in addition to an ordering clause that puts all topics
// with unread messages first.
boolean reverse = false;
int real_sort_option = sort_option;
if (sort_option<0)
{ // did we specify a "reverse" option?
reverse = true;
real_sort_option = -sort_option;
} // end if
String order_by_clause;
switch (real_sort_option)
{
case ConferenceContext.SORT_TOPICID:
// no reverse possible here
order_by_clause = "t.topicid ASC";
break;
case ConferenceContext.SORT_NUMBER:
if (reverse)
order_by_clause = "t.num DESC";
else
order_by_clause = "t.num ASC";
break;
case ConferenceContext.SORT_NAME:
if (reverse)
order_by_clause = "t.name DESC, t.num DESC";
else
order_by_clause = "t.name ASC, t.num ASC";
break;
case ConferenceContext.SORT_UNREAD:
if (reverse)
order_by_clause = "unread ASC, t.num DESC";
else
order_by_clause = "unread DESC, t.num ASC";
break;
case ConferenceContext.SORT_TOTAL:
if (reverse)
order_by_clause = "t.top_message ASC, t.num DESC";
else
order_by_clause = "t.top_message DESC, t.num ASC";
break;
case ConferenceContext.SORT_DATE:
if (reverse)
order_by_clause = "t.lastupdate ASC, t.num DESC";
else
order_by_clause = "t.lastupdate DESC, t.num ASC";
break;
default:
logger.error("ACK! sort_option (" + String.valueOf(sort_option) + ") is bogus!");
throw new DataException("Invalid sort option specified.");
} // end switch
// Build the huge SQL statement to feed to the database.
StringBuffer sql =
new StringBuffer("SELECT t.topicid, t.num, t.creator_uid, t.top_message, t.frozen, t.archived, "
+ "t.createdate, t.lastupdate, t.name, IFNULL(s.hidden,0) AS hidden, "
+ "(t.top_message - IFNULL(s.last_message,-1)) AS unread");
if (get_option==ConferenceContext.DISPLAY_ACTIVE)
sql.append(", SIGN(t.top_message - IFNULL(s.last_message,-1)) AS newflag");
sql.append(" FROM topics t LEFT JOIN topicsettings s ON t.topicid = s.topicid AND s.uid = ");
sql.append(conf.realUID()).append(" WHERE t.confid = ").append(conf.realConfID());
if (where_clause!=null)
sql.append(" AND ").append(where_clause);
sql.append(" ORDER BY ");
if (get_option==ConferenceContext.DISPLAY_ACTIVE)
sql.append("newflag DESC, ");
sql.append(order_by_clause).append(';');
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
// Now pass this query off to the database!
ResultSet rs = stmt.executeQuery(sql.toString());
while (rs.next())
{ // create the returned objects and add them to the vector
TopicContext top =
new TopicUserContextImpl(engine,conf,datapool,rs.getInt(1),rs.getShort(2),rs.getInt(3),
rs.getInt(4),rs.getBoolean(5),rs.getBoolean(6),
SQLUtil.getFullDateTime(rs,7),SQLUtil.getFullDateTime(rs,8),
rs.getString(9),rs.getBoolean(10),rs.getInt(11));
rc.add(top);
} // end while
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error reading topic entries: " + e.getMessage(),e);
throw new DataException("unable to retrieve topic information: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
return new ReadOnlyVector(rc);
} // end getTopicList
static TopicContext getTopicByID(EngineBackend engine, ConferenceBackend conf, DataPool datapool,
int topicid) throws DataException
{
if (logger.isDebugEnabled())
logger.debug("getTopicByID for topic # " + String.valueOf(topicid) + ", user #"
+ String.valueOf(conf.realUID()));
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// Query the dtabase by topic ID.
ResultSet rs = queryByTopic(stmt,topicid,conf.realUID());
if (rs.next()) // found it!
return new TopicUserContextImpl(engine,conf,datapool,topicid,rs.getShort(2),rs.getInt(3),
rs.getInt(4),rs.getBoolean(5),rs.getBoolean(6),
SQLUtil.getFullDateTime(rs,7),SQLUtil.getFullDateTime(rs,8),
rs.getString(9),rs.getBoolean(10),rs.getInt(11));
// else fall out and return null
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error reading topic entries: " + e.getMessage(),e);
throw new DataException("unable to retrieve topic information: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
return null; // default return
} // end getTopicByID
static TopicContext getTopicByNumber(EngineBackend engine, ConferenceBackend conf, DataPool datapool,
short topicnum) throws DataException
{
if (logger.isDebugEnabled())
logger.debug("getTopicByNumber for topic # " + String.valueOf(topicnum) + ", conf # "
+ String.valueOf(conf.realConfID()) + ", user #" + String.valueOf(conf.realUID()));
Connection conn = null; // pooled database connection
try
{ // get a database connection
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// Build the database query.
StringBuffer sql =
new StringBuffer("SELECT t.topicid, t.num, t.creator_uid, t.top_message, t.frozen, t.archived, "
+ "t.createdate, t.lastupdate, t.name, IFNULL(s.hidden,0) AS hidden, "
+ "(t.top_message - IFNULL(s.last_message,-1)) AS unread FROM topics t "
+ "LEFT JOIN topicsettings s ON t.topicid = s.topicid AND s.uid = ");
sql.append(conf.realUID()).append(" WHERE t.confid = ").append(conf.realConfID());
sql.append(" AND t.num = ").append(topicnum).append(';');
if (logger.isDebugEnabled())
logger.debug("SQL: " + sql.toString());
// Now pass this query off to the database!
ResultSet rs = stmt.executeQuery(sql.toString());
if (rs.next()) // found it!
return new TopicUserContextImpl(engine,conf,datapool,rs.getInt(1),topicnum,rs.getInt(3),
rs.getInt(4),rs.getBoolean(5),rs.getBoolean(6),
SQLUtil.getFullDateTime(rs,7),SQLUtil.getFullDateTime(rs,8),
rs.getString(9),rs.getBoolean(10),rs.getInt(11));
// else fall out and return null
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error reading topic entries: " + e.getMessage(),e);
throw new DataException("unable to retrieve topic information: " + e.getMessage(),e);
} // end catch
finally
{ // make sure we release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
return null; // default return
} // end getTopicByNumber
} // end class TopicUserContextImpl

View File

@ -0,0 +1,32 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import com.silverwrist.venice.core.DataException;
public interface UserBackend
{
public abstract int realUID();
public abstract int realBaseLevel();
public abstract String userRemoteAddress();
public abstract String userDefaultPseud() throws DataException;
} // end interface UserBackend

View File

@ -0,0 +1,988 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.util.*;
import java.sql.*;
import org.apache.log4j.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.*;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.security.PasswordHash;
import com.silverwrist.venice.security.Capability;
import com.silverwrist.venice.security.DefaultLevels;
import com.silverwrist.venice.security.AuditRecord;
class UserContextImpl implements UserContext, UserBackend
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(UserContextImpl.class.getName());
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private EngineBackend engine; // the back end of the engine
private DataPool datapool; // the data pool used by this object
private String remote_addr; // remote address identifier
private int uid = -1; // the user ID we're using
private int contactid; // ID of our contact information
private int level; // base security level for this user
private int confirm_num; // email confirmation number for this user
private boolean is_anon = false; // is this the anonymous user?
private boolean email_verified = false; // has email address been verified?
private String username; // the user name we're using
private java.util.Date created; // when was this user created? (GMT)
private java.util.Date last_access; // when did we last log in? (GMT)
private String description; // personal description
private String my_email = null; // my email address (cached)
private String my_pseud = null; // my pseud (cached)
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
UserContextImpl(EngineBackend engine, DataPool datapool)
{
this.engine = engine;
this.datapool = datapool;
} // end constructor
/*--------------------------------------------------------------------------------
* finalize() method
*--------------------------------------------------------------------------------
*/
protected void finalize()
{
engine = null;
datapool = null;
username = null;
created = null;
last_access = null;
} // end finalize
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private void loadUserData(ResultSet rs) throws SQLException
{
uid = rs.getInt("uid");
username = rs.getString("username");
// skip field "passhash"
contactid = rs.getInt("contactid");
is_anon = rs.getBoolean("is_anon");
email_verified = rs.getBoolean("verify_email");
// skip fields "lockout", "access_tries"
confirm_num = rs.getInt("email_confnum");
level = rs.getInt("base_lvl");
created = SQLUtil.getFullDateTime(rs,"created");
last_access = SQLUtil.getFullDateTime(rs,"lastaccess");
// skip field "passreminder"
description = rs.getString("description");
if (logger.isDebugEnabled())
{ // spit it all out to debug info
logger.debug("Loaded: UID " + String.valueOf(uid) + ", username \"" + username + "\", contactid "
+ String.valueOf(contactid));
logger.debug("...is_anon " + String.valueOf(is_anon) + ", email_verified "
+ String.valueOf(email_verified));
logger.debug("... level " + String.valueOf(level));
} // end if
} // end loadUserData
private void sendEmailConfirmation() throws DataException, EmailException
{
if (logger.isDebugEnabled())
logger.debug("sendEmailConfirmation(): sending to \"" + my_email + "\"");
// Create the message to be sent.
String message = engine.getStockMessage("email-confirm");
if (message==null)
{ // no message defined? oy!
logger.error("internal error condition: email-confirm stock message not defined");
throw new DataException("INTERNAL: email-confirm message not defined");
} // end if
message = StringUtil.replaceAllInstances(message,"$USERNAME",username);
message = StringUtil.replaceAllInstances(message,"$CONFNUM",String.valueOf(confirm_num));
// Create the emailer and send the message.
SimpleEmailer emailer = engine.createEmailer();
emailer.setTo(my_email);
emailer.setSubject("Venice Email Confirmation");
emailer.setText(message);
emailer.send();
if (logger.isDebugEnabled())
logger.debug("...email sent!");
} // end sendEmailConfirmation
/*--------------------------------------------------------------------------------
* Implementations from interface UserContext
*--------------------------------------------------------------------------------
*/
public int getUID()
{
return uid;
} // end getUID
public String getUserName()
{
return username;
} // end getUserName
public int getContactID()
{
return contactid;
} // end getContactID
public String getDescription()
{
return description;
} // end getDescription
public boolean isLoggedIn()
{
if (logger.isDebugEnabled())
logger.debug("isLoggedIn(): uid = " + String.valueOf(uid) + ", is_anon = " + String.valueOf(is_anon));
return ((uid!=-1) && !is_anon);
} // end is_logged_in
public boolean isEmailVerified()
{
return email_verified;
} // end isEmailVerified
public void authenticate(String username, String password) throws AccessError, DataException
{
if (isLoggedIn())
{ // already authenticated, can't authenticate again
logger.error("UserContext already authenticated (with uid " + String.valueOf(uid) + ")");
throw new InternalStateError("context already authenticated");
} // end if
if (logger.isDebugEnabled())
logger.debug("authenticate(): authenticating user \"" + username + "\"...");
Connection conn = null;
AuditRecord ar = null;
try
{ // look for a user name matching this user record
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE username = '"
+ SQLUtil.encodeString(username) + "';");
if (!(rs.next()))
{ // user not found
logger.error("...user not found");
ar = new AuditRecord(AuditRecord.LOGIN_FAIL,0,remote_addr,"Bad username: " + username);
throw new AccessError("The user account you have specified does not exist. Please try again.");
} // end if
int the_uid = rs.getInt("uid");
if (rs.getBoolean("is_anon"))
{ // can't log in as Anonymous Honyak
logger.error("...user is the Anonymous Honyak, can't explicitly login");
ar = new AuditRecord(AuditRecord.LOGIN_FAIL,the_uid,remote_addr,"Anonymous user");
throw new AccessError("This account cannot be explicitly logged into. Please try again.");
} // end if
if (rs.getBoolean("lockout"))
{ // account locked out
logger.error("...user is locked out by the Admin");
ar = new AuditRecord(AuditRecord.LOGIN_FAIL,the_uid,remote_addr,"Account locked out");
throw new AccessError("This account has been administratively locked out. Please contact "
+ "the system administrator for assistance.");
} // end if
// hash the password and compare it to the stored password hash
PasswordHash phash = new PasswordHash(password);
if (!(phash.equals(rs.getString("passhash"))))
{ // they specified an incorrect password
// TODO: advance an "invalid" counter and lock the account out if more than X tries
logger.warn("...invalid password");
ar = new AuditRecord(AuditRecord.LOGIN_FAIL,the_uid,remote_addr,"Bad password");
throw new AccessError("The password you have specified is incorrect. Please try again.");
} // end if
if (logger.isDebugEnabled())
logger.debug("...authenticated");
// we're authenticated - load the user data into the context
loadUserData(rs);
// update the "last access" time in the database
java.util.Date mydate = new java.util.Date();
stmt.executeUpdate("UPDATE users SET lastaccess = '" + SQLUtil.encodeDate(mydate)
+ "' WHERE uid = " + uid + ";");
// update the "last access" time in this object
last_access = mydate;
// an audit record indicating we logged in OK
ar = new AuditRecord(AuditRecord.LOGIN_OK,the_uid,remote_addr);
if (logger.isDebugEnabled())
logger.debug("...context loaded, we're ready :-)");
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error reading user data: " + e.getMessage(),e);
throw new DataException("unable to access user data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end if
} // end authenticate
public void confirmEmail(int conf_num) throws AccessError, DataException
{
if (logger.isDebugEnabled())
logger.debug("confirmEmail(): confirming for UID " + String.valueOf(uid));
if ((email_verified) || Capability.exemptFromEmailVerification(level))
{ // already confirmed
if (logger.isDebugEnabled())
logger.debug("...user has either already confirmed or is exempt");
return;
} // end if
AuditRecord ar = null;
if (conf_num!=confirm_num)
{ // the confirmation number is wrong
logger.warn("...confirmation number incorrect");
ar = new AuditRecord(AuditRecord.VERIFY_FAIL,uid,remote_addr,"Invalid confirmation number");
engine.saveAuditRecord(ar);
throw new AccessError("Confirmation number is incorrect. Please try again.");
} // end if
Connection conn = null;
try
{ // get a connection and set the user's status to reflect the verification
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE users SET verify_email = 1, base_lvl = ");
sql.append(DefaultLevels.afterEmailVerification()).append(" WHERE uid = ").append(uid).append(';');
stmt.executeUpdate(sql.toString());
email_verified = true;
level = DefaultLevels.afterEmailVerification();
// record an audit message indicating that we verified OK
ar = new AuditRecord(AuditRecord.VERIFY_OK,uid,remote_addr);
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error updating user data: " + e.getMessage(),e);
throw new DataException("unable to update user data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end if
} // end confirmEmail
public void resendEmailConfirmation() throws DataException, EmailException
{
if (logger.isDebugEnabled())
logger.debug("resendEmailConfirmation(): resending for UID " + String.valueOf(uid));
if ((email_verified) || Capability.exemptFromEmailVerification(level))
{ // already confirmed, no need to resend
if (logger.isDebugEnabled())
logger.debug("...user has either already confirmed or is exempt");
return;
} // end if
if (my_email==null)
getContactInfo(); // forces my_email to be updated
Connection conn = null;
AuditRecord ar = null;
try
{ // need to change the user's email confirmation number first
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
// generate new confirmation number
int new_confirm_num = engine.getNewConfirmationNumber();
// create an SQL statement to reset the user account information, and execute it
StringBuffer sql = new StringBuffer("UPDATE users SET email_confnum = ");
sql.append(new_confirm_num).append(" WHERE uid = ").append(uid).append(';');
stmt.executeUpdate(sql.toString());
confirm_num = new_confirm_num; // save changed value
// now send the email confirmation!
sendEmailConfirmation();
// log that a resend was performed...
ar = new AuditRecord(AuditRecord.RESEND_CONFIRM,uid,remote_addr);
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error updating user data: " + e.getMessage(),e);
throw new DataException("unable to update user data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end if
} // end resendEmailConfirmation
public ContactInfo getContactInfo() throws DataException
{
ContactInfoImpl rc;
if (contactid>=0)
rc = new ContactInfoImpl(datapool,contactid);
else
rc = new ContactInfoImpl(uid);
if (my_email==null)
my_email = rc.getEmail();
if (my_pseud==null)
my_pseud = rc.getGivenName() + " " + rc.getFamilyName();
return rc;
} // end getContactInfo
public boolean putContactInfo(ContactInfo ci) throws DataException, EmailException
{
boolean email_changed = false;
if ((ci.getOwnerUID()!=uid) || (ci.getOwnerSIGID()>=0))
{ // the contact information is not owned correctly
logger.error("ContactInfo ownership wrong (it's " + String.valueOf(ci.getOwnerUID()) + ", "
+ String.valueOf(ci.getOwnerSIGID()) + "), should be (" + String.valueOf(uid) + ", -1)");
throw new DataException("invalid contact information record");
} // end if
if (is_anon)
{ // we can't change Anonymous Honyak this way!
logger.error("cannot modify anonymous user contact info");
throw new DataException("unmodifiable contact information");
} // end if
Connection conn = null; // database connection
AuditRecord ar = null; // audit record
try
{ // get a database connection
conn = datapool.getConnection();
Stashable obj = (Stashable)ci;
// save the contact information
obj.stash(conn);
if (contactid<0)
{ // contact being established for the first time
contactid = ci.getContactID();
if (logger.isDebugEnabled())
logger.debug("...established initial contact (" + String.valueOf(contactid) + ") for user");
my_email = ci.getEmail();
sendEmailConfirmation();
email_changed = true;
} // end if
my_pseud = ci.getGivenName() + " " + ci.getFamilyName(); // update this field
if (my_email==null) // filling in, this is not necessarily the first time
my_email = ci.getEmail();
else if (!(my_email.equals(ci.getEmail())) && !Capability.exemptFromEmailVerification(level))
{ // email address change - need to reconfirm - but choose a new confirmation
// number and save it in the database first; also turn off the verify flag
// and set the base level to GLOBAL_UNVERIFIED
// NOTE: Administrators are exempt from this requirement!
if (logger.isDebugEnabled())
logger.debug("email address changed, need to reconfirm");
// generate new confirmation number
int new_confirm_num = engine.getNewConfirmationNumber();
// create an SQL statement to reset the user account information, and execute it
StringBuffer sql = new StringBuffer("UPDATE users SET verify_email = 0, email_confnum = ");
sql.append(new_confirm_num).append(", base_lvl = ").append(DefaultLevels.afterEmailAddressChange());
sql.append(" WHERE uid = ").append(uid).append(';');
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql.toString());
// save off changed data
email_verified = false;
confirm_num = new_confirm_num;
level = DefaultLevels.afterEmailAddressChange();
// now send the email confirmation!
sendEmailConfirmation();
email_changed = true;
} // end else if
ar = new AuditRecord(AuditRecord.USER_CONTACT_INFO,uid,remote_addr,
"contactid=" + String.valueOf(contactid));
} // end try
catch (ClassCastException cce)
{ // we need to be able to coerce the ContactInfo to a Stashable
logger.error("ContactInfo needs to be a Stashable for this to work");
throw new DataException("improper contact information record");
} // end catch
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error updating contact info: " + e.getMessage(),e);
throw new DataException("unable to access user contact data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end if
return email_changed;
} // end putContactInfo
public UserProfile getProfile(String xusername) throws DataException
{
if (logger.isDebugEnabled())
logger.debug("getProfile(\"" + xusername + "\")...");
Connection conn = null;
try
{ // retrieve a connection from the data pool
conn = datapool.getConnection();
UserProfileImpl prof = new UserProfileImpl(engine,conn,xusername,
Capability.canSeeHiddenContactFields(level));
if (logger.isDebugEnabled())
logger.debug("...found it!");
return prof;
} // end catch
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error looking up profile information: " + e.getMessage(),e);
throw new DataException("Unable to look up user info: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end getProfile
public UserProfile getProfile(int xuid) throws DataException
{
if (logger.isDebugEnabled())
logger.debug("getProfile(#" + String.valueOf(xuid) + ")...");
Connection conn = null;
try
{ // retrieve a connection from the data pool
conn = datapool.getConnection();
UserProfileImpl prof = new UserProfileImpl(engine,conn,xuid,Capability.canSeeHiddenContactFields(level));
if (logger.isDebugEnabled())
logger.debug("...found it!");
return prof;
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error looking up profile information: " + e.getMessage(),e);
throw new DataException("Unable to look up user info: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end getProfile
public void setPassword(String password, String reminder) throws DataException
{
if (is_anon)
{ // trying to change Anonymous Honyak's (nonexistent) password?
logger.error("cannot change password of anonymous account");
throw new DataException("The anonymous account cannot change its password.");
} // end if
Connection conn = null;
AuditRecord ar = null;
try
{ // retrieve a connection from the data pool
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
PasswordHash phash = new PasswordHash(password);
StringBuffer sql = new StringBuffer("UPDATE users SET passhash = '");
sql.append(phash.toString()).append("', passreminder = '").append(SQLUtil.encodeString(reminder));
sql.append("' WHERE uid = ").append(uid).append(';');
stmt.executeUpdate(sql.toString());
// record an audit record for this user
ar = new AuditRecord(AuditRecord.PASSWORD_CHANGE,uid,remote_addr);
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error changing password: " + e.getMessage(),e);
throw new DataException("Unable to set user password: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
try
{ // save off the audit record before we go, though
if ((ar!=null) && (conn!=null))
ar.store(conn);
} // end try
catch (SQLException e)
{ // we couldn't store the audit record!
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setPassword
public void setDescription(String new_descr) throws DataException
{
if (is_anon)
{ // trying to change Anonymous Honyak's (nonexistent) description?
logger.error("cannot change description of anonymous account");
throw new DataException("The anonymous account cannot change its description.");
} // end if
Connection conn = null;
try
{ // retrieve a connection from the data pool
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("UPDATE users SET description = '");
sql.append(SQLUtil.encodeString(new_descr)).append("' WHERE uid = ").append(uid).append(';');
stmt.executeUpdate(sql.toString());
description = new_descr; // change stored information
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error changing description: " + e.getMessage(),e);
throw new DataException("Unable to set user description: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end setDescription
public FrontPageViewConfig getFrontPageViewConfig(int max_cols) throws DataException
{
Connection conn = null;
try
{ // retrieve a connection from the data pool
conn = datapool.getConnection();
// create new object
return new FrontPageViewConfigImpl(conn,uid,max_cols);
} // end try
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error getting front page view config: " + e.getMessage(),e);
throw new DataException("unable to retrieve front page view config: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end getFrontPageViewConfig
public void putFrontPageViewConfig(FrontPageViewConfig cfg) throws DataException
{
Connection conn = null;
try
{ // coerce the value to a Stashable first
Stashable obj = (Stashable)cfg;
if (obj.getStashableUID()!=uid)
{ // wrong UID for configuration - this is bogus
logger.error("invalid ownership of FrontPageViewConfig (was "
+ String.valueOf(obj.getStashableUID()) + ", should be " + String.valueOf(uid) + ")");
throw new DataException("invalid front page view config record");
} // end if
// retrieve a connection from the data pool
conn = datapool.getConnection();
// stash the object
obj.stash(conn);
} // end try
catch (ClassCastException cce)
{ // we need to be able to coerce the FrontPageViewConfig to a Stashable
logger.error("FrontPageViewConfig was not a Stashable");
throw new DataException("improper front page view config record");
} // end catch
catch (SQLException e)
{ // turn SQLException into data exception
logger.error("DB error saving front page view config: " + e.getMessage(),e);
throw new DataException("unable to save front page view config: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end putFrontPageViewConfig
public List getMemberSIGs() throws DataException
{
return SIGUserContextImpl.getMemberSIGEntries(engine,this,datapool);
} // end getMemberSIGs
public SIGContext getSIGContext(int sigid) throws DataException
{
return SIGUserContextImpl.getSIGContext(engine,this,datapool,sigid);
} // end getSIGContext
public SIGContext getSIGContext(String alias) throws DataException
{
return SIGUserContextImpl.getSIGContext(engine,this,datapool,alias);
} // end getSIGContext
public List getRootCategoryList() throws DataException
{
return CategoryDescriptorImpl.getTopLevelCategoryList(datapool,Capability.hideHiddenCategories(level));
} // end getRootCategoryList
public CategoryDescriptor getCategoryDescriptor(int catid) throws DataException
{
return new CategoryDescriptorImpl(datapool,catid,Capability.hideHiddenCategories(level));
} // end getCategoryDescriptor
public List searchForSIGs(int field, int mode, String term, int offset, int count) throws DataException
{
return SIGUserContextImpl.searchForSIGs(engine,this,datapool,field,mode,term,offset,count);
} // end searchForSIGs
public int getSearchSIGCount(int field, int mode, String term) throws DataException
{
return SIGUserContextImpl.getSearchSIGCount(this,datapool,field,mode,term);
} // end getSearchSIGCount
public List getSIGsInCategory(int catid, int offset, int count) throws DataException
{
return SIGUserContextImpl.getSIGsInCategory(engine,this,datapool,catid,offset,count);
} // end getSIGsInCategory
public List getSIGsInCategory(CategoryDescriptor cat, int offset, int count) throws DataException
{
return SIGUserContextImpl.getSIGsInCategory(engine,this,datapool,cat.getLinkedCategoryID(),offset,count);
} // end getSIGsInCategory
public int getNumSIGsInCategory(int catid) throws DataException
{
return SIGUserContextImpl.getNumSIGsInCategory(this,datapool,catid);
} // end getNumSIGsInCategory
public int getNumSIGsInCategory(CategoryDescriptor cat) throws DataException
{
return SIGUserContextImpl.getNumSIGsInCategory(this,datapool,cat.getLinkedCategoryID());
} // end getNumSIGsInCategory
public List searchForCategories(int mode, String term, int offset, int count) throws DataException
{
return CategoryDescriptorImpl.searchForCategories(datapool,Capability.hideHiddenCategories(level),
Capability.showHiddenSearchCategories(level),mode,
term,offset,count);
} // end searchForCategories
public int getSearchCategoryCount(int mode, String term) throws DataException
{
return CategoryDescriptorImpl.getSearchCategoryCount(datapool,Capability.hideHiddenCategories(level),
Capability.showHiddenSearchCategories(level),
mode,term);
} // end getSearchCategoryCount
public SIGContext createSIG(String name, String alias, String language, String synopsis, String rules,
String joinkey, int hide_mode) throws DataException, AccessError
{
if (!(Capability.canCreateSIG(level)))
throw new AccessError("You are not authorized to create new SIGs.");
// Convert the "hide mode" value int othe two hide flags.
boolean hide_dir = (hide_mode!=SIGContext.HIDE_NONE);
boolean hide_search = (hide_mode==SIGContext.HIDE_BOTH);
// Create the new SIG's database entries and internal data.
SIGData new_sig = SIGCoreData.createSIG(engine,this,datapool,name,alias,uid,language,synopsis,rules,
joinkey,hide_dir,hide_search);
// Create the SIG context we return to the user.
SIGContext rc = new SIGUserContextImpl(engine,this,datapool,new_sig);
new_sig.rd_release(); // release the extra reference we have on SIGData
// And that's it! You expected lightning bolts maybe? :-)
return rc;
} // end createSIG
public boolean canCreateSIG()
{
return Capability.canCreateSIG(level);
} // end canCreateSIG
/*--------------------------------------------------------------------------------
* Implementations from interface UserBackend
*--------------------------------------------------------------------------------
*/
public int realUID()
{
return uid;
} // end realUID
public int realBaseLevel()
{
return level;
} // end realBaseLevel
public String userRemoteAddress()
{
return remote_addr;
} // end userRemoteAddress
public String userDefaultPseud() throws DataException
{
if (my_pseud==null)
getContactInfo();
return my_pseud;
} // end userDefaultPseud
/*--------------------------------------------------------------------------------
* Operations private to implementation package
*--------------------------------------------------------------------------------
*/
void loadAnonymous(String remote_addr) throws DataException
{
Connection conn = null;
if (logger.isDebugEnabled())
logger.debug("loadAnonymous() on UserContext: addr " + remote_addr);
try
{ // retrieve a connection from the data pool
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE is_anon = 1;");
if (!(rs.next()))
{ // could not find the anonymous user - this is an internal error
logger.error("WTF? anonymous user not found?!?");
throw new DataException("INTERNAL ERROR - cannot find anonymous user");
} // end if
loadUserData(rs); // load the data for Anonymous Honyak
this.remote_addr = remote_addr;
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("error loading anonymous user data: " + e.getMessage(),e);
throw new DataException("unable to access user data: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end loadAnonymous
void loadNewUser(String remote_addr, int uid, int level, String username, int confirm_num,
java.util.Date created, java.util.Date last_access)
{
if (logger.isDebugEnabled())
logger.debug("loadNewUser() on UserContext: addr " + remote_addr + ", uid " + String.valueOf(uid)
+ ", level " + String.valueOf(level) + ", username \"" + username + "\"");
this.remote_addr = remote_addr;
this.uid = uid;
this.contactid = -1;
this.level = level;
this.username = username;
this.confirm_num = confirm_num;
this.created = created;
this.last_access = last_access;
} // end loadNewUser
} // end class UserContextImpl

View File

@ -0,0 +1,132 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import com.silverwrist.venice.core.*;
class UserFoundImpl implements UserFound
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private int uid;
private String name;
private String description;
private String given_name;
private String family_name;
private String locality;
private String region;
private String country;
private int level = -1;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
UserFoundImpl(int uid, String name, String description, String given_name, String family_name,
String locality, String region, String country)
{
this.uid = uid;
this.name = name;
this.description = description;
this.given_name = given_name;
this.family_name = family_name;
this.locality = locality;
this.region = region;
this.country = country;
} // end constructor
UserFoundImpl(int uid, String name, String description, String given_name, String family_name,
String locality, String region, String country, int level)
{
this.uid = uid;
this.name = name;
this.description = description;
this.given_name = given_name;
this.family_name = family_name;
this.locality = locality;
this.region = region;
this.country = country;
this.level = level;
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface UserFound
*--------------------------------------------------------------------------------
*/
public int getUID()
{
return uid;
} // end getUID
public String getName()
{
return name;
} // end getName
public String getDescription()
{
return description;
} // end getDescription
public String getGivenName()
{
return given_name;
} // end getGivenName
public String getFamilyName()
{
return family_name;
} // end getFamilyName
public String getLocality()
{
return locality;
} // end getLocality
public String getRegion()
{
return region;
} // end getRegion
public String getCountry()
{
return country;
} // end getCountry
public int getLevel()
{
return level;
} // end getLevel
} // end class UserFoundImpl

View File

@ -0,0 +1,347 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.core.impl;
import java.sql.*;
import java.util.*;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.db.*;
class UserProfileImpl implements UserProfile
{
private EngineBackend engine; // the engine back end
private int uid; // user ID
private String username; // user name
private String given_name; // given name ("first name")
private String family_name; // family name ("last name")
private char middle_initial; // middle initial (natch)
private String prefix; // prefix (Mr., Ms., Prof., Dr., etc.)
private String suffix; // suffix (Jr., III, etc.)
private String company; // company name
private String addr1; // address line 1
private String addr2; // address line 2
private String locality; // locality ("city")
private String region; // region ("state")
private String postal_code; // postal code ("ZIP code")
private String country; // 2-character ISO 3166 country code
private String phone; // voice phone number
private String fax; // facsimile (fax) number
private String mobile; // mobile phone (cellphone) number
private String email; // email address
private String photo_url; // URL of user photo
private String url; // URL of user's homepage
private String descr; // user's self-description
private java.util.Date created; // date created
private java.util.Date last_login; // date of last login
private java.util.Date last_update; // date of last update
private String real_email; // real email address
UserProfileImpl(EngineBackend engine, Connection conn, String username, boolean override)
throws DataException, SQLException
{
this.engine = engine;
// first retrieve from the users table
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT uid, username, contactid, created, lastaccess, description "
+ "FROM users WHERE username = '");
sql.append(SQLUtil.encodeString(username)).append("';");
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new DataException("User '" + username + "' not found.");
// load the "elementary" fields
this.uid = rs.getInt("uid");
this.username = rs.getString("username");
int contact_id = rs.getInt("contactid");
created = SQLUtil.getFullDateTime(rs,"created");
last_login = SQLUtil.getFullDateTime(rs,"lastaccess");
descr = rs.getString("description");
loadContact(conn,contact_id,override);
} // end constructor
UserProfileImpl(EngineBackend engine, Connection conn, int uid, boolean override)
throws DataException, SQLException
{
this.engine = engine;
// first retrieve from the users table
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT uid, username, contactid, created, lastaccess, description "
+ "FROM users WHERE uid = ");
sql.append(uid).append(';');
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new DataException("User #" + String.valueOf(uid) + " not found.");
// load the "elementary" fields
this.uid = rs.getInt("uid");
this.username = rs.getString("username");
int contact_id = rs.getInt("contactid");
created = SQLUtil.getFullDateTime(rs,"created");
last_login = SQLUtil.getFullDateTime(rs,"lastaccess");
descr = rs.getString("description");
loadContact(conn,contact_id,override);
} // end constructor
private void loadContact(Connection conn, int contact_id, boolean override) throws SQLException
{
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT * FROM contacts WHERE contactid = ");
sql.append(contact_id).append(';');
ResultSet rs = stmt.executeQuery(sql.toString());
if (rs.next())
{ // load all the record data
given_name = rs.getString("given_name");
family_name = rs.getString("family_name");
String blort = rs.getString("middle_init");
if ((blort==null) || (blort.length()<1))
middle_initial = ' ';
else
middle_initial = blort.charAt(0);
prefix = rs.getString("prefix");
suffix = rs.getString("suffix");
company = rs.getString("company");
if (!override && rs.getBoolean("pvt_addr"))
{ // enforce address privacy
addr1 = null;
addr2 = null;
} // end if
else
{ // load the address strings
addr1 = rs.getString("addr1");
addr2 = rs.getString("addr2");
} // end else
locality = rs.getString("locality");
region = rs.getString("region");
postal_code = rs.getString("pcode");
country = rs.getString("country");
if (!override && rs.getBoolean("pvt_phone"))
{ // enforce phone privacy
phone = null;
mobile = null;
} // end if
else
{ // load the phone strings
phone = rs.getString("phone");
mobile = rs.getString("mobile");
} // end else
if (!override && rs.getBoolean("pvt_fax"))
fax = null;
else
fax = rs.getString("fax");
real_email = rs.getString("email");
if (!override && rs.getBoolean("pvt_email"))
email = null;
else
email = real_email;
photo_url = rs.getString("photo_url");
url = rs.getString("url");
last_update = SQLUtil.getFullDateTime(rs,"lastupdate");
} // end if
else
{ // no contact ID - just default all the data
given_name = null;
family_name = null;
middle_initial = ' ';
prefix = null;
suffix = null;
company = null;
addr1 = null;
addr2 = null;
locality = null;
region = null;
postal_code = null;
country = null;
phone = null;
fax = null;
mobile = null;
email = null;
photo_url = null;
url = null;
last_update = null;
real_email = null;
} // end else
} // end loadContact
public int getUID()
{
return uid;
} // end getUID
public String getUserName()
{
return username;
} // end getUserName
public String getGivenName()
{
return given_name;
} // end getGivenName
public String getFamilyName()
{
return family_name;
} // end getFamilyName
public char getMiddleInitial()
{
return middle_initial;
} // end getMiddleInitial
public String getNamePrefix()
{
return prefix;
} // end getNamePrefix
public String getNameSuffix()
{
return suffix;
} // end getNameSuffix
public String getCompany()
{
return company;
} // end getCompany
public String getAddressLine1()
{
return addr1;
} // end getAddressLine1
public String getAddressLine2()
{
return addr2;
} // end getAddressLine2
public String getLocality()
{
return locality;
} // end getLocality
public String getRegion()
{
return region;
} // end getRegion
public String getPostalCode()
{
return postal_code;
} // end getPostalCode
public String getCountry()
{
return country;
} // end getCountry
public String getFullCountry()
{
return engine.getCountryNameForCode(country);
} // end getFullCountry
public String getPhone()
{
return phone;
} // end getPhone
public String getFax()
{
return fax;
} // end getFax
public String getMobile()
{
return mobile;
} // end getMobile
public String getEmail()
{
return email;
} // end getEmail
public String getPhotoURL()
{
return photo_url;
} // end getPhotoURL
public String getURL()
{
return url;
} // end getURL
public java.util.Date getCreateDate()
{
return created;
} // end getCreateDate
public java.util.Date getLastLoginDate()
{
return last_login;
} // end getLastLoginDate
public java.util.Date getLastUpdate()
{
return last_update;
} // end getLastUpdate
public String getDescription()
{
return descr;
} // end getDescription
} // end class UserProfileImpl

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,421 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.db;
import java.util.*;
import java.sql.*;
import org.apache.log4j.*;
import org.w3c.dom.*;
import com.silverwrist.util.DOMElementHelper;
import com.silverwrist.venice.core.ConfigException;
public class DataPool implements Runnable
{
/*--------------------------------------------------------------------------------
* Static data values
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(DataPool.class.getName());
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String driver; // name of JDBC driver class
private String url; // URL for JDBC connection
private String username; // username for JDBC connection
private String password; // password for JDBC connection
private int max_conns; // maximum number of possible connections
private boolean wait_if_busy; // do we wait for a connection if none is available?
private boolean pending = false; // pending connection being created?
private Vector avail_connections; // connections which are available for use
private Vector busy_connections; // connections which are currently in use
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public DataPool(Element cfg) throws ConfigException, SQLException
{
// Make sure they passed the <database/> section to us.
if (!(cfg.getTagName().equals("database")))
{ // not the right section name
logger.fatal("configuration section is not <database/>");
throw new ConfigException("improper configuration section",cfg);
} // end if
// Use a DOMElementHelper to read off the configuration for the DataPool.
DOMElementHelper cfgx = new DOMElementHelper(cfg);
driver = cfgx.getSubElementText("driver");
if (driver==null)
{ // no driver found!
logger.fatal("no <driver/> name inside <database/> section");
throw new ConfigException("no <driver/> name specified",cfg);
} // end if
if (logger.isDebugEnabled())
logger.debug("DataPool driver: " + driver);
url = cfgx.getSubElementText("uri");
if (url==null)
{ // no database URI found!
logger.fatal("no <uri/> name inside <database/> section");
throw new ConfigException("no database <uri/> specified",cfg);
} // end if
if (logger.isDebugEnabled())
logger.debug("DataPool URI: " + url);
username = cfgx.getSubElementText("username");
if (username==null)
{ // no database username found
logger.fatal("no <username/> inside <database/> section");
throw new ConfigException("no database <username/> specified",cfg);
} // end if
if (logger.isDebugEnabled())
logger.debug("DataPool username: " + url);
password = cfgx.getSubElementText("password");
if (password==null)
{ // no database password found
logger.fatal("no user <password/> inside <database/> section");
throw new ConfigException("no database <password/> specified",cfg);
} // end if
int initial_conns = 0;
try
{ // retrieve the initial-conns figure and make it an integer
String tmp = cfgx.getSubElementText("initial-conns");
if (tmp==null)
{ // the connections value was not specified
logger.fatal("database <initial-conns/> value not specified");
throw new ConfigException("no <initial-conns/> value specified",cfg);
} // end if
initial_conns = Integer.parseInt(tmp);
if (initial_conns<0)
{ // the connections value was out of range
logger.fatal("database <initial-conns/> value was out of range");
throw new ConfigException("<initial-conns/> value out of range",cfg);
} // end if
} // end try
catch (NumberFormatException e)
{ // the value wasn't a valid integer
logger.fatal("database <initial-conns/> value was not a number");
throw new ConfigException("<initial-conns/> value is not a number",e,cfg);
} // end catch
if (logger.isDebugEnabled())
logger.debug("DataPool initial connections: " + String.valueOf(initial_conns));
try
{ // retrieve the max-conns figure and make it an integer
String tmp = cfgx.getSubElementText("max-conns");
if (tmp==null)
{ // maximum connections value not specified
logger.fatal("database <max-conns/> value not specified");
throw new ConfigException("no <max-conns/> value specified",cfg);
} // end if
max_conns = Integer.parseInt(tmp);
if (max_conns<=0)
{ // value must be greater than 0!
logger.fatal("database <max-conns/> value was out of range");
throw new ConfigException("<max-conns/> value out of range",cfg);
} // end if
} // end try
catch (NumberFormatException e)
{ // the value wasn't a valid integer
logger.fatal("database <max-conns/> value was not a number");
throw new ConfigException("<max-conns/> value is not a number",e,cfg);
} // end catch
if (logger.isDebugEnabled())
logger.debug("DataPool maximum connections: " + String.valueOf(max_conns));
wait_if_busy = cfgx.hasChildElement("wait-if-busy");
if (logger.isDebugEnabled())
logger.debug("DataPool wait if busy: " + String.valueOf(wait_if_busy));
if (initial_conns>max_conns)
{ // fix initial value if above maximum
if (logger.isDebugEnabled())
logger.debug("N.B.: reducing configured initial connections");
initial_conns = max_conns;
} // end if
// Create the vectors that hold connections.
avail_connections = new Vector(initial_conns);
busy_connections = new Vector();
// Populate the "available connection" vector.
for (int i=0; i<initial_conns; i++)
avail_connections.addElement(makeNewConnection());
logger.info("DataPool initialized");
} // end constructor
/*--------------------------------------------------------------------------------
* finalize() function
*--------------------------------------------------------------------------------
*/
protected void finalize()
{
closeConnections(avail_connections);
avail_connections = null;
closeConnections(busy_connections);
busy_connections = null;
driver = null;
url = null;
username = null;
password = null;
} // end finalize
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private Connection makeNewConnection() throws SQLException
{
try
{ // make the connection and return it
Class.forName(driver).newInstance(); // preload driver class
// the newInstance() call above is to work around some broken Java implementations
return DriverManager.getConnection(url,username,password);
} // end try
catch (ClassNotFoundException e)
{ // convert a ClassNotFoundException to a nicer SQLException
logger.error("JDBC driver class \"" + driver + "\" not found",e);
throw new SQLException("Can't find class for driver: " + driver);
} // end catch
catch (IllegalAccessException e2)
{ // convert this to a nicer SQLException
logger.fatal("Can't access \"" + driver + "\" constructor: " + e2.getMessage(),e2);
throw new SQLException("Can't access class for driver: " + driver);
} // end catch
catch (InstantiationException e3)
{ // convert this to a nicer SQLException
logger.fatal("Can't create instance of \"" + driver + "\": " + e3.getMessage(),e3);
throw new SQLException("Can't create class for driver: " + driver);
} // end catch
} // end makeNewConnection
private void makeBackgroundConnection()
{
pending = true;
try
{ // spin off the connection attempt to the background
Thread thrd = new Thread(this);
thrd.start();
} // end try
catch (OutOfMemoryError e)
{ // give up on new connection
logger.warn("memory failure spinning off background-connect thread");
pending = false;
} // end catch
} // end makeBackgroundConnection
private void closeConnections(Vector vconn)
{
if (logger.isDebugEnabled())
logger.debug("closeConnections(" + String.valueOf(vconn.size()) + " to be closed)");
for (int i=0; i<vconn.size(); i++)
{ // loop over the entire vector
try
{ // take each connection and close it
Connection c = (Connection)(vconn.get(i));
if (!(c.isClosed()))
c.close();
} // end try
catch (SQLException e)
{ // what do we care, this connection is dying anyhow
logger.warn("got a SQLException in closeConnections (ignored): " + e.getMessage());
} // end catch
} // end for
} // end closeConnections
/*--------------------------------------------------------------------------------
* Implementations from interface Runnable
*--------------------------------------------------------------------------------
*/
public void run()
{
try
{ // attempt to create another connection in the background
Connection c = makeNewConnection();
synchronized (this)
{ // we've got a new available connection - let everyone know
if (logger.isDebugEnabled())
logger.debug("created new connection in the background");
avail_connections.addElement(c);
pending = false;
notifyAll();
} // end synchronized block
} // end try
catch (Exception e)
{ // caught an SQLException or an OutOfMemory exception
logger.warn("background connection thread caught " + e.getClass().getName() + ": " + e.getMessage());
// ditch this new connection and wait until an existing one frees up
} // end catch
} // end run
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public synchronized int numConnections()
{
int rc = avail_connections.size() + busy_connections.size();
if (logger.isDebugEnabled())
logger.debug("numConnections() => " + String.valueOf(rc));
return rc;
} // end numConnections
public synchronized Connection getConnection() throws SQLException
{
for (;;)
{ // loop until we get a connection or throw an exception
if (avail_connections.isEmpty())
{ // no connections available - we may need to make a new one
if (logger.isDebugEnabled())
logger.debug("no connections available - looking to get one");
if ((numConnections() < max_conns) && !pending)
makeBackgroundConnection(); // try to create a new connection
else if (!wait_if_busy)
{ // don't want to wait? tough, we're h0sed!
logger.error("exhausted maximum connection limit (" + String.valueOf(max_conns) + ")");
throw new SQLException("connection limit reached");
} // end else if
// Wait for the background connect attempt to finish, or for
// someone to return a connection.
try
{ // park the thread here until we know what's up
wait();
} // end try
catch (InterruptedException e)
{ // do nothing
} // end catch
// now fall through the loop and try again
} // end if
else
{ // pull the last connection off the available list...
int ndx = avail_connections.size() - 1;
Connection rc = (Connection)(avail_connections.elementAt(ndx));
avail_connections.removeElementAt(ndx);
if (rc.isClosed())
{ // this connection is closed - discard it, and notify any waiters that a slot
// has opened up
if (logger.isDebugEnabled())
logger.debug("discarding closed connection");
notifyAll();
rc = null;
// fall out to the end of the loop and try again
} // end if
else
{ // this connection is OK - return it
busy_connections.addElement(rc);
return rc;
} // end else
} // end else (at least one connection available)
} // end for (ever)
} // end getConnection
public synchronized void releaseConnection(Connection c)
{
busy_connections.removeElement(c); // move from one vector to another
avail_connections.addElement(c);
notifyAll(); // wake up! Got a new connection for you!
} // end releaseConnection
public synchronized void closeAllConnections()
{
if (logger.isDebugEnabled())
logger.debug("closing ALL connections!");
closeConnections(avail_connections);
avail_connections = new Vector();
closeConnections(busy_connections);
busy_connections = new Vector();
} // end closeAllConnections
public synchronized String toString()
{
StringBuffer info = new StringBuffer();
info.append("DataPool(\"").append(url).append("\",\"").append(username).append("\"), ");
info.append(avail_connections.size()).append(" avail, ").append(busy_connections.size());
info.append(" busy, ").append(max_conns).append(" max");
return info.toString();
} // end toString
} // end class DataPool

View File

@ -0,0 +1,371 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.db;
import java.sql.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.ValidationException;
import com.silverwrist.venice.core.IDUtils;
public class PostLinkDecoder
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final int MAX_LINK_LEN = 130;
private static final int MAX_SIG_LEN = 32;
private static final int MAX_CONF_LEN = 64;
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String signame = null;
private String confname = null;
private short topicnum = -1;
private int first_post = -1;
private int last_post = -1;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public PostLinkDecoder(String data) throws ValidationException
{
if (StringUtil.isStringEmpty(data))
throw new ValidationException("empty string");
if (data.length()>MAX_LINK_LEN)
throw new ValidationException("post link string too long");
// turn the data into a StringBuffer so we can parse it
StringBuffer work = new StringBuffer(data);
// First Test: Bang
int pos = work.toString().indexOf('!');
if (pos>0)
{ // We have "sig!something" ... store off the SIG name
setSIGName(work.substring(0,pos));
work.delete(0,pos+1);
if (work.length()==0)
return; // we had just "sig!" - that's the syntax for a SIG link
} // end if
else if (pos==0)
throw new ValidationException("! at beginning of string");
// Second Test: Dot Number One
pos = work.toString().indexOf('.');
if (pos<0)
{ // there's no dots in here...this must have been either "postlink" or "sig!conference"
if (signame!=null) // it's "sig!conference"
setConferenceName(work.toString());
else // it's "postlink"
setPostRange(work);
return;
} // end if
else if (pos==0)
throw new ValidationException(". at beginning of string");
// Peel off the initial substring.
String conf_or_topic = work.substring(0,pos);
work.delete(0,pos+1);
if (work.length()==0)
{ // we had "conference." or "topic." (or perhaps "sig!conference.")
if (signame==null)
{ // it's either "conference." or "topic." - try topic first
try
{ // try it as a topic number first...
setTopicNumber(conf_or_topic);
} // end try
catch (ValidationException ve)
{ // it's not a topic number - try it as a conference name!
setConferenceName(conf_or_topic);
} // end catch
} // end if
else // it was "sig!conference."...save it off
setConferenceName(conf_or_topic);
return; // all done here...
} // end if
// Third Test: Dot Number Two
pos = work.toString().indexOf('.');
if (pos<0)
{ // we had "conference.topic" or "topic.posts" (or perhaps "sig!conference.topic")
if (signame==null)
{ // we have "conference.topic" or "topic.posts" - have to determine this
boolean is_topic = false; // what does "work" currently hold?
try
{ // try the "topic.posts" possibility first...
setTopicNumber(conf_or_topic);
} // end try
catch (ValidationException ve)
{ // nope, it's gotta be "conference.topic"
setConferenceName(conf_or_topic);
is_topic = true;
} // end if
// complete the parsing here
if (is_topic)
setTopicNumber(work.toString());
else
setPostRange(work);
} // end if
else
{ // it's "sig!conference.topic"...set 'em up accordingly
setConferenceName(conf_or_topic);
setTopicNumber(work.toString());
} // end else
return; // all done
} // end if
else if (pos==0)
throw new ValidationException(". at beginning of string");
// We definitely have "conference.topic.something" (or "sig!conference.topic.sonething") now,
// so save off the conference name and topic number.
setConferenceName(conf_or_topic);
setTopicNumber(work.substring(0,pos));
work.delete(0,pos+1);
if (work.length()==0)
return; // we just had "conference.topic." or "sig!conference.topic.", which is valid
setPostRange(work); // the rest must be the post range!
} // end constructor
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private static boolean isAllDigits(String str)
{
for (int i=0; i<str.length(); i++)
{ // if any character is not a digit, bail out!
if (!(Character.isDigit(str.charAt(i))))
return false;
} // end for
return true;
} // end isAllDigits
private void setSIGName(String name) throws ValidationException
{
if (name.length()>MAX_SIG_LEN)
throw new ValidationException("SIG alias is too long");
if (!(IDUtils.isValidVeniceID(name)))
throw new ValidationException("SIG alias is not a valid Venice identifier");
signame = name;
} // end setSIGName
private void setConferenceName(String name) throws ValidationException
{
if (name.length()>MAX_CONF_LEN)
throw new ValidationException("conference alias is too long");
if (!(IDUtils.isValidVeniceID(name)))
throw new ValidationException("conference alias is not a valid Venice identifier");
confname = name;
} // end setConferenceName
private void setTopicNumber(String val) throws ValidationException
{
if (!isAllDigits(val))
throw new ValidationException("invalid topic number reference");
short temp_val;
try
{ // parse the temp value
temp_val = Short.parseShort(val);
} // end try
catch (NumberFormatException nfe)
{ // if there's a validation exception, it goes here
throw new ValidationException("invalid topic number reference");
} // end catch
topicnum = temp_val;
} // end setTopicNumber
private void setPostRange(StringBuffer buf) throws ValidationException
{
int pos = buf.toString().indexOf('-');
String temp = null;
int temp_val = -1;
if (pos>0)
{ // we've got "temp-something" here...make sure "temp" is a valid post number
temp = buf.substring(0,pos);
buf.delete(0,pos+1);
if (!isAllDigits(temp))
throw new ValidationException("invalid post number reference");
try
{ // parse the temp value
temp_val = Integer.parseInt(temp);
} // end try
catch (NumberFormatException nfe)
{ // if there's a validation exception, it goes here
throw new ValidationException("invalid post number reference");
} // end catch
if (buf.length()==0)
{ // we just had "first-"...set it up
first_post = temp_val;
last_post = -1;
return;
} // end if
} // end if
else if (pos==0)
throw new ValidationException("- at beginning of post range");
// the remaining string must be all digits at this point
if (!isAllDigits(buf.toString()))
throw new ValidationException("invalid post number reference");
try
{ // parse the first value
first_post = Integer.parseInt(buf.toString());
} // end try
catch (NumberFormatException nfe)
{ // if there's a validation exception, it goes here
throw new ValidationException("invalid post number reference");
} // end catch
if (temp!=null)
{ // we converted a "temp_val" above - include it
if (temp_val<first_post)
{ // put the "temp_val" up front
last_post = first_post;
first_post = temp_val;
} // end if
else // reverse order - arrange them correctly
last_post = temp_val;
} // end if
else // we have a "range" of one post
last_post = first_post;
} // end setPostRange
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String getSIG()
{
return signame;
} // end getSIG
public String getConference()
{
return confname;
} // end getConference
public short getTopic()
{
return topicnum;
} // end getTopic
public int getFirstPost()
{
return first_post;
} // end getFirstPost
public int getLastPost()
{
return last_post;
} // end getFirstPost
public boolean needDatabaseVerification()
{
return ((signame!=null) || (confname!=null));
} // end needDatabaseVerification
public void verifyNames(Connection conn) throws ValidationException
{
try
{ // do the necessary database stuff
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer();
ResultSet rs;
if (signame!=null)
{ // verify the SIG name against the database
sql.append("SELECT sigid FROM sigs WHERE alias = '").append(SQLUtil.encodeString(signame));
sql.append("';");
rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new ValidationException("SIG alias not found");
sql.setLength(0);
} // end if
if (confname!=null)
{ // verify the conference name against the database
sql.append("SELECT confid FROM confalias WHERE alias = '").append(SQLUtil.encodeString(confname));
sql.append("';");
rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
throw new ValidationException("conference alias not found");
} // end if
} // end try
catch (SQLException e)
{ // database error verifying stuff!
throw new ValidationException("unable to verify names in post link");
} // end catch
} // end verifyNames
} // end class PostLinkDecoder

View File

@ -0,0 +1,67 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.db;
public class PostLinkDecoderContext
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String signame; // SIG name that's cached
private String confname; // conference name that's cached
private short topic; // topic that's cached
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public PostLinkDecoderContext(String signame, String confname, short topic)
{
this.signame = signame;
this.confname = confname;
this.topic = topic;
} // end PostLinkDecoderContext
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String getSIGName()
{
return signame;
} // end getSIGName
public String getConferenceName()
{
return confname;
} // end getConferenceName
public short getTopicNumber()
{
return topic;
} // end getTopicNumber
} // end class PostLinkDecoderContext

View File

@ -0,0 +1,188 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.db;
import java.sql.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.ValidationException;
import com.silverwrist.venice.htmlcheck.Rewriter;
import com.silverwrist.venice.htmlcheck.RewriterServices;
import com.silverwrist.venice.htmlcheck.MarkupData;
import com.silverwrist.venice.core.IDUtils;
public class PostLinkRewriter implements Rewriter
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DataPool datapool;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public PostLinkRewriter(DataPool datapool)
{
this.datapool = datapool;
} // end constructor
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private static String buildPostLink(PostLinkDecoder pl, PostLinkDecoderContext ctxt)
{
StringBuffer b = new StringBuffer("x-postlink:");
boolean started = false;
if (pl.getSIG()==null)
b.append(ctxt.getSIGName());
else
{ // append the real SIG name
started = true;
b.append(pl.getSIG());
} // end else
b.append('!');
if (pl.getConference()==null)
{ // need to default the context
if (started)
return b.toString();
b.append(ctxt.getConferenceName());
} // end if
else
{ // append the proper conference name
started = true;
b.append(pl.getConference());
} // end else
b.append('.');
if (pl.getTopic()==-1)
{ // need to default the topic number
if (started)
return b.toString();
b.append(ctxt.getTopicNumber());
} // end if
else
{ // append the proper topic number
started = true;
b.append(pl.getTopic());
} // end else
// append the post link information, if applicable
b.append('.');
if (pl.getFirstPost()==-1)
return b.toString();
b.append(pl.getFirstPost());
if (pl.getFirstPost()==pl.getLastPost())
return b.toString();
b.append('-');
if (pl.getLastPost()==-1)
return b.toString();
b.append(pl.getLastPost());
return b.toString();
} // end buildPostLink
/*--------------------------------------------------------------------------------
* Implementations from interface Rewriter
*--------------------------------------------------------------------------------
*/
public String getName()
{
return null;
} // end getName
public MarkupData rewrite(String data, RewriterServices svc)
{
PostLinkDecoderContext ctxt;
try
{ // attempt to get the decoder context
ctxt = (PostLinkDecoderContext)(svc.getRewriterContextValue("PostLinkDecoderContext"));
if (ctxt==null)
return null; // decoder can't function
} // end try
catch (ClassCastException x)
{ // decoder can't function without the context
return null;
} // end catch
PostLinkDecoder pl;
try
{ // create the post link decoder
pl = new PostLinkDecoder(data);
if (pl.needDatabaseVerification())
{ // open up a database connection and verify the SIG/conference names
Connection conn = null;
try
{ // verify against the database
conn = datapool.getConnection();
pl.verifyNames(conn);
} // end try
catch (SQLException e)
{ // just return null on failures
return null;
} // end catch
finally
{ // release the connection when we're done
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
} // end if
} // end try
catch (ValidationException ve)
{ // we can't validate the post link - just bail out
return null;
} // end catch
// build the necessary markup and return it
StringBuffer open_a = new StringBuffer("<A HREF=\"");
open_a.append(buildPostLink(pl,ctxt)).append("\"");
String catenate = svc.getRewriterAttrValue("ANCHORTAIL");
if (!(StringUtil.isStringEmpty(catenate)))
open_a.append(' ').append(catenate);
open_a.append('>');
return new MarkupData(open_a.toString(),data,"</A>");
} // end rewrite
} // end class PostLinkRewriter

View File

@ -0,0 +1,176 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.db;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.StringUtil;
public class SQLUtil
{
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private static java.util.Date convertDateTimeString(String dstr) throws SQLException
{
if (dstr==null)
return null; // null values are the same
try
{ // do almost the reverse process of formatting it into a string
GregorianCalendar cal = new GregorianCalendar(new SimpleTimeZone(0,"UTC"));
cal.set(Calendar.YEAR,Integer.parseInt(dstr.substring(0,4)));
cal.set(Calendar.MONTH,Integer.parseInt(dstr.substring(5,7)) - 1 + Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH,Integer.parseInt(dstr.substring(8,10)));
cal.set(Calendar.HOUR_OF_DAY,Integer.parseInt(dstr.substring(11,13)));
cal.set(Calendar.MINUTE,Integer.parseInt(dstr.substring(14,16)));
cal.set(Calendar.SECOND,Integer.parseInt(dstr.substring(17,19)));
return cal.getTime();
} // end try
catch (NumberFormatException e)
{ // the NumberFormatException becomes an SQLException
throw new SQLException("invalid DATETIME field format");
} // end catch
} // end convertDateString
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static String encodeString(String str)
{
return StringUtil.encodeStringSQL(str);
} // end encodeString
public static String encodeStringArg(String str)
{
if (str==null)
return "NULL";
StringBuffer b = new StringBuffer("'");
b.append(StringUtil.encodeStringSQL(str)).append('\'');
return b.toString();
} // end encodeStringArg
public static String encodeStringWildcards(String str)
{
if ((str.indexOf('_')<0) && (str.indexOf('%')<0))
return StringUtil.encodeStringSQL(str);
StringBuffer buf = new StringBuffer();
for (int i=0; i<str.length(); i++)
{ // loop through the string encoding its characters
char c = str.charAt(i);
switch (c)
{
case '\'':
buf.append("\'\'");
break;
case '_':
buf.append("\\_");
break;
case '%':
buf.append("\\%");
break;
default:
buf.append(c);
break;
} // end switch
} // end for
return buf.toString();
} // end encodeStringWildcards
public static String encodeDate(java.util.Date d)
{
// Break down the date as a UTC value.
GregorianCalendar cal = new GregorianCalendar(new SimpleTimeZone(0,"UTC"));
cal.setTime(d);
// Create the two string buffers converting the date.
StringBuffer rc = new StringBuffer();
StringBuffer conv = new StringBuffer();
String c;
// Encode the year first.
conv.append("0000").append(cal.get(Calendar.YEAR));
c = conv.toString();
rc.append(c.substring(c.length()-4)).append('-');
// Now the month...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.MONTH) - Calendar.JANUARY + 1);
c = conv.toString();
rc.append(c.substring(c.length()-2)).append('-');
// And the day...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.DAY_OF_MONTH));
c = conv.toString();
rc.append(c.substring(c.length()-2)).append(' ');
// And the hour...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.HOUR_OF_DAY));
c = conv.toString();
rc.append(c.substring(c.length()-2)).append(':');
// And the minute...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.MINUTE));
c = conv.toString();
rc.append(c.substring(c.length()-2)).append(':');
// And the second...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.SECOND));
c = conv.toString();
rc.append(c.substring(c.length()-2));
// This is the resulting date/time value.
return rc.toString();
} // end encodeDate
public static java.util.Date getFullDateTime(ResultSet rs, String column) throws SQLException
{
return convertDateTimeString(rs.getString(column));
} // end getFullDateTime
public static java.util.Date getFullDateTime(ResultSet rs, int column) throws SQLException
{
return convertDateTimeString(rs.getString(column));
} // end getFullDateTime
} // end class SQLUtil

View File

@ -0,0 +1,98 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.db;
import java.sql.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.htmlcheck.Rewriter;
import com.silverwrist.venice.htmlcheck.RewriterServices;
import com.silverwrist.venice.htmlcheck.MarkupData;
import com.silverwrist.venice.core.IDUtils;
public class UserNameRewriter implements Rewriter
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DataPool datapool;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public UserNameRewriter(DataPool datapool)
{
this.datapool = datapool;
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface Rewriter
*--------------------------------------------------------------------------------
*/
public String getName()
{
return null;
} // end getName
public MarkupData rewrite(String data, RewriterServices svc)
{
if (StringUtil.isStringEmpty(data) || (data.length()>64) || !(IDUtils.isValidVeniceID(data)))
return null;
Connection conn = null;
try
{ // get a database connection and create a statement
conn = datapool.getConnection();
Statement stmt = conn.createStatement();
StringBuffer sql = new StringBuffer("SELECT uid FROM users WHERE username = '");
sql.append(SQLUtil.encodeString(data)).append("';");
ResultSet rs = stmt.executeQuery(sql.toString());
if (!(rs.next()))
return null; // not found
} // end try
catch (SQLException e)
{ // if we hit a database error, just return null...
return null;
} // end catch
finally
{ // make sure and release the connection before we go
if (conn!=null)
datapool.releaseConnection(conn);
} // end finally
StringBuffer open_a = new StringBuffer("<A HREF=\"x-userlink:");
open_a.append(data).append("\"");
String catenate = svc.getRewriterAttrValue("ANCHORTAIL");
if (!(StringUtil.isStringEmpty(catenate)))
open_a.append(' ').append(catenate);
open_a.append('>');
return new MarkupData(open_a.toString(),data,"</A>");
} // end rewrite
} // end class UserNameRewriter

View File

@ -0,0 +1,28 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public class AlreadyFinishedException extends HTMLCheckerException
{
public AlreadyFinishedException()
{
super("The HTML Checker is already in a finished state.");
} // end constructor
} // end AlreadyFinishedException

View File

@ -0,0 +1,40 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public interface HTMLChecker
{
public abstract void append(String str) throws AlreadyFinishedException;
public abstract void finish() throws AlreadyFinishedException;
public abstract void reset();
public abstract String getValue() throws NotYetFinishedException;
public abstract int getLength() throws NotYetFinishedException;
public abstract int getLines() throws NotYetFinishedException;
public abstract int getCounter(String name) throws NotYetFinishedException;
public abstract Object getContextValue(String name);
public abstract void setContextValue(String name, Object val);
} // end interface HTMLChecker

View File

@ -0,0 +1,66 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public interface HTMLCheckerConfig extends HTMLTagSets
{
public abstract short getWordWrapLength();
public abstract void setWordWrapLength(short val);
public abstract boolean getProcessAngles();
public abstract void setProcessAngles(boolean val);
public abstract boolean getProcessParens();
public abstract void setProcessParens(boolean val);
public abstract boolean getDiscardHTMLTags();
public abstract void setDiscardHTMLTags(boolean val);
public abstract String getAnchorTail();
public abstract void setAnchorTail(String s);
public abstract void addOutputFilter(OutputFilter filter);
public abstract void addRawOutputFilter(OutputFilter filter);
public abstract void addStringRewriter(Rewriter rewriter);
public abstract void addWordRewriter(Rewriter rewriter);
public abstract void addTagRewriter(Rewriter rewriter);
public abstract void addParenRewriter(Rewriter rewriter);
public abstract boolean isTagSetAllowed(int setid);
public abstract void allowTagSet(int setid);
public abstract void disallowTagSet(int setid);
public abstract void configureNormalTagSet();
public abstract void configureRestrictedTagSet();
public abstract HTMLChecker createHTMLChecker();
} // end interface HTMLCheckerConfig

View File

@ -0,0 +1,30 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
import com.silverwrist.venice.htmlcheck.impl.HTMLCheckerConfigImpl;
public class HTMLCheckerCreator
{
public static HTMLCheckerConfig create()
{
return HTMLCheckerConfigImpl.createHTMLCheckerConfig();
} // end create
} // end HTMLCheckerCreator

View File

@ -0,0 +1,46 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public class HTMLCheckerException extends com.silverwrist.venice.VeniceException
{
public HTMLCheckerException()
{
super();
} // end constructor
public HTMLCheckerException(String msg)
{
super(msg);
} // end constructor
public HTMLCheckerException(Exception e)
{
super(e);
} // end constructor
public HTMLCheckerException(String msg, Exception e)
{
super(msg,e);
} // end constructor
} // end class HTMLCheckerException

View File

@ -0,0 +1,138 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public interface HTMLTagSets
{
/**
* Denotes all tags that affect &quot;inline&quot; formatting only, such as
* &lt;EM&gt; and &lt;B&gt;. These are usually allowed.
*/
public static final int INLINE_FORMAT = 1;
/**
* Denotes the &quot;A&quot; tag.
*/
public static final int ANCHOR = 2;
/**
* Denotes all tags that affect &quot;block-level&quot; formatting, such as
* &lt;P&gt; and &lt;Hn&gt;.
*/
public static final int BLOCK_FORMAT = 3;
/**
* Denotes all tags that cause &quot;active&quot; content to be included in the
* HTML document, such as &lt;OBJECT&gt;, &lt;APPLET&gt;, and &lt;SCRIPT&gt;.
* These are generally not allowed.
*/
public static final int ACTIVE_CONTENT = 4;
/**
* Denotes the tags that create clickable image maps, such as &lt;AREA&gt; and
* &lt;MAP&gt;.
*/
public static final int IMAGE_MAPS = 5;
/**
* Denotes the tags that are used for document-level formatting and structure, such as
* &lt;HTML&gt;, &lt;BODY&gt;, and &lt;TITLE&gt;. These are generally not allowed.
*/
public static final int DOC_FORMAT = 6;
/**
* Denotes the &lt;FONT&gt; tag.
*/
public static final int FONT_FORMAT = 7;
/**
* Denotes all tags that are used in conjunction with forms, such as
* &lt;FORM&gt;, &lt;INPUT&gt;, and &lt;SELECT&gt;.
*/
public static final int FORMS = 8;
/**
* Denotes all tags that are used in conjunction with tables, such as
* &lt;TABLE&gt;, &lt;TR&gt;, and &lt;TD&gt;.
*/
public static final int TABLES = 9;
/**
* Denotes the &lt;DEL&gt; and &lt;INS&gt; tags, which are used for change markup.
*/
public static final int CHANGE_MARKUP = 10;
/**
* Denotes all tags related to frames, such as &lt;FRAMESET&gt; and &lt;FRAME&gt;.
* These are generally not allowed.
*/
public static final int FRAMES = 11;
/**
* Denotes the &lt;IMG&gt; tag.
*/
public static final int IMAGES = 12;
/**
* Denotes tags like &lt;PRE&gt;, which are used to preformat input text.
*/
public static final int PREFORMAT = 13;
/**
* Denotes Netscape-specific inline formatting, such as the hated &lt;BLINK&gt;.
*/
public static final int NSCP_INLINE_FORMAT = 14;
/**
* Denotes Netscape's layer tags, such as &lt;LAYER&gt; and &lt;ILAYER&gt;. These are
* generally not allowed.
*/
public static final int NSCP_LAYERS = 15;
/**
* Denotes Netscape-specific form tags, like &lt;KEYGEN&gt;. These are generally
* not allowed.
*/
public static final int NSCP_FORMS = 16;
/**
* Denotes Netscape-specific block formatting tags, like &lt;MULTICOL&gt;. These are
* generally not allowed.
*/
public static final int NSCP_BLOCK_FORMAT = 17;
/**
* Denotes the Netscape &lt;SERVER&gt; tag, used for server-side execution. This is
* generally not allowed.
*/
public static final int NSCP_SERVER = 18;
/**
* Denotes Microsoft-specific document formatting tags, such as &lt;BGSOUND&gt;. These
* are generally not allowed.
*/
public static final int MSFT_DOC_FORMAT = 19;
/**
* Denotes Microsoft-specific inline formatting tags, such as &lt;COMMENT&gt;. These
* are generally not allowed.
*/
public static final int MSFT_INLINE_FORMAT = 20;
/**
* Denotes Microsoft-specific block formatting tags, such as &lt;MARQUEE&gt;. These
* are generally not allowed.
*/
public static final int MSFT_BLOCK_FORMAT = 21;
/**
* Denotes Microsoft-specific active-content tags, such as &lt;XML&gt;. These
* are generally not allowed.
*/
public static final int MSFT_ACTIVE_CONTENT = 22;
/**
* Denotes constructs for server-side page use only, such as with Microsoft Active
* Server Pages and Sun Java Server Pages. These are generally not allowed.
*/
public static final int SERVER_PAGE = 23;
/**
* Denotes tags used by the Sun Java Server and other Java-compatible servers for
* including server-side components. These are generally not allowed.
*/
public static final int JAVA_SERVER = 24;
} // end interface HTMLTagSets

View File

@ -0,0 +1,67 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public class MarkupData
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String begin_markup;
private String text;
private String end_markup;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public MarkupData(String begin_markup, String text, String end_markup)
{
this.begin_markup = begin_markup;
this.text = text;
this.end_markup = end_markup;
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String getBeginMarkup()
{
return begin_markup;
} // end getBeginMarkup
public String getText()
{
return text;
} // end getText
public String getEndMarkup()
{
return end_markup;
} // end getEndMarkup
} // end class MarkupData

View File

@ -0,0 +1,29 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public interface ModSpellingDictionary extends SpellingDictionary
{
public abstract void addWord(String word);
public abstract void delWord(String word);
public abstract void clear();
} // end interface ModSpellingDictionary

View File

@ -0,0 +1,28 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public class NotYetFinishedException extends HTMLCheckerException
{
public NotYetFinishedException()
{
super("The HTML Checker is not yet in a finished state.");
} // end constructor
} // end NotYetFinishedException

View File

@ -0,0 +1,28 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public interface OutputFilter
{
public abstract boolean tryOutputCharacter(StringBuffer buf, char ch);
public abstract boolean matchCharacter(char ch);
public abstract int lengthNoMatch(String s);
} // end interface OutputFilter

View File

@ -0,0 +1,26 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public interface Rewriter
{
public abstract String getName();
public abstract MarkupData rewrite(String data, RewriterServices svc);
} // end interface Rewriter

View File

@ -0,0 +1,26 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public interface RewriterServices
{
public abstract String getRewriterAttrValue(String name);
public abstract Object getRewriterContextValue(String name);
} // end interface RewriterServices

View File

@ -0,0 +1,26 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck;
public interface SpellingDictionary
{
public abstract int size();
public abstract boolean checkWord(String word);
} // end interface SpellingDictionary

View File

@ -0,0 +1,144 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.dict;
import java.io.*;
import org.apache.log4j.*;
import com.silverwrist.venice.htmlcheck.SpellingDictionary;
public class LazyLexicon implements Runnable, SpellingDictionary
{
/*--------------------------------------------------------------------------------
* Static data values
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(LazyLexicon.class.getName());
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Lexicon inner_lex = null;
private String[] filenames;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public LazyLexicon(String[] filenames)
{
this.filenames = filenames; // save off the file names to be loaded
// spin off the load process into the background
Thread thrd = new Thread(this);
thrd.start();
} // end constructor
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private synchronized Lexicon getLex()
{
while (inner_lex==null)
{ // wait for the inner thread to finish creating the lexicon
if (logger.isDebugEnabled())
logger.debug("LazyLexicon: waiting for lex to load...");
try
{ // park the thread here until we know what's up
wait();
} // end try
catch (InterruptedException e)
{ // do nothing
} // end catch
} // end while
return inner_lex;
} // end getLex
/*--------------------------------------------------------------------------------
* Implementations from interface Runnable
*--------------------------------------------------------------------------------
*/
public void run()
{
Lexicon lex = new Lexicon();
if (logger.isDebugEnabled())
logger.debug("LazyLexicon loading " + String.valueOf(filenames.length) + " lexicon(s)");
for (int i=0; i<filenames.length; i++)
{ // load data into the lexicon in turn
if (logger.isDebugEnabled())
logger.debug("LazyLexicon loading file: " + filenames[i]);
try
{ // start reading the file
lex.readFile(filenames[i]);
} // end try
catch (IOException e)
{ // trap it and go on to the next one
logger.error("IOException loading lexfile " + filenames[i] + ": " + e.getMessage());
} // end catch
} // end for
if (logger.isDebugEnabled())
logger.debug("LazyLexicon load complete.");
synchronized (this)
{ // set the lexicon reference and wake up all waiting threads
inner_lex = lex;
notifyAll();
} // end synchronized block
System.gc(); // free any extra crap generated by the lexicon load
} // end run
/*--------------------------------------------------------------------------------
* Implementations from interface SpellingDictionary
*--------------------------------------------------------------------------------
*/
public int size()
{
return getLex().size();
} // end size
public boolean checkWord(String word)
{
return getLex().checkWord(word);
} // end checkWord
} // end class LazyLexicon

View File

@ -0,0 +1,239 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.dict;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import com.silverwrist.venice.htmlcheck.ModSpellingDictionary;
public class Lexicon implements ModSpellingDictionary, Serializable
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private HashSet[] sets; // 26 word sets, one for each letter of the alphabet
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public Lexicon()
{
sets = new HashSet[26];
for (int i=0; i<26; i++)
sets[i] = new HashSet(500,0.9F);
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface SpellingDictionary
*--------------------------------------------------------------------------------
*/
public synchronized int size()
{
int rc = 0;
for (int i=0; i<26; i++)
rc += sets[i].size();
return rc;
} // end size
public synchronized boolean checkWord(String word)
{
String real_word = word.toLowerCase();
int ndx = (int)(real_word.charAt(0) - 'a');
return sets[ndx].contains(real_word);
} // end checkWord
/*--------------------------------------------------------------------------------
* Implementations from interface ModSpellingDictionary
*--------------------------------------------------------------------------------
*/
public synchronized void addWord(String word)
{
String real_word = word.toLowerCase();
int ndx = (int)(real_word.charAt(0) - 'a');
sets[ndx].add(real_word);
} // end addWord
public synchronized void delWord(String word)
{
String real_word = word.toLowerCase();
int ndx = (int)(real_word.charAt(0) - 'a');
sets[ndx].remove(real_word);
} // end delWord
public synchronized void clear()
{
for (int i=0; i<26; i++)
sets[i].clear();
} // end clear
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public synchronized void saveToStream(OutputStream stm, boolean compress) throws IOException
{
ObjectOutputStream real_stm;
if (compress)
{ // run through a GZIP object before writing
GZIPOutputStream gz_stm = new GZIPOutputStream(stm);
real_stm = new ObjectOutputStream(gz_stm);
} // end if
else // just create the ObjectOutputStream directly
real_stm = new ObjectOutputStream(stm);
real_stm.writeObject(this);
real_stm.flush();
} // end saveToStream
public synchronized void saveToFile(File file, boolean compress) throws IOException
{
FileOutputStream fstm = new FileOutputStream(file);
try
{ // save the object data
saveToStream(fstm,compress);
fstm.flush();
} // end try
finally
{ // make sure we close the file before leaving
fstm.close();
} // end finally
} // end saveToFile
public synchronized void saveToFile(String filename, boolean compress) throws IOException
{
FileOutputStream fstm = new FileOutputStream(filename);
try
{ // save the object data
saveToStream(fstm,compress);
fstm.flush();
} // end try
finally
{ // make sure we close the file before leaving
fstm.close();
} // end finally
} // end saveToFile
public synchronized void readFile(String filename) throws IOException
{
BufferedReader rdr = new BufferedReader(new FileReader(filename));
String word = rdr.readLine();
while (word!=null)
{ // add each word to the lexicon as we go
addWord(word);
word = rdr.readLine();
} // end while
rdr.close();
} // end readFile
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static Lexicon loadFromStream(InputStream stm, boolean compress) throws IOException
{
ObjectInputStream real_stm;
if (compress)
{ // chain in a decompressor before we read the object
GZIPInputStream gz_stm = new GZIPInputStream(stm);
real_stm = new ObjectInputStream(gz_stm);
} // end if
else // just load uncompressed
real_stm = new ObjectInputStream(stm);
try
{ // attempt to read the LExicon object
Object tmp = real_stm.readObject();
if (tmp instanceof Lexicon)
return (Lexicon)tmp;
throw new IOException("invalid stream data format");
} // end try
catch (OptionalDataException od)
{ // translate exception here so we only throw one type
throw new IOException("invalid stream data format");
} // end catch
catch (ClassNotFoundException cnf)
{ // translate exception here so we only throw one type
throw new IOException("invalid stream data format");
} // end catch
} // end loadFromStream
public static Lexicon loadFromFile(File file, boolean compress) throws IOException
{
FileInputStream fstm = new FileInputStream(file);
try
{ // load the object data and return it
return loadFromStream(fstm,compress);
} // end try
finally
{ // close the file before leaving
fstm.close();
} // end finally
} // end loadFromFile
public static Lexicon loadFromFile(String filename, boolean compress) throws IOException
{
FileInputStream fstm = new FileInputStream(filename);
try
{ // load the object data and return it
return loadFromStream(fstm,compress);
} // end try
finally
{ // close the file before leaving
fstm.close();
} // end finally
} // end loadFromFile
} // end class Lexicon

View File

@ -0,0 +1,117 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.dict;
import java.io.*;
public class LexiconBuilder
{
private LexiconBuilder()
{ // cannot construct this object
} // end constructor
private static final String USAGE = "Usage: LexiconBuilder [-c] outputfile inputfile [...]";
public static void main(String args[])
{
if (args.length==0)
{ // print the usage string and exit
System.err.println(USAGE);
System.exit(1);
} // end if
boolean compress = false;
int ofx = 0;
if (args[0].equals("-c"))
{ // we're compressing the output
compress = true;
if (++ofx>=args.length)
{ // no output filename specified!
System.err.println("No output file specified!");
System.err.println(USAGE);
System.exit(1);
} // end if
} // end if
int ifx = ofx + 1;
if (ifx>=args.length)
{ // no input filename specified!
System.err.println("No input file specified!");
System.err.println(USAGE);
System.exit(1);
} // end if
Lexicon lex = new Lexicon(); // initialize lexicon object
while (ifx<args.length)
{ // load each file in turn
try
{ // start reading the file
BufferedReader rdr = new BufferedReader(new FileReader(args[ifx]));
System.out.println("Loading from file " + args[ifx]);
int ctr = 0;
String word = rdr.readLine();
while (word!=null)
{ // add each word to the lexicon as we go
lex.addWord(word);
if (((++ctr) % 1000)==0)
System.out.println("...read " + String.valueOf(ctr) + " words");
word = rdr.readLine();
} // end while
rdr.close();
System.out.println("Finished reading " + args[ifx] + ", " + String.valueOf(ctr) + " words read");
} // end try
catch (IOException e)
{ // just die on IOException
System.err.println("Error loading " + args[ifx] + ": " + e.getMessage());
System.exit(1);
} // end catch
ifx++; // go to next file
} // end while
System.out.println("All input files loaded, " + String.valueOf(lex.size()) + " words in total");
try
{ // save the lexicon to its very own file
lex.saveToFile(args[ofx],compress);
} // end try
catch (IOException e)
{ // just die on IOException
System.err.println("Error writing to " + args[ofx] + ": " + e.getMessage());
System.exit(1);
} // end catch
System.out.println("Wrote " + args[ofx] + ", LexiconBuilder complete.");
System.exit(0);
} // end main
} // end class LexiconBuilder

View File

@ -0,0 +1,89 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.dict;
import java.io.*;
import java.util.*;
public class LexiconTest
{
private LexiconTest()
{ // this class cannot be instantiated
} // end constructor
private static final String USAGE = "Usage: LexiconTest [-c] lexfile word [...]";
public static void main(String args[])
{
if (args.length==0)
{ // print the usage string and exit
System.err.println(USAGE);
System.exit(1);
} // end if
boolean compress = false;
int ifx = 0;
if (args[0].equals("-c"))
{ // we're compressing the output
compress = true;
if (++ifx>=args.length)
{ // no lexicon specified!
System.err.println("No lexicon file specified!");
System.err.println(USAGE);
System.exit(1);
} // end if
} // end if
int wfx = ifx + 1;
Lexicon lex = null;
try
{ // save the lexicon to its very own file
System.out.println("Loading " + args[ifx] + "...");
Date start = new Date();
lex = Lexicon.loadFromFile(args[ifx],compress);
Date stop = new Date();
long interval = stop.getTime() - start.getTime();
System.out.println("Loaded " + args[ifx] + ", elapsed time " + String.valueOf(interval/1000) + "."
+ String.valueOf(interval%1000) + " seconds");
} // end try
catch (IOException e)
{ // just die on IOException
System.err.println("Error loading from " + args[ifx] + ": " + e.getMessage());
System.exit(1);
} // end catch
while (wfx<args.length)
{ // check each word specified on the command line
if (lex.checkWord(args[wfx]))
System.out.println(args[wfx] + ": in the dictionary");
else
System.out.println(args[wfx] + ": NOT in the dictionary");
} // end while
System.exit(0);
} // end main
} // end class LexiconTest

View File

@ -0,0 +1,68 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.filters;
import java.util.*;
import com.silverwrist.venice.htmlcheck.Rewriter;
import com.silverwrist.venice.htmlcheck.RewriterServices;
import com.silverwrist.venice.htmlcheck.MarkupData;
public class EmailRewriter implements Rewriter
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public EmailRewriter()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface Rewriter
*--------------------------------------------------------------------------------
*/
public String getName()
{
return null;
} // end getName
public MarkupData rewrite(String data, RewriterServices svc)
{
int at_pos = data.indexOf('@');
if ((at_pos<=0) || (at_pos==(data.length()-1)))
return null;
// TODO: put in more validation checking
// build the <A> tag (the gnarliest part)
StringBuffer open_a = new StringBuffer("<A HREF=\"mailto:");
open_a.append(data).append("\"");
String catenate = svc.getRewriterAttrValue("ANCHORTAIL");
if ((catenate!=null) && (catenate.length()>0))
open_a.append(' ').append(catenate);
open_a.append('>');
// return the markup data back to the checker
return new MarkupData(open_a.toString(),data,"</A>");
} // end rewrite
} // end class EmailRewriter

View File

@ -0,0 +1,148 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.filters;
import com.silverwrist.venice.htmlcheck.OutputFilter;
/**
* An output filter for <CODE>HTMLChecker</CODE> that escapes the three basic characters
* used by HTML formatting. It translates the following characters:
* <UL>
* <LI>&lt; - &amp;lt;</LI>
* <LI>&gt; - &amp;gt;</LI>
* <LI>&amp; - &amp;amp;</LI>
* </UL>
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @see HTMLOutputFilter
* @see HTMLChecker#addOutputFilter
*/
public class HTMLEncodingFilter implements OutputFilter
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String ESCAPED_CHARACTERS = "<>&";
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Creates a new instance of <CODE>HTMLEncodingFilter.</CODE>
*/
public HTMLEncodingFilter()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface OutputFilter
*--------------------------------------------------------------------------------
*/
/**
* Checks and possibly outputs a character. If the character <CODE>ch</CODE> is '<',
* '>', or '&', it appends the appropriate string to the string buffer
* <CODE>buf</CODE> and returns <CODE>true</CODE>. If not, it returns <CODE>false</CODE>
* and leaves the buffer alone.
*
* @param buf The string buffer to append the character equivalent to.
* @param ch The character to be checked and possibly output.
* @return <CODE>true</CODE> if the character matches and was output,
* <CODE>false</CODE> if not.
* @see #matchCharacter
* @see HTMLOutputFilter#tryOutputCharacter
*/
public boolean tryOutputCharacter(StringBuffer buf, char ch)
{
switch (ch)
{ // turn the HTML flag characters into appropriate entity escapes
case '<':
buf.append("&lt;");
return true;
case '>':
buf.append("&gt;");
return true;
case '&':
buf.append("&amp;");
return true;
default:
break;
} // end switch
return false; // bail out! not one we handle!
} // end tryOutputCharacter
/**
* Returns <CODE>true</CODE> if the character <CODE>ch</CODE> is '<', '>', or '&',
* <CODE>false</CODE> if not.
*
* @param ch The character to be tested.
* @return <CODE>true</CODE> if the character <CODE>ch</CODE> is '<', '>', or '&',
* <CODE>false</CODE> if not.
* @see #tryOutputCharacter
* @see #lengthNoMatch
* @see HTMLOutputFilter#matchCharacter
*/
public boolean matchCharacter(char ch)
{
return (ESCAPED_CHARACTERS.indexOf(ch)>=0);
} // end matchCharacter
/**
* Given a character string, returns the total number of characters in that string,
* starting from the beginning, that are <I>not</I> handled by this filter before
* one that <I>is</I> appears. If none of the characters in this string are handled
* by the filter, the length of the string is returned.
*
* @param s The string to scan through.
* @return The length of the initial sequence of non-matching characters in this string.
* @see #matchCharacter
* @see HTMLOutputFilter#lengthNoMatch
*/
public int lengthNoMatch(String s)
{
int rc = s.length();
int i;
for (i=0; i<ESCAPED_CHARACTERS.length(); i++)
{ // look for one of the escaped characters in the string...
int tmp = s.indexOf(ESCAPED_CHARACTERS.charAt(i));
if ((tmp>=0) && (tmp<rc))
{ // we have a new return value
rc = tmp;
if (rc==0)
break; // can't get any lower!
} // end if
} // end for
return rc;
} // end lengthNoMatch
} // end class HTMLEncodingFilter

View File

@ -0,0 +1,112 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.filters;
import com.silverwrist.venice.htmlcheck.OutputFilter;
/**
* An output filter for <CODE>HTMLChecker</CODE> that escapes the apostrophe character
* (the SQL quote character) by doubling it.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @see OutputFilter
* @see HTMLChecker#addOutputFilter
*/
public class SQLEncodingFilter implements OutputFilter
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Creates a new instance of <CODE>SQLEncodingFilter.</CODE>
*/
public SQLEncodingFilter()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface OutputFilter
*--------------------------------------------------------------------------------
*/
/**
* Checks and possibly outputs a character. If the character <CODE>ch</CODE> is
* an apostrophe, it appends two apostrophes to the string buffer
* <CODE>buf</CODE> and returns <CODE>true</CODE>. If not, it returns <CODE>false</CODE>
* and leaves the buffer alone.
*
* @param buf The string buffer to append the character equivalent to.
* @param ch The character to be checked and possibly output.
* @return <CODE>true</CODE> if the character matches and was output,
* <CODE>false</CODE> if not.
* @see #matchCharacter
* @see HTMLOutputFilter#tryOutputCharacter
*/
public boolean tryOutputCharacter(StringBuffer buf, char ch)
{
if (ch=='\'')
{ // convert one apostrophe into two
buf.append("\'\'");
return true;
} // end if
return false;
} // end tryOutputCharacter
/**
* Returns <CODE>true</CODE> if the character <CODE>ch</CODE> is an apostrophe,
* <CODE>false</CODE> if not.
*
* @param ch The character to be tested.
* @return <CODE>true</CODE> if the character <CODE>ch</CODE> is an apostrophe,
* <CODE>false</CODE> if not.
* @see #tryOutputCharacter
* @see #lengthNoMatch
* @see HTMLOutputFilter#matchCharacter
*/
public boolean matchCharacter(char ch)
{
return (ch=='\'');
} // end matchCharacter
/**
* Given a character string, returns the total number of characters in that string,
* starting from the beginning, that are <I>not</I> handled by this filter before
* one that <I>is</I> appears. If none of the characters in this string are handled
* by the filter, the length of the string is returned.
*
* @param s The string to scan through.
* @return The length of the initial sequence of non-matching characters in this string.
* @see #matchCharacter
* @see HTMLOutputFilter#lengthNoMatch
*/
public int lengthNoMatch(String s)
{
int rc = s.indexOf('\'');
if (rc<0)
rc = s.length();
return rc;
} // end lengthNoMatch
} // end class SQLEncodingFilter

View File

@ -0,0 +1,118 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.filters;
import java.util.*;
import com.silverwrist.venice.htmlcheck.Rewriter;
import com.silverwrist.venice.htmlcheck.RewriterServices;
import com.silverwrist.venice.htmlcheck.MarkupData;
import com.silverwrist.venice.htmlcheck.SpellingDictionary;
public class SpellingRewriter implements Rewriter
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String DEFAULT_BEGIN_ERROR = "<FONT COLOR=\"red\"><B>";
private static final String DEFAULT_END_ERROR = "</B></FONT>";
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Vector dictionaries = new Vector();
private String begin_error = DEFAULT_BEGIN_ERROR;
private String end_error = DEFAULT_END_ERROR;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public SpellingRewriter()
{ // do nothing here
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface Rewriter
*--------------------------------------------------------------------------------
*/
public String getName()
{
return "spelling";
} // end getName
public MarkupData rewrite(String data, RewriterServices svc)
{
Iterator it = dictionaries.iterator();
while (it.hasNext())
{ // check each stored dictionary in turn
SpellingDictionary dict = (SpellingDictionary)(it.next());
if (dict.checkWord(data))
return null; // it's in a dictionary, that means it's spelled right
} // end while
// not found - it's spelled wrong
return new MarkupData(begin_error,data,end_error);
} // end rewrite
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public void addDictionary(SpellingDictionary dict)
{
dictionaries.add(dict);
} // end addDictionary
public String getBeginError()
{
return begin_error;
} // end getBeginError
public void setBeginError(String val)
{
begin_error = val;
} // end setBeginError
public String getEndError()
{
return end_error;
} // end getEndError
public void setEndError(String val)
{
end_error = val;
} // end setEndError
} // end class SpellingRewriter

View File

@ -0,0 +1,114 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.filters;
import java.util.*;
import com.silverwrist.venice.htmlcheck.Rewriter;
import com.silverwrist.venice.htmlcheck.RewriterServices;
import com.silverwrist.venice.htmlcheck.MarkupData;
public class URLRewriter implements Rewriter
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String NULLSTRING = "";
private static Hashtable prefix_list = null;
private static boolean set_up = true;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public URLRewriter()
{
setUpPrefixes(); // make sure the prefix data is set up
} // end constructor
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private static void setUpPrefixes()
{
if (set_up)
{ // allocate the hash table
set_up = false;
prefix_list = new Hashtable(10,0.9F);
// fill it with the proper URL prefixes
prefix_list.put("http:",NULLSTRING);
prefix_list.put("ftp:",NULLSTRING);
prefix_list.put("gopher:",NULLSTRING);
prefix_list.put("mailto:",NULLSTRING);
prefix_list.put("news:",NULLSTRING);
prefix_list.put("nntp:",NULLSTRING);
prefix_list.put("telnet:",NULLSTRING);
prefix_list.put("tn3270:",NULLSTRING);
prefix_list.put("www.",new String("http://"));
prefix_list.put("ftp.",new String("ftp://"));
prefix_list.put("gopher.",new String("gopher://"));
} // end if
} // end setUpPrefixes
/*--------------------------------------------------------------------------------
* Implementations from interface Rewriter
*--------------------------------------------------------------------------------
*/
public String getName()
{
return null;
} // end getName
public MarkupData rewrite(String data, RewriterServices svc)
{
Enumeration prefixes = prefix_list.keys();
while (prefixes.hasMoreElements())
{ // get the next prefix and compare against the beginning of the string
String pfx = (String)(prefixes.nextElement());
if (data.regionMatches(true,0,pfx,0,pfx.length()))
{ // good enough! build the open <A> tag (the gnarliest part of the markup)
StringBuffer open_a = new StringBuffer("<A HREF=\"");
String catenate = (String)(prefix_list.get(pfx));
open_a.append(catenate).append(data).append("\"");
catenate = svc.getRewriterAttrValue("ANCHORTAIL");
if ((catenate!=null) && (catenate.length()>0))
open_a.append(' ').append(catenate);
open_a.append('>');
// here's how you mark it up!
return new MarkupData(open_a.toString(),data,"</A>");
} // end if
} // end while
return null; // sorry, no can do
} // end rewrite
} // end class URLRewriter

View File

@ -0,0 +1,49 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
class BalancedTag extends OpenCloseTag
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
BalancedTag(String name, boolean brk)
{
super(name,brk);
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public final boolean balanceTags()
{
return true;
} // end balanceTags
} // end class BalancedTag

View File

@ -0,0 +1,28 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
public interface HTMLCheckerBackend
{
public abstract String getCheckerAttrValue(String name);
public abstract void sendTagMessage(String msg);
public abstract Object getCheckerContextValue(String name);
} // end interface HTMLCheckerBackend

View File

@ -0,0 +1,252 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
import java.util.*;
import com.silverwrist.venice.htmlcheck.*;
public class HTMLCheckerConfigImpl implements HTMLCheckerConfig
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String DEFAULT_ANCHOR_TAIL = "TARGET=\"Wander\"";
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private boolean process_angles = true; // process angle-bracketed strings?
private boolean process_parens = true; // process parenthesized strings?
private boolean discard_html_tags = false; // discard all HTML tags?
private short word_wrap_length = 0; // word wrap length
private String anchor_tail = DEFAULT_ANCHOR_TAIL; // the tail end of the anchor
private BitSet allowed_tagsets = new BitSet(); // which tagsets are allowed?
private Vector output_filters = new Vector(); // output filters
private Vector raw_output_filters = new Vector(); // output filters only applied in "raw mode"
private Vector string_rewriters = new Vector(); // rewriters that operate on full "strings"
private Vector word_rewriters = new Vector(); // rewriters that operate on "words" only
private Vector tag_rewriters = new Vector(); // rewriters that operate on <tags> only
private Vector paren_rewriters = new Vector(); // rewriters that operate on (parens) only
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
HTMLCheckerConfigImpl()
{
TagRepository.init();
TagRepository.configureNormalSet(allowed_tagsets);
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface HTMLCheckerConfig
*--------------------------------------------------------------------------------
*/
public short getWordWrapLength()
{
return word_wrap_length;
} // end getWordWrapLength
public void setWordWrapLength(short val)
{
if (val<0)
word_wrap_length = 0;
else
word_wrap_length = val;
} // end setWordWrapLength
public boolean getProcessAngles()
{
return process_angles;
} // end getProcessAngles
public void setProcessAngles(boolean val)
{
process_angles = val;
} // end setProcessAngles
public boolean getProcessParens()
{
return process_parens;
} // end getProcessParens
public void setProcessParens(boolean val)
{
process_parens = val;
} // end setProcessParens
public boolean getDiscardHTMLTags()
{
return discard_html_tags;
} // end getDiscardHTMLTags
public void setDiscardHTMLTags(boolean val)
{
discard_html_tags = val;
} // end setDiscardHTMLTags
public String getAnchorTail()
{
return anchor_tail;
} // end getAnchorTail
public void setAnchorTail(String s)
{
anchor_tail = s;
} // end setAnchorTail
public void addOutputFilter(OutputFilter filter)
{
output_filters.add(filter);
} // end addOutputFilter
public void addRawOutputFilter(OutputFilter filter)
{
raw_output_filters.add(filter);
} // end addRawOutputFilter
public void addStringRewriter(Rewriter rewriter)
{
string_rewriters.add(rewriter);
} // end addStringRewriter
public void addWordRewriter(Rewriter rewriter)
{
word_rewriters.add(rewriter);
} // end addWordRewriter
public void addTagRewriter(Rewriter rewriter)
{
tag_rewriters.add(rewriter);
} // end addTagRewriter
public void addParenRewriter(Rewriter rewriter)
{
} // end addParenRewriter
public boolean isTagSetAllowed(int setid)
{
return allowed_tagsets.get(setid);
} // end isTagSetAllowed
public void allowTagSet(int setid)
{
allowed_tagsets.set(setid);
} // end allowTagSet
public void disallowTagSet(int setid)
{
allowed_tagsets.clear(setid);
} // end disallowTagSet
public void configureNormalTagSet()
{
TagRepository.configureNormalSet(allowed_tagsets);
} // end configureNormalTagSet
public void configureRestrictedTagSet()
{
TagRepository.configureRestrictedSet(allowed_tagsets);
} // end configureRestrictedTagSet
/*--------------------------------------------------------------------------------
* Operations usable only from within the package
*--------------------------------------------------------------------------------
*/
List getOutputFilters()
{
return output_filters;
} // end getOutputFilters
List getRawOutputFilters()
{
return raw_output_filters;
} // end getRawOutputFilters
List getStringRewriters()
{
return string_rewriters;
} // end getStringRewriters
List getWordRewriters()
{
return word_rewriters;
} // end getWordRewriters
List getTagRewriters()
{
return tag_rewriters;
} // end getTagRewriters
List getParenRewriters()
{
return paren_rewriters;
} // end getParenRewriters
public HTMLChecker createHTMLChecker()
{
return new HTMLCheckerImpl(this);
} // end createHTMLChecker
/*--------------------------------------------------------------------------------
* Static operations
*--------------------------------------------------------------------------------
*/
public static HTMLCheckerConfig createHTMLCheckerConfig()
{
return new HTMLCheckerConfigImpl();
} // end createHTMLCheckerConfig
} // end class HTMLCheckerConfigImpl

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,44 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
class ListElementTag extends OpenCloseTag
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
ListElementTag(String name)
{
super(name,true);
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public boolean causeLineBreak(boolean is_closing)
{
return !is_closing;
} // end causeLineBreak
} // end class ListElementTag

View File

@ -0,0 +1,50 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
class OpenCloseTag extends SimpleTag
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
OpenCloseTag(String name, boolean brk)
{
super(name,brk);
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public final boolean allowClose()
{
return true;
} // end allowClose
public final String makeClosingTag()
{
return "</" + getTagName() + ">";
} // end makeClosingTag
} // end class OpenCloseTag

View File

@ -0,0 +1,103 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
class SimpleTag
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String tagname; // the name of the tag
private boolean linebreak; // does tag cause line breaks?
private int index; // index of the tag
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
SimpleTag(String name, boolean brk)
{
tagname = name.toUpperCase();
linebreak = brk;
index = -1;
} // end constructor
/*--------------------------------------------------------------------------------
* Operations usable only within the package
*--------------------------------------------------------------------------------
*/
final void setIndex(int ndx)
{
if (index==-1)
index = ndx;
} // end setIndex
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String getTagName()
{
return tagname;
} // end getTagName
public boolean allowClose()
{
return false;
} // end allowClose
public boolean balanceTags()
{
return false;
} // end balanceTags
public boolean causeLineBreak(boolean is_closing)
{
return linebreak;
} // end causeLineBreak
public final int getIndex()
{
return index;
} // end getIndex
public String makeClosingTag()
{
throw new RuntimeException("cannot make closing tags of SimpleTag");
} // end makeClosingTag
public String rewriteTagContents(String contents, boolean is_closing, HTMLCheckerBackend context)
{
return contents; // just let everything pass for now
} // end rewriteTagContents
} // end class SimpleTag

View File

@ -0,0 +1,124 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
class TagA extends BalancedTag
{
/*--------------------------------------------------------------------------------
* Internal static data
*--------------------------------------------------------------------------------
*/
private static final String TARGET_ATTR = "TARGET";
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
TagA()
{
super("A",false);
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String rewriteTagContents(String contents, boolean is_closing, HTMLCheckerBackend context)
{
if (is_closing)
return contents; // don't bother checking close tags
// Skip over the initial word of the tag data, as that's the tag name.
int i = 0;
while ((i!=contents.length()) && !(Character.isWhitespace(contents.charAt(i))))
i++;
// Search for the TARGET= attribute in the tag data.
boolean target_seen = false;
while (i!=contents.length())
{ // skip over any whitespace between one attribute (or the name) and the next one
while ((i!=contents.length()) && Character.isWhitespace(contents.charAt(i)))
i++;
if (i==contents.length())
break; // reached end of string, all done searching
// Mark the start of this attribute name and start skipping over it.
int start_name = i;
while ((i!=contents.length()) && !(Character.isWhitespace(contents.charAt(i)))
&& (contents.charAt(i)!='='))
i++;
// We now know where the attribute name is, see if it's "TARGET".
if ((i-start_name)==TARGET_ATTR.length())
{ // compare the substring to see if it's right
String name = contents.substring(start_name,i);
if (name.equalsIgnoreCase(TARGET_ATTR))
{ // OK, we saw the TARGET tag in the list! Bail out!
target_seen = true;
break;
} // end if
} // end if
while ((i!=contents.length()) && Character.isWhitespace(contents.charAt(i)))
i++; // skip over whitespace at end of name but before the = sign
if ((i<contents.length()) && (contents.charAt(i)=='='))
{ // skip over the = sign first
i++;
while ((i!=contents.length()) && Character.isWhitespace(contents.charAt(i)))
i++; // skip over whitespace after the = sign
if (i==contents.length())
break; // reached end of string, all done searching
if ((contents.charAt(i)=='\'') || (contents.charAt(i)=='\"'))
{ // this is a quoted string - swallow it
char quote_char = contents.charAt(i++); // skip the quote part
while ((i!=contents.length()) && (contents.charAt(i)!=quote_char))
i++; // skip over data between quotes
if (i!=contents.length())
i++; // skip over last quote
} // end if
else
{ // skip over a single word
while ((i!=contents.length()) && !(Character.isWhitespace(contents.charAt(i))))
i++;
} // end else
} // end if
// else this tag had no value - just go on to the next one
} // end while
if (target_seen)
return contents; // no need to alter the string
String tail = (String)(context.getCheckerAttrValue("ANCHORTAIL"));
return new String(contents + " " + tail);
} // end rewriteTagContents
} // end class TagA

View File

@ -0,0 +1,48 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
class TagNOBR extends BalancedTag
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
TagNOBR()
{
super("NOBR",false);
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String rewriteTagContents(String contents, boolean is_closing, HTMLCheckerBackend context)
{
if (is_closing)
context.sendTagMessage("/NOBR");
else
context.sendTagMessage("NOBR");
return contents;
} // end rewriteTagContents
} // end class TagNOBR

View File

@ -0,0 +1,243 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
import java.util.*;
import com.silverwrist.venice.htmlcheck.HTMLTagSets;
class TagRepository implements HTMLTagSets
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private static Hashtable tagname_to_index = new Hashtable(50,0.9F);
private static Vector index_to_object = new Vector();
private static Vector index_to_setid = new Vector();
private static int maxlength = 0;
private static boolean initialized = false;
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
private static void enshrineTag(SimpleTag tag, int set)
{
int ndx = index_to_object.size();
index_to_object.add(tag);
index_to_setid.add(new Integer(set));
tag.setIndex(ndx);
tagname_to_index.put(new String(tag.getTagName()),new Integer(ndx));
int newlen = tag.getTagName().length();
if (newlen>maxlength)
maxlength = newlen;
} // end enshrineTag
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static void init()
{
if (!initialized)
{ // set the flag so we don't do this again
initialized = true;
// begin enshrining the tags!
enshrineTag(new SimpleTag("!DOCTYPE",false),DOC_FORMAT);
enshrineTag(new SimpleTag("%",false),SERVER_PAGE);
enshrineTag(new SimpleTag("%=",false),SERVER_PAGE);
enshrineTag(new SimpleTag("%@",false),SERVER_PAGE);
enshrineTag(new TagA(),ANCHOR);
enshrineTag(new BalancedTag("ABBR",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("ACRONYM",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("ADDRESS",true),BLOCK_FORMAT);
enshrineTag(new BalancedTag("APPLET",false),ACTIVE_CONTENT);
enshrineTag(new SimpleTag("AREA",false),IMAGE_MAPS);
enshrineTag(new BalancedTag("B",false),INLINE_FORMAT);
enshrineTag(new SimpleTag("BASE",false),DOC_FORMAT);
enshrineTag(new SimpleTag("BASEFONT",false),DOC_FORMAT);
enshrineTag(new BalancedTag("BDO",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("BEAN",false),JAVA_SERVER);
enshrineTag(new SimpleTag("BGSOUND",false),MSFT_DOC_FORMAT);
enshrineTag(new BalancedTag("BIG",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("BLINK",false),NSCP_INLINE_FORMAT);
enshrineTag(new BalancedTag("BLOCKQUOTE",true),BLOCK_FORMAT);
enshrineTag(new OpenCloseTag("BODY",false),DOC_FORMAT);
enshrineTag(new SimpleTag("BR",true),BLOCK_FORMAT);
enshrineTag(new OpenCloseTag("BUTTON",false),FORMS);
enshrineTag(new BalancedTag("CAPTION",true),TABLES);
enshrineTag(new BalancedTag("CENTER",true),BLOCK_FORMAT);
enshrineTag(new BalancedTag("CITE",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("CODE",false),INLINE_FORMAT);
enshrineTag(new SimpleTag("COL",true),TABLES);
enshrineTag(new OpenCloseTag("COLGROUP",true),TABLES);
enshrineTag(new BalancedTag("COMMENT",false),MSFT_INLINE_FORMAT);
enshrineTag(new ListElementTag("DD"),BLOCK_FORMAT);
enshrineTag(new BalancedTag("DEL",false),CHANGE_MARKUP);
enshrineTag(new BalancedTag("DFN",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("DIR",true),BLOCK_FORMAT);
enshrineTag(new BalancedTag("DIV",true),BLOCK_FORMAT);
enshrineTag(new BalancedTag("DL",true),BLOCK_FORMAT);
enshrineTag(new ListElementTag("DT"),BLOCK_FORMAT);
enshrineTag(new BalancedTag("EM",false),INLINE_FORMAT);
enshrineTag(new SimpleTag("EMBED",false),ACTIVE_CONTENT);
enshrineTag(new BalancedTag("FIELDSET",false),FORMS);
enshrineTag(new BalancedTag("FONT",false),FONT_FORMAT);
enshrineTag(new BalancedTag("FORM",false),FORMS);
enshrineTag(new SimpleTag("FRAME",true),FRAMES);
enshrineTag(new BalancedTag("FRAMESET",false),FRAMES);
enshrineTag(new BalancedTag("H1",true),FONT_FORMAT);
enshrineTag(new BalancedTag("H2",true),FONT_FORMAT);
enshrineTag(new BalancedTag("H3",true),FONT_FORMAT);
enshrineTag(new BalancedTag("H4",true),FONT_FORMAT);
enshrineTag(new BalancedTag("H5",true),FONT_FORMAT);
enshrineTag(new BalancedTag("H6",true),FONT_FORMAT);
enshrineTag(new OpenCloseTag("HEAD",false),DOC_FORMAT);
enshrineTag(new SimpleTag("HR",true),BLOCK_FORMAT);
enshrineTag(new OpenCloseTag("HTML",false),DOC_FORMAT);
enshrineTag(new BalancedTag("I",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("IFRAME",true),FRAMES);
enshrineTag(new BalancedTag("ILAYER",true),NSCP_LAYERS);
enshrineTag(new SimpleTag("IMG",false),IMAGES);
enshrineTag(new SimpleTag("INPUT",false),FORMS);
enshrineTag(new BalancedTag("INS",false),CHANGE_MARKUP);
enshrineTag(new SimpleTag("ISINDEX",false),FORMS);
enshrineTag(new BalancedTag("KBD",false),INLINE_FORMAT);
enshrineTag(new SimpleTag("KEYGEN",false),NSCP_FORMS);
enshrineTag(new BalancedTag("LABEL",false),FORMS);
enshrineTag(new BalancedTag("LAYER",true),NSCP_LAYERS);
enshrineTag(new BalancedTag("LEGEND",false),FORMS);
enshrineTag(new ListElementTag("LI"),BLOCK_FORMAT);
enshrineTag(new SimpleTag("LINK",false),DOC_FORMAT);
enshrineTag(new BalancedTag("LISTING",false),MSFT_INLINE_FORMAT);
enshrineTag(new BalancedTag("MAP",false),IMAGE_MAPS);
enshrineTag(new BalancedTag("MARQUEE",true),MSFT_BLOCK_FORMAT);
enshrineTag(new BalancedTag("MENU",true),BLOCK_FORMAT);
enshrineTag(new SimpleTag("META",false),DOC_FORMAT);
enshrineTag(new BalancedTag("MULTICOL",true),NSCP_BLOCK_FORMAT);
enshrineTag(new TagNOBR(),BLOCK_FORMAT);
enshrineTag(new BalancedTag("NOEMBED",false),ACTIVE_CONTENT);
enshrineTag(new BalancedTag("NOFRAMES",false),FRAMES);
enshrineTag(new BalancedTag("NOLAYER",false),NSCP_LAYERS);
enshrineTag(new BalancedTag("NOSCRIPT",false),ACTIVE_CONTENT);
enshrineTag(new BalancedTag("OBJECT",false),ACTIVE_CONTENT);
enshrineTag(new BalancedTag("OL",true),BLOCK_FORMAT);
enshrineTag(new BalancedTag("OPTGROUP",false),FORMS);
enshrineTag(new ListElementTag("OPTION"),FORMS);
enshrineTag(new OpenCloseTag("P",true),BLOCK_FORMAT);
enshrineTag(new SimpleTag("PARAM",false),ACTIVE_CONTENT);
enshrineTag(new SimpleTag("PLAINTEXT",false),PREFORMAT);
enshrineTag(new BalancedTag("PRE",false),PREFORMAT);
enshrineTag(new BalancedTag("Q",false),INLINE_FORMAT);
enshrineTag(new SimpleTag("RT",false),MSFT_ACTIVE_CONTENT);
enshrineTag(new BalancedTag("RUBY",false),MSFT_ACTIVE_CONTENT);
enshrineTag(new BalancedTag("S",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("SAMP",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("SCRIPT",false),ACTIVE_CONTENT);
enshrineTag(new BalancedTag("SELECT",false),FORMS);
enshrineTag(new BalancedTag("SERVER",false),NSCP_SERVER);
enshrineTag(new BalancedTag("SERVLET",false),JAVA_SERVER);
enshrineTag(new BalancedTag("SMALL",false),INLINE_FORMAT);
enshrineTag(new SimpleTag("SPACER",false),NSCP_INLINE_FORMAT);
enshrineTag(new BalancedTag("SPAN",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("STRIKE",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("STRONG",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("STYLE",false),DOC_FORMAT);
enshrineTag(new BalancedTag("SUB",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("SUP",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("TABLE",true),TABLES);
enshrineTag(new OpenCloseTag("TBODY",false),TABLES);
enshrineTag(new BalancedTag("TD",true),TABLES);
enshrineTag(new BalancedTag("TEXTAREA",true),FORMS);
enshrineTag(new OpenCloseTag("TFOOT",false),TABLES);
enshrineTag(new BalancedTag("TH",true),TABLES);
enshrineTag(new OpenCloseTag("THEAD",false),TABLES);
enshrineTag(new BalancedTag("TITLE",false),DOC_FORMAT);
enshrineTag(new BalancedTag("TR",true),TABLES);
enshrineTag(new BalancedTag("TT",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("U",false),INLINE_FORMAT);
enshrineTag(new BalancedTag("UL",true),BLOCK_FORMAT);
enshrineTag(new BalancedTag("VAR",false),INLINE_FORMAT);
enshrineTag(new TagWBR(),BLOCK_FORMAT);
enshrineTag(new BalancedTag("XML",false),MSFT_ACTIVE_CONTENT);
enshrineTag(new BalancedTag("XMP",false),NSCP_INLINE_FORMAT);
} // end if
} // end init
public static int getMaxTagLength()
{
return maxlength;
} // end getMaxTagLength
public static int tagNameToIndex(String tag)
{ // look up tag name and get index
Object obj = tagname_to_index.get(tag.toUpperCase());
if (obj==null)
return -1;
else
return ((Integer)obj).intValue();
} // end tagNameToIndex
public static SimpleTag tagIndexToObject(int ndx)
{
Object obj = index_to_object.get(ndx);
if (obj==null)
return null;
else
return (SimpleTag)obj;
} // end tagIndexToObject
public static int tagIndexToSet(int ndx)
{
Object obj = index_to_setid.get(ndx);
if (obj==null)
return -1;
else
return ((Integer)obj).intValue();
} // end tagIndexToSet
public static void configureNormalSet(BitSet bs)
{
bs.xor(bs); // clears all bits presently set in the bitset
bs.set(INLINE_FORMAT);
bs.set(ANCHOR);
bs.set(BLOCK_FORMAT);
bs.set(FONT_FORMAT);
bs.set(IMAGES);
} // end configureNormalSet
public static void configureRestrictedSet(BitSet bs)
{
bs.xor(bs); // clears all bits presently set in the bitset
bs.set(INLINE_FORMAT);
} // end configureRestrictedSet
} // end class TagRepository

View File

@ -0,0 +1,45 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Community System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.venice.htmlcheck.impl;
class TagWBR extends SimpleTag
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
TagWBR()
{
super("WBR",false);
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String rewriteTagContents(String contents, boolean is_closing, HTMLCheckerBackend context)
{
context.sendTagMessage("WBR");
return contents; // just let everything pass for now
} // end rewriteTagContents
} // end class TagWBR

Some files were not shown because too many files have changed in this diff Show More