implemented the system administrator function "Import User Accounts," allowing

a sysadmin to create mass quantities of user accounts automatically by
uploading an XML file
This commit is contained in:
Eric J. Bowersox
2001-11-24 05:04:10 +00:00
parent f5a5009932
commit 4e251e72e1
29 changed files with 2285 additions and 922 deletions

View File

@@ -49,7 +49,7 @@ public class StringUtil
* @return The SQL-encoded equivalent of <CODE>str</CODE>. If <CODE>str</CODE> is
* <B><CODE>null</CODE></B>, returns <B><CODE>null</CODE></B>.
*/
public static String encodeStringSQL(String str)
public static final String encodeStringSQL(String str)
{
if (str==null)
return null; // safety feature
@@ -81,7 +81,7 @@ public class StringUtil
* @return The HTML-encoded equivalent of <CODE>str</CODE>. If <CODE>str</CODE> is
* <B><CODE>null</CODE></B>, returns <B><CODE>null</CODE></B>.
*/
public static String encodeHTML(String str)
public static final String encodeHTML(String str)
{
if (str==null)
return null; // safety feature
@@ -134,7 +134,7 @@ public class StringUtil
* @return <B><CODE>true</CODE></B> if the given string is <B><CODE>null</CODE></B> or a string of
* length 0, <B><CODE>false</CODE></B> otherwise.
*/
public static boolean isStringEmpty(String s)
public static final boolean isStringEmpty(String s)
{
return ((s==null) || (s.length()==0));
@@ -157,7 +157,7 @@ public class StringUtil
* of the <CODE>find</CODE> string will be deleted.
* @return The <CODE>base</CODE> string with all replacements made as detailed above.
*/
public static String replaceAllInstances(String base, String find, String replace)
public static final String replaceAllInstances(String base, String find, String replace)
{
if ((base==null) || isStringEmpty(find))
return base; // safety feature
@@ -204,7 +204,7 @@ public class StringUtil
* <CODE>base</CODE>.
* @return The <CODE>base</CODE> string with all variable substitutions made as detailed above.
*/
public static String replaceAllVariables(String base, Map vars)
public static final String replaceAllVariables(String base, Map vars)
{
if ((base==null) || (vars==null) || (vars.size()==0))
return base; // safety feature
@@ -244,5 +244,39 @@ public class StringUtil
} // end replaceAllVariables
public static final String join(Object[] arr, String separator)
{
StringBuffer buf = null;
for (int i=0; i<arr.length; i++)
{ // put it all together
if (buf==null)
buf = new StringBuffer(arr[i].toString());
else
buf.append(separator).append(arr[i].toString());
} // end for
return (buf==null) ? null : buf.toString();
} // end join
public static final String join(List l, String separator)
{
StringBuffer buf = null;
Iterator it = l.iterator();
while (it.hasNext())
{ // put it all together
Object o = it.next();
if (buf==null)
buf = new StringBuffer(o.toString());
else
buf.append(separator).append(o.toString());
} // end for
return (buf==null) ? null : buf.toString();
} // end join
} // end class StringUtil

View File

@@ -18,7 +18,9 @@
package com.silverwrist.venice.core;
import java.util.List;
import com.silverwrist.venice.except.AccessError;
import com.silverwrist.venice.except.DataException;
import com.silverwrist.venice.security.Role;
public interface AdminOperations
{
@@ -38,4 +40,8 @@ public interface AdminOperations
public abstract void setProperties(GlobalProperties props) throws DataException;
public abstract AdminUserContext createNewAccount(String username, String password, String reminder,
boolean verify_email, boolean lockout, Role base_role,
String description) throws DataException, AccessError;
} // end interface AdminOperations

View File

@@ -20,6 +20,7 @@ package com.silverwrist.venice.core;
import java.io.InputStream;
import java.util.Date;
import java.sql.Connection;
import com.silverwrist.venice.util.VCard;
public interface ContactInfo
{
@@ -123,4 +124,6 @@ public interface ContactInfo
public abstract boolean getModified();
public abstract void importVCard(VCard vc);
} // end interface ContactInfo

View File

@@ -25,6 +25,7 @@ import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.Role;
class AdminOperationsImpl implements AdminOperations
{
@@ -151,4 +152,30 @@ class AdminOperationsImpl implements AdminOperations
} // end setProperties
public AdminUserContext createNewAccount(String username, String password, String reminder,
boolean verify_email, boolean lockout, Role base_role,
String description) throws DataException, AccessError
{
if (logger.isDebugEnabled())
logger.debug("createNewAccount(\"" + username + "\",<password>,<reminder>)...");
if (base_role==null)
base_role = env.getDefaultRole("Global.NewUser");
// Create the user account.
ReturnNewUser rnu = UserContextImpl.createAccount(env,env.getUser().userRemoteAddress(),username,
password,reminder,verify_email,lockout,0,base_role,
description);
// Need to create a normal user context here for just a minute to autojoin the communities.
UserContextImpl rc = new UserContextImpl(env);
rc.loadNewUser("0.0.0.0",rnu.getUserID(),base_role.getLevel(),username,0,rnu.getCreationDate(),
rnu.getCreationDate());
rc.autoJoinCommunities();
// Now reload the user context and return it.
return AdminUserContextImpl.getAdminUserContext(env,rnu.getUserID());
} // end createNewAccount
} // end class AdminOperationsImpl

View File

@@ -133,18 +133,7 @@ class AdminUserContextImpl implements AdminUserContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -185,18 +174,7 @@ class AdminUserContextImpl implements AdminUserContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -249,18 +227,7 @@ class AdminUserContextImpl implements AdminUserContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -301,18 +268,7 @@ class AdminUserContextImpl implements AdminUserContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -382,18 +338,7 @@ class AdminUserContextImpl implements AdminUserContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end if
@@ -427,18 +372,7 @@ class AdminUserContextImpl implements AdminUserContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -481,18 +415,7 @@ class AdminUserContextImpl implements AdminUserContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -535,18 +458,7 @@ class AdminUserContextImpl implements AdminUserContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally

View File

@@ -566,18 +566,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -682,18 +671,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -730,18 +708,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -778,18 +745,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -826,18 +782,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1023,18 +968,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1077,18 +1011,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1203,18 +1126,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1296,18 +1208,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1397,18 +1298,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1888,18 +1778,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -2091,18 +1970,7 @@ class CommunityCoreData implements CommunityData, CommunityDataBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally

View File

@@ -450,18 +450,7 @@ class ConferenceCommunityContextImpl implements ConferenceCommunityContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -570,18 +559,7 @@ class ConferenceCommunityContextImpl implements ConferenceCommunityContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally

View File

@@ -512,18 +512,7 @@ class ConferenceCoreData implements ConferenceData
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -568,18 +557,7 @@ class ConferenceCoreData implements ConferenceData
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -680,18 +658,7 @@ class ConferenceCoreData implements ConferenceData
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -768,18 +735,7 @@ class ConferenceCoreData implements ConferenceData
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -860,18 +816,7 @@ class ConferenceCoreData implements ConferenceData
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1021,18 +966,7 @@ class ConferenceCoreData implements ConferenceData
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1287,18 +1221,7 @@ class ConferenceCoreData implements ConferenceData
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1488,18 +1411,7 @@ class ConferenceCoreData implements ConferenceData
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally

View File

@@ -21,10 +21,12 @@ import java.io.*;
import java.sql.*;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.core.internals.EnvEngine;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.util.*;
class ContactInfoImpl implements ContactInfo, Stashable
{
@@ -101,7 +103,7 @@ class ContactInfoImpl implements ContactInfo, Stashable
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(ContactInfoImpl.class.getName());
private static Category logger = Category.getInstance(ContactInfoImpl.class);
/*--------------------------------------------------------------------------------
* Attributes
@@ -691,6 +693,221 @@ class ContactInfoImpl implements ContactInfo, Stashable
} // end getModified
public void importVCard(VCard vc)
{
// Import the easy fields first.
if (vc.getGivenName()!=null)
given_name = vc.getGivenName();
if (vc.getFamilyName()!=null)
family_name = vc.getFamilyName();
if (vc.getMiddleName()!=null)
{ // modify the middle initial
String tmp = vc.getMiddleName();
middle_initial = (StringUtil.isStringEmpty(tmp) ? ' ' : tmp.charAt(0));
} // end if
if (vc.getPrefix()!=null)
prefix = vc.getPrefix();
if (vc.getSuffix()!=null)
suffix = vc.getSuffix();
if (vc.getOrganizationName()!=null)
company = vc.getOrganizationName();
if (vc.getURL()!=null)
url = vc.getURL();
// Look for an address.
Boolean hide = null;
VCardAddress addr = vc.getPreferredAddress();
if (addr!=null)
{ // always hide the address if it's a home one
if (addr.isHomeAddress())
hide = Boolean.TRUE;
} // end if
if (addr==null)
addr = vc.getWorkAddress();
if (addr==null)
{ // get home address (and hide it)
addr = vc.getHomeAddress();
if (addr!=null)
hide = Boolean.TRUE;
} // end if
if (addr==null)
{ // get any other address (and hide it)
addr = vc.getAnyAddress();
if ((addr!=null) && addr.isHomeAddress())
hide = Boolean.TRUE;
} // end if
if (addr!=null)
{ // fill in the address values here
if (addr.getPOBox()!=null)
{ // we have a PO Box...
if (addr.getExtension()!=null)
{ // and we have an extension too!
if (addr.getStreet()!=null)
{ // Address line 1 is PO Box + extension, line 2 is street
addr1 = "PO Box " + addr.getPOBox() + ", " + addr.getExtension();
addr2 = addr.getStreet();
} // end if
else
{ // Address line 1 is PO box, line 2 is extension
addr1 = "PO Box " + addr.getPOBox();
addr2 = addr.getExtension();
} // end else
} // end if
else
{ // Address line 1 is PO Box, line 2 is street
addr1 = "PO Box " + addr.getPOBox();
addr2 = addr.getStreet();
} // end else
} // end if
else
{ // PO Box not present
if (addr.getExtension()!=null)
{ // Address line 1 is extension, line 2 is street
addr1 = addr.getExtension();
addr2 = addr.getStreet();
} // end if
else
{ // Address line 1 is street, line 2 is null
addr1 = addr.getStreet();
addr2 = null;
} // end else
} // end else
// Set the other fields.
if (addr.getLocality()!=null)
locality = addr.getLocality();
if (addr.getRegion()!=null)
region = addr.getRegion();
if (addr.getPostalCode()!=null)
postal_code = addr.getPostalCode();
if ((addr.getCountry()!=null) && (addr.getCountry().length()==2))
country = addr.getCountry().toUpperCase();
// Set hide flag if appropriate.
if (hide!=null)
private_addr = hide.booleanValue();
} // end if (loading address)
// Figure out which phone number to put in.
hide = null;
VCardPhone p = vc.getPreferredPhone();
if (p!=null)
{ // hide the phone if it's a home phone
if (p.isHomePhone())
hide = Boolean.TRUE;
} // end if
if (p==null)
p = vc.getWorkPhone();
if (p==null)
{ // try the home phone (and hide it)
p = vc.getHomePhone();
if (p!=null)
hide = Boolean.TRUE;
} // end if
if (p==null)
{ // now try and get any voice phone
p = vc.getVoicePhone();
if ((p!=null) && p.isHomePhone())
hide = Boolean.TRUE;
} // end if
if (p==null)
{ // now try and get any phone
p = vc.getAnyPhone();
if ((p!=null) && (p.isHomePhone() || p.isCellPhone() || p.isPCSPhone()))
hide = Boolean.TRUE;
} // end if
if (p!=null)
phone = p.getNumber();
// now get the cellphone
p = vc.getCellPhone();
if (p!=null)
mobile = p.getNumber();
if (hide!=null) // save hide value
private_phone = hide.booleanValue();
// now get the fax number
hide = null;
p = vc.getPreferredFax();
if (p!=null)
{ // hide the phone if it's a home phone
if (p.isHomePhone())
hide = Boolean.TRUE;
} // end if
if (p==null)
p = vc.getWorkFax();
if (p==null)
{ // try the home phone (and hide it)
p = vc.getHomeFax();
if (p!=null)
hide = Boolean.TRUE;
} // end if
if (p==null)
{ // now try and get any fax
p = vc.getAnyFax();
if ((p!=null) && (p.isHomePhone()))
hide = Boolean.TRUE;
} // end if
// save off the fax number
if (p!=null)
fax = p.getNumber();
if (hide!=null)
private_fax = hide.booleanValue();
// Get the internet address we wish to use.
hide = null;
VCardEmail em = vc.getPreferredEmail();
if (em!=null)
{ // make sure the email is an Internet address!
if (!(em.isInternetEmail()))
em = null;
else if (em.isHomeEmail())
hide = Boolean.TRUE;
} // end if
if (em==null)
{ // get an Internet email address somehow
em = vc.getInternetEmail();
if ((em!=null) && em.isHomeEmail())
hide = Boolean.TRUE;
} // end if
// Set the E-mail address.
if (em!=null)
email = em.getAddress();
if (hide!=null)
private_email = hide.booleanValue();
is_modified = true; // we definitely modified things now!
} // end importVCard
/*--------------------------------------------------------------------------------
* Implementations from interface Stashable
*--------------------------------------------------------------------------------

View File

@@ -530,18 +530,7 @@ class TopicMessageUserContextImpl implements TopicMessageContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -659,18 +648,7 @@ class TopicMessageUserContextImpl implements TopicMessageContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -766,18 +744,7 @@ class TopicMessageUserContextImpl implements TopicMessageContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -946,18 +913,7 @@ class TopicMessageUserContextImpl implements TopicMessageContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1072,18 +1028,7 @@ class TopicMessageUserContextImpl implements TopicMessageContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally

View File

@@ -324,18 +324,7 @@ class TopicUserContextImpl implements TopicContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -383,18 +372,7 @@ class TopicUserContextImpl implements TopicContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -813,18 +791,7 @@ class TopicUserContextImpl implements TopicContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -925,18 +892,7 @@ class TopicUserContextImpl implements TopicContext
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally

View File

@@ -457,18 +457,7 @@ class UserContextImpl implements UserContext, UserBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end if
@@ -493,7 +482,7 @@ class UserContextImpl implements UserContext, UserBackend
{ // the confirmation number is wrong
logger.warn("...confirmation number incorrect");
ar = new AuditRecord(AuditRecord.VERIFY_FAIL,uid,remote_addr,"Invalid confirmation number");
env.getEngine().saveAuditRecord(ar);
env.saveAuditRecord(ar);
throw new AccessError("Confirmation number is incorrect. Please try again.");
} // end if
@@ -526,18 +515,7 @@ class UserContextImpl implements UserContext, UserBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end if
@@ -591,18 +569,7 @@ class UserContextImpl implements UserContext, UserBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end if
@@ -726,18 +693,7 @@ class UserContextImpl implements UserContext, UserBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end if
@@ -838,18 +794,7 @@ class UserContextImpl implements UserContext, UserBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
@@ -1413,18 +1358,7 @@ class UserContextImpl implements UserContext, UserBackend
} // 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
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end if
@@ -1633,6 +1567,178 @@ class UserContextImpl implements UserContext, UserBackend
} // end autoJoinCommunities
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
static ReturnNewUser createAccount(EnvEngine env, String remote_addr, String username, String password,
String reminder, boolean verify_email, boolean lockout, int confirm_num,
Role base_role, String description)
throws AccessError, DataException
{
String encode_username = SQLUtil.encodeString(username);
int new_uid; // new user ID - return from this function
java.util.Date created; // date created - return from this function
Connection conn = null;
AuditRecord ar = null;
try
{ // first, lock a bunch of tables for the purpose of this operation
conn = env.getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES users WRITE, userprefs WRITE, propuser WRITE, sigmember WRITE, "
+ "sideboxes WRITE, confhotlist WRITE;");
try
{ // make sure the user account doesn't already exist
ResultSet rs = stmt.executeQuery("SELECT uid FROM users WHERE username = '" + encode_username + "';");
if (rs.next())
{ // the user account already exists
logger.warn("username \"" + username + "\" already exists");
throw new AccessError("That user name already exists. Please try again.");
} // end if
// Insert a new record for this user
PasswordHash phash = new PasswordHash(password);
StringBuffer sql =
new StringBuffer("INSERT INTO users (username, passhash, verify_email, lockout, email_confnum, "
+ "base_lvl, created, lastaccess, passreminder, description) VALUES ('");
sql.append(encode_username).append("', '").append(phash.toString()).append("', ");
sql.append(verify_email ? '1' : '0').append(", ").append(lockout ? '1' : '0').append(", ");
sql.append(confirm_num).append(", ").append(base_role.getLevel()).append(", '");
created = new java.util.Date();
sql.append(SQLUtil.encodeDate(created)).append("', '").append(SQLUtil.encodeDate(created));
sql.append("', ").append(SQLUtil.encodeStringArg(reminder)).append(", ");
sql.append(SQLUtil.encodeStringArg(description)).append(");");
stmt.executeUpdate(sql.toString());
// what is the new user ID?
rs = stmt.executeQuery("SELECT LAST_INSERT_ID();");
if (!(rs.next()))
{ // the readback failed...
logger.error("readback of new user's UID failed");
throw new DataException("unable to read back new user ID");
} // end if
new_uid = rs.getInt(1);
if (logger.isDebugEnabled())
logger.debug("...created user \"" + username + "\" with UID " + new_uid);
// add a UserPrefs record for this user, too
sql.setLength(0);
sql.append("INSERT INTO userprefs (uid) VALUES (").append(new_uid).append(");");
stmt.executeUpdate(sql.toString());
if (logger.isDebugEnabled())
logger.debug("...created userprefs");
// add a properties configuration for this user
rs = stmt.executeQuery("SELECT propuser.ndx, propuser.data FROM propuser, users WHERE "
+ "propuser.uid = users.uid AND users.is_anon = 1;");
sql.setLength(0);
while (rs.next())
{ // set up to insert into the propuser table
if (sql.length()==0)
sql.append("INSERT INTO propuser (uid, ndx, data) VALUES ");
else
sql.append(", ");
sql.append("(").append(new_uid).append(", ").append(rs.getInt(1)).append(", '");
sql.append(SQLUtil.encodeString(rs.getString(2))).append("')");
} // end while
if (sql.length()>0)
{ // execute the big update
sql.append(';');
stmt.executeUpdate(sql.toString());
} // end if
if (logger.isDebugEnabled())
logger.debug("...created user properties");
// get the sidebox configuration for this user
rs = stmt.executeQuery("SELECT sideboxes.boxid, sideboxes.sequence FROM sideboxes, "
+ "users WHERE sideboxes.uid = users.uid AND users.is_anon = 1;");
sql.setLength(0);
while (rs.next())
{ // set up to insert into the sideboxes table
if (sql.length()==0)
sql.append("INSERT INTO sideboxes (uid, boxid, sequence) VALUES ");
else
sql.append(", ");
sql.append("(").append(new_uid).append(", ").append(rs.getInt(1)).append(", ");
sql.append(rs.getInt(2)).append(')');
} // end while
if (sql.length()>0)
{ // execute the big update
sql.append(';');
stmt.executeUpdate(sql.toString());
} // end if
if (logger.isDebugEnabled())
logger.debug("...loaded default sidebox config");
// get the hotlist configuration for this user
rs = stmt.executeQuery("SELECT confhotlist.sequence, confhotlist.sigid, confhotlist.confid FROM "
+ "confhotlist, users WHERE confhotlist.uid = users.uid AND users.is_anon = 1;");
sql.setLength(0);
while (rs.next())
{ // set up to insert into the confhotlist table
if (sql.length()==0)
sql.append("INSERT INTO confhotlist (uid, sequence, sigid, confid) VALUES ");
else
sql.append(", ");
sql.append('(').append(new_uid).append(", ").append(rs.getInt(1)).append(", ").append(rs.getInt(2));
sql.append(", ").append(rs.getInt(3)).append(')');
} // end while
if (sql.length()>0)
{ // execute the big update
sql.append(';');
stmt.executeUpdate(sql.toString());
} // end if
if (logger.isDebugEnabled())
logger.debug("...loaded default hotlist config");
} // end try
finally
{ // make sure the tables get unlocked before we go
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
// the operation was a success - give back an audit record
ar = new AuditRecord(AuditRecord.ACCOUNT_CREATE,new_uid,remote_addr);
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error creating user: " + e.getMessage(),e);
throw new DataException("unable to create user record: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
AuditRecord.store(conn,ar);
env.releaseConnection(conn);
} // end finally
return new ReturnNewUser(new_uid,created);
} // end createAccount
/*--------------------------------------------------------------------------------
* Static initializer
*--------------------------------------------------------------------------------

View File

@@ -1010,180 +1010,21 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
throws DataException, AccessError
{
checkInitialized();
Connection conn = null;
AuditRecord ar = null;
String encode_username = SQLUtil.encodeString(username);
Role new_role = global_security.getDefaultRole("Global.NewUser");
// email confirmation # is between 1000000 and 9999999
int confirm_num = getNewConfirmationNumber();
int new_uid;
java.util.Date created = null;
if (logger.isDebugEnabled())
logger.debug("createNewAccount(\"" + username + "\",<password>,<reminder>)...");
try
{ // look to see if the user name is already present
conn = env.getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES users WRITE, userprefs WRITE, propuser WRITE, sigmember WRITE, "
+ "sideboxes WRITE, confhotlist WRITE;");
try
{ // make sure the user name isn't there already
ResultSet rs = stmt.executeQuery("SELECT uid FROM users WHERE username = '" + encode_username + "';");
if (rs.next())
{ // the user account already exists
logger.warn("username \"" + username + "\" already exists");
throw new AccessError("That user name already exists. Please try again.");
} // end if
// perform the insert of the user's new data
PasswordHash phash = new PasswordHash(password);
StringBuffer sql = new StringBuffer("INSERT INTO users (username, passhash, email_confnum, "
+ "base_lvl, created, lastaccess, passreminder) VALUES ('");
sql.append(encode_username).append("', '").append(phash.toString()).append("', ");
sql.append(confirm_num).append(", ").append(new_role.getLevel()).append(", '");
created = new java.util.Date();
sql.append(SQLUtil.encodeDate(created)).append("', '").append(SQLUtil.encodeDate(created));
sql.append("', ").append(SQLUtil.encodeStringArg(reminder)).append(");");
stmt.executeUpdate(sql.toString());
// what is the new user ID?
rs = stmt.executeQuery("SELECT LAST_INSERT_ID();");
if (!(rs.next()))
{ // the readback failed...
logger.error("readback of new user's UID failed");
throw new DataException("unable to read back new user ID");
} // end if
new_uid = rs.getInt(1);
if (logger.isDebugEnabled())
logger.debug("...created user \"" + username + "\" with UID " + new_uid);
// add a UserPrefs record for this user, too
sql.setLength(0);
sql.append("INSERT INTO userprefs (uid) VALUES (").append(new_uid).append(");");
stmt.executeUpdate(sql.toString());
if (logger.isDebugEnabled())
logger.debug("...created userprefs");
// add a properties configuration for this user
rs = stmt.executeQuery("SELECT propuser.ndx, propuser.data FROM propuser, users WHERE "
+ "propuser.uid = users.uid AND users.is_anon = 1;");
sql.setLength(0);
while (rs.next())
{ // set up to insert into the propuser table
if (sql.length()==0)
sql.append("INSERT INTO propuser (uid, ndx, data) VALUES ");
else
sql.append(", ");
sql.append("(").append(new_uid).append(", ").append(rs.getInt(1)).append(", '");
sql.append(SQLUtil.encodeString(rs.getString(2))).append("')");
} // end while
if (sql.length()>0)
{ // execute the big update
sql.append(';');
stmt.executeUpdate(sql.toString());
} // end if
if (logger.isDebugEnabled())
logger.debug("...created user properties");
// get the sidebox configuration for this user
rs = stmt.executeQuery("SELECT sideboxes.boxid, sideboxes.sequence FROM sideboxes, "
+ "users WHERE sideboxes.uid = users.uid AND users.is_anon = 1;");
sql.setLength(0);
while (rs.next())
{ // set up to insert into the sideboxes table
if (sql.length()==0)
sql.append("INSERT INTO sideboxes (uid, boxid, sequence) VALUES ");
else
sql.append(", ");
sql.append("(").append(new_uid).append(", ").append(rs.getInt(1)).append(", ");
sql.append(rs.getInt(2)).append(')');
} // end while
if (sql.length()>0)
{ // execute the big update
sql.append(';');
stmt.executeUpdate(sql.toString());
} // end if
if (logger.isDebugEnabled())
logger.debug("...loaded default sidebox config");
// get the hotlist configuration for this user
rs = stmt.executeQuery("SELECT confhotlist.sequence, confhotlist.sigid, confhotlist.confid FROM "
+ "confhotlist, users WHERE confhotlist.uid = users.uid AND users.is_anon = 1;");
sql.setLength(0);
while (rs.next())
{ // set up to insert into the confhotlist table
if (sql.length()==0)
sql.append("INSERT INTO confhotlist (uid, sequence, sigid, confid) VALUES ");
else
sql.append(", ");
sql.append('(').append(new_uid).append(", ").append(rs.getInt(1)).append(", ").append(rs.getInt(2));
sql.append(", ").append(rs.getInt(3)).append(')');
} // end while
if (sql.length()>0)
{ // execute the big update
sql.append(';');
stmt.executeUpdate(sql.toString());
} // end if
if (logger.isDebugEnabled())
logger.debug("...loaded default hotlist config");
} // end try
finally
{ // make sure the tables get unlocked before we go
Statement ulk_stmt = conn.createStatement();
ulk_stmt.executeUpdate("UNLOCK TABLES;");
} // end finally
// the operation was a success - give back an audit record
ar = new AuditRecord(AuditRecord.ACCOUNT_CREATE,new_uid,remote_addr);
} // end try
catch (SQLException e)
{ // database error - this is a DataException
logger.error("DB error creating user: " + e.getMessage(),e);
throw new DataException("unable to create user record: " + 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
env.releaseConnection(conn);
} // end finally
// Create the user account.
ReturnNewUser rnu = UserContextImpl.createAccount(env,remote_addr,username,password,reminder,false,
false,confirm_num,new_role,null);
// create a new context for the user (they're now effectively logged in)
UserContextImpl rc = new UserContextImpl(env);
rc.loadNewUser(remote_addr,new_uid,new_role.getLevel(),username,confirm_num,created,created);
rc.loadNewUser(remote_addr,rnu.getUserID(),new_role.getLevel(),username,confirm_num,rnu.getCreationDate(),
rnu.getCreationDate());
rc.autoJoinCommunities(); // EJB 4/14/2001
if (logger.isDebugEnabled())
logger.debug("...created new user context");
@@ -1731,33 +1572,6 @@ public class VeniceEngineImpl implements VeniceEngine, EngineBackend
} // end detachConferenceDataObject
public void saveAuditRecord(AuditRecord ar)
{
checkInitialized();
Connection conn = null;
if (ar==null)
return; // don't store a null record
try
{ // get a connection and use it to store the audit record
conn = env.getConnection();
ar.store(conn);
} // end try
catch (SQLException e)
{ // just log an error if we screwed up
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
env.releaseConnection(conn);
} // end finally
} // end saveAuditRecord
public void registerNewConference(ConferenceData conf)
{
checkInitialized();

View File

@@ -77,8 +77,6 @@ public interface EngineBackend
public abstract void detachConferenceDataObject(int confid);
public abstract void saveAuditRecord(AuditRecord ar);
public abstract void registerNewConference(ConferenceData conf);
public abstract HTMLChecker createCheckerObject(int type);

View File

@@ -20,6 +20,7 @@ package com.silverwrist.venice.core.internals;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.*;
import com.silverwrist.venice.core.SecurityInfo;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.except.AccessError;
@@ -28,6 +29,13 @@ import com.silverwrist.venice.svc.ServiceControl;
public class EnvEngine
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(EnvEngine.class);
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
@@ -141,4 +149,30 @@ public class EnvEngine
} // end getSecurityInfo
public final void saveAuditRecord(AuditRecord ar)
{
Connection conn = null;
if (ar==null)
return; // don't store a null record
try
{ // get a connection and use it to store the audit record
conn = datapool.getConnection();
ar.store(conn);
} // end try
catch (SQLException e)
{ // just log an error if we screwed up
logger.error("DB error saving audit record: " + e.getMessage(),e);
} // end catch
finally
{ // make sure the connection is released before we go
datapool.releaseConnection(conn);
} // end finally
} // end saveAuditRecord
} // end class EnvEngine

View File

@@ -0,0 +1,61 @@
/*
* 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 Communities 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.internals;
import java.util.Date;
public class ReturnNewUser
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private int uid;
private Date created;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ReturnNewUser(int uid, Date created)
{
this.uid = uid;
this.created = created;
} // end class ReturnNewUser
/*--------------------------------------------------------------------------------
* External getters
*--------------------------------------------------------------------------------
*/
public final int getUserID()
{
return uid;
} // end getUserID
public final Date getCreationDate()
{
return created;
} // end getCreationDate
} // end class ReturnNewUser

View File

@@ -19,6 +19,7 @@ package com.silverwrist.venice.security;
import java.sql.*;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.venice.db.SQLUtil;
import com.silverwrist.venice.core.AuditData;
import com.silverwrist.venice.except.DataException;
@@ -104,6 +105,13 @@ public class AuditRecord implements AuditData
} // end class DescrStringCache
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(AuditRecord.class);
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
@@ -399,4 +407,20 @@ public class AuditRecord implements AuditData
} // end getAuditRecordCount
public static void store(Connection conn, AuditRecord ar)
{
try
{ // save off the audit record
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
} // end store
} // end class AuditRecord

View File

@@ -24,6 +24,7 @@ import com.silverwrist.util.DOMElementHelper;
import com.silverwrist.venice.except.AccessError;
import com.silverwrist.venice.except.ConfigException;
import com.silverwrist.venice.svc.SecurityMonitorEnvironment;
import com.silverwrist.venice.util.XMLLoader;
/**
* A <CODE>SecurityMonitor</CODE> which is configured by means of XML data, supplied by means of a Venice
@@ -118,28 +119,17 @@ public class StaticSecurityMonitor implements SecurityMonitor
*/
public StaticSecurityMonitor(Element cfg, SecurityMonitorEnvironment env) throws ConfigException
{
XMLLoader loader = XMLLoader.get();
boolean set_root_monitor = false;
if (!(cfg.getTagName().equals("security-definition")))
{ // not the right kind of element!
logger.fatal("security monitor config is not a <security-definition/> element");
throw new ConfigException("configuration must be a <security-definition/>",cfg);
} // end if
DOMElementHelper root_h = new DOMElementHelper(cfg);
if (root_h.hasAttribute("id"))
id = cfg.getAttribute("id");
else
{ // no id= attribute? that's bad!
logger.fatal("security monitor has no id= attribute");
throw new ConfigException("<security-definition/> must have an id= attribute",cfg);
} // end else
loader.configVerifyTagName(cfg,"security-definition"); // verify the tag name
// Get the new security monitor's ID.
id = loader.configGetAttribute(cfg,"id");
if (logger.isDebugEnabled())
logger.debug("defining new StaticSecurityMonitor with id=" + id);
// Make sure this security monitor isn't already defined.
if (env.isMonitorDefined(id))
{ // the monitor with this ID has already been defined!
logger.fatal("security monitor with id=" + id + " is already defined!");
@@ -147,8 +137,10 @@ public class StaticSecurityMonitor implements SecurityMonitor
} // end if
// See if the security monitor has a parent attribute.
DOMElementHelper root_h = new DOMElementHelper(cfg);
if (root_h.hasAttribute("parent"))
{ // find our parent
{ // get the parent and determine if it exists or not
String parent_id = cfg.getAttribute("parent");
parent = env.getMonitor(parent_id);
if (parent==null)
@@ -158,19 +150,13 @@ public class StaticSecurityMonitor implements SecurityMonitor
} // end if
// Determine the new scope for this security monitor.
int my_scope = parent.getScopeInfo().getScope();
int my_offset = DEFAULT_SCOPE_OFFSET;
if (root_h.hasAttribute("offset"))
{ // get the offset value and compare it
Integer tmp = root_h.getAttributeInt("offset");
if (tmp==null)
{ // the offset was not an integer value - bye now!
logger.fatal("offset= value was not an integer");
throw new ConfigException("offset= attribute of <security-definition/> must be an integer");
} // end if
my_offset = tmp.intValue();
{ // load the offset attribute and make sure it's in range
my_offset = loader.configGetAttributeInt(cfg,"offset");
if (my_offset<1)
{ // the offset must be greater than or equal to 1!
logger.fatal("offset= value (" + my_offset + ") was out of range");
@@ -180,6 +166,7 @@ public class StaticSecurityMonitor implements SecurityMonitor
} // end if
// Determine the final scope and check its validity.
my_scope += my_offset;
if (!(ScopeInfo.isValidScope(my_scope)))
{ // resulting scope is out of range!
@@ -191,7 +178,7 @@ public class StaticSecurityMonitor implements SecurityMonitor
// allocate a scope info object with the new scope
scope = new ScopeInfo(my_scope);
} // end if
} // end if (security monitor has parent)
else
{ // this must be the root security monitor!
if (env.isRootMonitorDefined())
@@ -206,7 +193,7 @@ public class StaticSecurityMonitor implements SecurityMonitor
scope = new ScopeInfo(0);
parent = PrimordialSecurityMonitor.get();
} // end else
} // end else (security monitor is root)
// get the defined roles
Element sect = root_h.getSubElement("defined-roles");
@@ -268,19 +255,10 @@ public class StaticSecurityMonitor implements SecurityMonitor
if ((n.getNodeType()==Node.ELEMENT_NODE) && (n.getNodeName().equals("list")))
{ // create the role list and add it to the temporary map
// but first, get the ID
DOMElementHelper hn = new DOMElementHelper((Element)n);
String list_id;
if (hn.hasAttribute("id"))
list_id = id + "." + hn.getElement().getAttribute("id");
else
{ // no id= attribute - can't do anything with this
logger.fatal("<list/> element found with no id= attribute!");
throw new ConfigException("no id= attribute on defined <list/> element",hn.getElement());
} // end else
String list_id = id + "." + loader.configGetAttribute((Element)n,"id");
// now actually build the list and insert it
List rlist = buildList(hn.getElement(),list_id,tmp_default_roles,tmp_static_permissions,
List rlist = buildList((Element)n,list_id,tmp_default_roles,tmp_static_permissions,
tmp_dynamic_permissions);
tmp_lists.put(list_id,rlist);
@@ -357,99 +335,84 @@ public class StaticSecurityMonitor implements SecurityMonitor
private Role createRole(Element e) throws ConfigException
{
String symbol, text;
XMLLoader loader = XMLLoader.get();
// Get the role symbol and automagically scope it.
String symbol = id + "." + loader.configGetAttribute(e,"id");
// Look for the value.
String value_str = loader.configGetAttribute(e,"value").trim().toUpperCase();
int level;
if (value_str.equals("LMIN"))
level = scope.getLowBandLow();
else if (value_str.equals("LMAX"))
level = scope.getLowBandHigh();
else if (value_str.equals("HMIN"))
level = scope.getHighBandLow();
else if (value_str.equals("HMAX"))
level = scope.getHighBandHigh();
else if ( value_str.startsWith("L+") || value_str.startsWith("L-") || value_str.startsWith("H+")
|| value_str.startsWith("H-"))
{ // take the characters following the 2-character prefix and convert them to an integer
int offset;
try
{ // convert the value and make sure it's not less than 0
offset = Integer.parseInt(value_str.substring(2));
if (offset<0)
{ // don't want it less than zero here!
logger.fatal("offset value " + offset + " was out of range");
throw new ConfigException("offset value= attribute for <role/> was out of range",e);
} // end if
DOMElementHelper h = new DOMElementHelper(e);
if (h.hasAttribute("id"))
symbol = id + "." + e.getAttribute("id"); // symbols get automagically scoped
} // end try
catch (NumberFormatException nfe)
{ // not a numeric offset value
logger.fatal("offset value \"" + value_str + "\" was not numeric");
throw new ConfigException("offset value= attribute for <role/> was not properly numeric",e);
} // end catch
if (value_str.charAt(1)=='-')
offset = -offset; // compute as negative offset
try
{ // now use the scope to compute the level!
level = scope.getLevel((value_str.charAt(0)=='H'),offset);
} // end try
catch (IllegalArgumentException iae)
{ // we landed with a value outside the scope!
logger.fatal("offset value \"" + value_str + "\" was not in the scope");
throw new ConfigException("offset value= attribute for <role/> was not within the scope",e);
} // end catch
} // end else if
else
{ // no role defined
logger.fatal("<role/> defined with no id= attribute!");
throw new ConfigException("no id= attribute for a <role/>",e);
{ // just a straight numeric level
try
{ // parse it out and give it a scope check
level = Integer.parseInt(value_str);
if (!(scope.isInScope(level)))
{ // not in the right scope - can't help you, pal!
logger.fatal("level value \"" + level + "\" was not in the scope");
throw new ConfigException("level value= attribute for <role/> was not within the scope",e);
} // end else
} // end if
if (h.hasAttribute("value"))
{ // get the value and parse it out
String value_str = e.getAttribute("value").trim().toUpperCase();
if (value_str.equals("LMIN"))
level = scope.getLowBandLow();
else if (value_str.equals("LMAX"))
level = scope.getLowBandHigh();
else if (value_str.equals("HMIN"))
level = scope.getHighBandLow();
else if (value_str.equals("HMAX"))
level = scope.getHighBandHigh();
else if ( value_str.startsWith("L+") || value_str.startsWith("L-") || value_str.startsWith("H+")
|| value_str.startsWith("H-"))
{ // take the characters following the 2-character prefix and convert them to an integer
int offset;
try
{ // convert the value and make sure it's not less than 0
offset = Integer.parseInt(value_str.substring(2));
if (offset<0)
{ // don't want it less than zero here!
logger.fatal("offset value " + offset + " was out of range");
throw new ConfigException("offset value= attribute for <role/> was out of range",e);
} // end if
} // end try
catch (NumberFormatException nfe)
{ // the level was not numeric
logger.fatal("level value \"" + value_str + "\" was not numeric");
throw new ConfigException("level value= attribute for <role/> was not properly numeric",e);
} // end try
catch (NumberFormatException nfe)
{ // not a numeric offset value
logger.fatal("offset value \"" + value_str + "\" was not numeric");
throw new ConfigException("offset value= attribute for <role/> was not properly numeric",e);
} // end catch
if (value_str.charAt(1)=='-')
offset = -offset; // compute as negative offset
try
{ // now use the scope to compute the level!
level = scope.getLevel((value_str.charAt(0)=='H'),offset);
} // end try
catch (IllegalArgumentException iae)
{ // we landed with a value outside the scope!
logger.fatal("offset value \"" + value_str + "\" was not in the scope");
throw new ConfigException("offset value= attribute for <role/> was not within the scope",e);
} // end catch
} // end else if
else
{ // just a straight numeric level
try
{ // parse it out and give it a scope check
level = Integer.parseInt(value_str);
if (!(scope.isInScope(level)))
{ // not in the right scope - can't help you, pal!
logger.fatal("level value \"" + level + "\" was not in the scope");
throw new ConfigException("level value= attribute for <role/> was not within the scope",e);
} // end if
} // end try
catch (NumberFormatException nfe)
{ // the level was not numeric
logger.fatal("level value \"" + value_str + "\" was not numeric");
throw new ConfigException("level value= attribute for <role/> was not properly numeric",e);
} // end catch
} // end else
} // end if
else
{ // no value defined for this role!
logger.fatal("<role/> defined with no value= attribute!");
throw new ConfigException("no value= attribute for a <role/>",e);
} // end catch
} // end else
// Get the text; default to the symbol name if it doesn't exist.
text = h.getElementText();
DOMElementHelper h = new DOMElementHelper(e);
String text = h.getElementText();
if (text==null)
text = symbol;
@@ -461,10 +424,13 @@ public class StaticSecurityMonitor implements SecurityMonitor
private List buildList(Element elem, String listid, Map defaultrole, Map static_perm, Set dynamic_perm)
throws ConfigException
{
XMLLoader loader = XMLLoader.get();
// If there's a permission tag under this list, take it.
DOMElementHelper h = new DOMElementHelper(elem);
Element perm = h.getSubElement("permission");
if (perm!=null)
{ // there's a permission associated with this list, find out what it is
{ // Find out what the permission is.
DOMElementHelper ph = new DOMElementHelper(perm);
if (ph.hasAttribute("role"))
{ // look up the role and make sure it corresponds to one we know
@@ -485,8 +451,9 @@ public class StaticSecurityMonitor implements SecurityMonitor
dynamic_perm.add(listid);
} // end if
// else there's no problem
// else just skip this check
// Begin loading the list elements.
NodeList nl = elem.getChildNodes();
ArrayList rc = new ArrayList(nl.getLength());
boolean have_default = false;
@@ -495,34 +462,25 @@ public class StaticSecurityMonitor implements SecurityMonitor
Node n = nl.item(i);
if ((n.getNodeType()==Node.ELEMENT_NODE) && (n.getNodeName().equals("element")))
{ // look at the attributes of this element node
DOMElementHelper itmh = new DOMElementHelper((Element)n);
Role r = null;
if (itmh.hasAttribute("role"))
{ // convert the string into a role
r = this.getRole(itmh.getElement().getAttribute("role"));
if (r==null)
{ // the role is not defined!
logger.fatal("list <element/> role (" + itmh.getElement().getAttribute("role") + ") not defined");
throw new ConfigException("<element/> inside of <list/> did not use defined role!",
itmh.getElement());
} // end if
String rname = loader.configGetAttribute((Element)n,"role");
Role r = this.getRole(rname);
if (r==null)
{ // the role is not defined!
logger.fatal("list <element/> role (" + rname + ") not defined");
throw new ConfigException("<element/> inside of <list/> did not use defined role!",(Element)n);
} // end if
else
{ // no attribute present
logger.fatal("<element/> defined with no role= attribute!");
throw new ConfigException("no role= attribute for a list <element/>",itmh.getElement());
} // end else
rc.add(r); // add element to defining list
if (itmh.hasAttribute("default"))
// Check and see if this item is a default.
DOMElementHelper nh = new DOMElementHelper((Element)n);
if (nh.hasAttribute("default"))
{ // this is a default item...
if (have_default)
{ // but there can't be two defaults!
logger.fatal("duplicate default= attributes in list <element/> nodes!");
throw new ConfigException("duplicate default= attribute in list <element/>",itmh.getElement());
throw new ConfigException("duplicate default= attribute in list <element/>",nh.getElement());
} // end if
else
@@ -547,55 +505,34 @@ public class StaticSecurityMonitor implements SecurityMonitor
private void processDefault(Element elem, Map defaultrole) throws ConfigException
{
XMLLoader loader = XMLLoader.get();
// Start by getting the default ID.
DOMElementHelper h = new DOMElementHelper(elem);
String def_id = null;
if (h.hasAttribute("id"))
def_id = id + "." + elem.getAttribute("id");
else
{ // no id defined!
logger.fatal("<default/> defined with no id= attribute!");
throw new ConfigException("no id= attribute for a <default/>",elem);
String def_id = id + "." + loader.configGetAttribute(elem,"id");
} // end else
Role r = null;
if (h.hasAttribute("role"))
{ // get the role associated with the item
r = this.getRole(elem.getAttribute("role"));
if (r==null)
{ // no role found - this is an error!
logger.fatal("<default/> role (" + elem.getAttribute("role") + ") not defined");
throw new ConfigException("<default/> did not use defined role!",elem);
} // end if
// Now get the associated default role.
Role r = this.getRole(loader.configGetAttribute(elem,"role"));
if (r==null)
{ // no role found - this is an error!
logger.fatal("<default/> role (" + elem.getAttribute("role") + ") not defined");
throw new ConfigException("<default/> did not use defined role!",elem);
} // end if
else
{ // no role defined!
logger.fatal("<default/> defined with no id= attribute!");
throw new ConfigException("no id= attribute for a <default/>",elem);
} // end else
// and save the default
defaultrole.put(def_id,r);
} // end processDefault
private void processPermission(Element elem, Map static_perm, Set dynamic_perm) throws ConfigException
{
XMLLoader loader = XMLLoader.get();
// Start by getting the permission ID.
String perm_id = id + "." + loader.configGetAttribute(elem,"id");
// Now get the associated role, if any.
DOMElementHelper h = new DOMElementHelper(elem);
String perm_id = null;
if (h.hasAttribute("id"))
perm_id = id + "." + elem.getAttribute("id");
else
{ // no id defined!
logger.fatal("<permission/> defined with no id= attribute!");
throw new ConfigException("no id= attribute for a <permission/>",elem);
} // end else
if (h.hasAttribute("role"))
{ // this is a static permission; try and get the associated role
Role r = this.getRole(elem.getAttribute("role"));

View File

@@ -22,6 +22,8 @@ import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.*;
import com.silverwrist.util.ServletMultipartHandler;
import com.silverwrist.util.ServletMultipartException;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.except.*;
@@ -227,7 +229,24 @@ public class SystemAdmin extends VeniceServlet
} // end catch
} // end if
} // end if ("G" command)
if (cmd.equals("IMP"))
{ // "IMP" = "Import Users"
try
{ // get the import dialog
AdminImportUser rc = new AdminImportUser(user.getAdminInterface(),false);
setMyLocation(request,"sysadmin?cmd=IMP");
return rc;
} // end try
catch (AccessError ae)
{ // an access error generally means we're not an administrator
return new ErrorBox("Access Error","You do not have permission to administer the system.",null);
} // end catch
} // end if ("IMP" command)
// TODO: other command handling
@@ -396,4 +415,60 @@ public class SystemAdmin extends VeniceServlet
} // end doVenicePost
protected VeniceContent doVenicePost(HttpServletRequest request, ServletMultipartHandler mphandler,
VeniceEngine engine, UserContext user, RenderData rdat)
throws ServletException, IOException, VeniceServletResult
{
// decide what to do based on the "cmd" parameter
String cmd = getStandardCommandParam(mphandler);
if (logger.isDebugEnabled())
logger.debug("SystemAdmin/doPost command value = " + cmd);
if (cmd.equals("IMP"))
{ // "IMP" = "Import User Accounts"
try
{ // get the administrative interface and then check the buttons
AdminOperations adm = user.getAdminInterface();
if (isImageButtonClicked(mphandler,"cancel"))
throw new RedirectResult("sysadmin"); // we decided not to bother - go back
if (!isImageButtonClicked(mphandler,"upload"))
{ // the button must be wrong!
logger.error("no known button click on SystemAdmin.doPost, cmd=IMP");
return new ErrorBox("Internal Error","Unknown command button pressed","sysadmin");
} // end if
if (!(mphandler.isFileParam("idata")))
return new ErrorBox("Internal Error","Invalid input file parameter.","sysadmin");
// create the view object and use it to execute the operation
AdminImportUser rc = new AdminImportUser(user.getAdminInterface(),true);
rc.execute(mphandler.getFileContentStream("idata"));
setMyLocation(request,"sysadmin?cmd=IMP");
return rc;
} // end try
catch (AccessError ae)
{ // an access error generally means we're not an administrator
return new ErrorBox("Access Error","You do not have permission to administer the system.",null);
} // end catch
catch (ServletMultipartException smpe)
{ // error loading the data stream
return new ErrorBox("Internal Error","Error loading post data: " + smpe.getMessage(),"sysadmin");
} // end catch
} // end if
// TODO: other command handling
if (!(user.hasAdminAccess()))
return new ErrorBox("Access Error","You do not have permission to administer the system.",null);
setMyLocation(request,"sysadmin");
return makeSystemAdminTop();
} // end doVenicePost
} // end class SystemAdmin

View File

@@ -341,6 +341,18 @@ public abstract class VeniceServlet extends HttpServlet
} // end getStandardCommandParam
protected final String getStandardCommandParam(ServletMultipartHandler mphandler) throws ErrorBox
{
if (mphandler.isFileParam("cmd"))
throw new ErrorBox(null,"Internal Error: command should be a normal param",null);
String foo = mphandler.getValue("cmd");
if (foo==null)
return "???";
else
return foo;
} // end getStandardCommandParam
protected final void setMyLocation(ServletRequest request, String loc)
{
request.setAttribute(LOCATION_ATTR,loc);

View File

@@ -0,0 +1,315 @@
/*
* 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 Communities 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.servlets.format;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import org.apache.log4j.*;
import org.w3c.dom.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.util.DOMElementHelper;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.security.*;
import com.silverwrist.venice.util.*;
public class AdminImportUser implements JSPRender
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(AdminImportUser.class);
// Attribute name for request attribute
protected static final String ATTR_NAME = "com.silverwrist.venice.content.AdminFindUser";
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private AdminOperations adm;
private boolean doing_it;
private int processed = 0;
private int errors = 0;
private String message = null;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public AdminImportUser(AdminOperations adm, boolean doing_it)
{
this.adm = adm;
this.doing_it = doing_it;
} // end constructor
/*--------------------------------------------------------------------------------
* External static functions
*--------------------------------------------------------------------------------
*/
public static AdminImportUser retrieve(ServletRequest request)
{
return (AdminImportUser)(request.getAttribute(ATTR_NAME));
} // end retrieve
/*--------------------------------------------------------------------------------
* Implementations from interface VeniceContent
*--------------------------------------------------------------------------------
*/
public String getPageTitle(RenderData rdat)
{
return "Import User Accounts";
} // end getPageTitle
public String getPageQID()
{
return null;
} // end getPageQID
/*--------------------------------------------------------------------------------
* Implementations from interface JSPRender
*--------------------------------------------------------------------------------
*/
public void store(ServletRequest request)
{
request.setAttribute(ATTR_NAME,this);
} // end store
public String getTargetJSPName()
{
return (doing_it ? "import_results.jsp" : "import_form.jsp");
} // end getTargetJSPName
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public final void execute(InputStream xml_data)
{
XMLLoader loader = XMLLoader.get();
Document xmldoc;
try
{ // load the XML data!
xmldoc = loader.loadPostData(xml_data);
} // end try
catch (ValidationException e)
{ // serious parser error!
message = "<B>Error parsing XML: " + StringUtil.encodeHTML(e.getMessage()) + "</B>\n";
return;
} // end catch
Element root = xmldoc.getDocumentElement();
if (!(root.getTagName().equals("venice-import-users")))
{ // wrong document type!
message = "<B>XML Error: Document is not a &lt;venice-import-users/&gt; document</B>\n";
return;
} // end if
SecurityInfo sinf = adm.getSecurityInfo();
Role default_role = sinf.getDefaultRole("Global.NewUser");
ArrayList scroll = new ArrayList();
NodeList nl = root.getChildNodes();
for (int i=0; i<nl.getLength(); i++)
{ // get each node from the list, see if it's a Venice user
Node n = nl.item(i);
if ((n.getNodeType()==Node.ELEMENT_NODE) && n.getNodeName().equals("venice-user"))
{ // this is a Venice user record - first parse it out into binary data
processed++;
DOMElementHelper h = new DOMElementHelper((Element)n);
String id = h.getElement().getAttribute("id");
String username = null, password = null, reminder = null, description = null;
String zonehint = null;
Role r = default_role;
boolean confirm = false, locked = false, hideaddr = false, hidephone = false, hidefax = false;
boolean hideemail = false;
VCard vcard = null;
// BUILD PHASE - Build the data to be used for this user.
try
{ // parse out the info
username = h.getSubElementText("username");
if (username==null)
throw new ValidationException("no <username/> element found");
username = username.trim();
if (!(IDUtils.isValidVeniceID(username)))
throw new ValidationException("<username/> \"" + username + "\" is not a valid Venice ID");
password = h.getSubElementText("password");
if (password==null)
throw new ValidationException("no <password/> element found");
password = password.trim();
reminder = h.getSubElementText("password-reminder");
if (reminder!=null)
reminder = reminder.trim();
description = h.getSubElementText("description");
if (description!=null)
description = description.trim();
Element opts = h.getSubElement("options");
if (opts!=null)
{ // parse out the options
DOMElementHelper hopts = new DOMElementHelper(opts);
if (hopts.hasAttribute("role"))
{ // get the role from the file and return it
r = sinf.getRole(opts.getAttribute("role"));
if (r==null)
throw new ValidationException("role not defined: " + opts.getAttribute("role"));
} // end if
confirm = hopts.hasAttribute("confirmed");
locked = hopts.hasAttribute("locked");
hideaddr = hopts.hasAttribute("hideaddr");
hidephone = hopts.hasAttribute("hidephone");
hidefax = hopts.hasAttribute("hidefax");
hideemail = hopts.hasAttribute("hideemail");
if (hopts.hasAttribute("zonehint"))
zonehint = opts.getAttribute("zonehint").trim();
} // end if
// else just leave things as the default
opts = h.getSubElement("vCard");
if (opts==null)
throw new ValidationException("no <vCard/> element found");
vcard = new VCard(opts);
} // end try
catch (ValidationException e)
{ // record the error and continue
logger.error("caught ValidationException in build phase(" + id + ")",e);
String tmp = "<B>Error in element \"" + StringUtil.encodeHTML(id) + "\":</B> "
+ StringUtil.encodeHTML(e.getMessage());
scroll.add(tmp);
errors++;
continue;
} // end catch
// EXECUTE PHASE - make this user go!
try
{ // create the user context
AdminUserContext uc = adm.createNewAccount(username,password,reminder,confirm,locked,r,description);
// set up the contact info
ContactInfo ci = uc.getContactInfo();
ci.setPrivateAddress(hideaddr);
ci.setPrivatePhone(hidephone);
ci.setPrivateFax(hidefax);
ci.setPrivateEmail(hideemail);
ci.importVCard(vcard);
uc.putContactInfo(ci);
// set up the timezone
String tmp = vcard.getTimeZone();
if (tmp!=null)
{ // get a "generic" time zone and convert it to a real one
TimeZone zone_raw = TimeZone.getTimeZone("GMT" + tmp);
String[] ids = TimeZone.getAvailableIDs(zone_raw.getRawOffset());
TimeZone zone = null;
if (ids.length>0)
{ // OK, there's at least one time zone...which one do we pick?
if (zonehint!=null)
{ // use the "zonehint" to get the right time zone
for (int j=0; (zone==null) && (j<ids.length); j++)
if (ids[j].indexOf(zonehint)>=0)
zone = TimeZone.getTimeZone(ids[j]);
} // end if
if (zone==null)
zone = TimeZone.getTimeZone(ids[0]);
} // end if
else // just use the raw timezone
zone = zone_raw;
uc.setTimeZone(zone);
} // end if
} // end try
catch (AccessError ae)
{ // caught an access error creating user
logger.error("caught AccessError in execute phase(" + id + ")",ae);
String tmp = "<B>Unable to create \"" + username + "\" (element \"" + StringUtil.encodeHTML(id)
+ "\"):</B> " + StringUtil.encodeHTML(ae.getMessage());
scroll.add(tmp);
errors++;
continue;
} // end catch
catch (DataException de)
{ // caught a database error creating the user
logger.error("caught DataException in execute phase(" + id + ")",de);
String tmp = "<B>Unable to create \"" + username + "\" (element \"" + StringUtil.encodeHTML(id)
+ "\"):</B> database error: " + StringUtil.encodeHTML(de.getMessage());
scroll.add(tmp);
errors++;
continue;
} // end catch
// this user was created successfully!
String tmp = "[id " + StringUtil.encodeHTML(id) + "] user \"" + username + "\" created successfully.";
scroll.add(tmp);
} // end if
} // end for
// Gather the scroll items together to form the message.
message = StringUtil.join(scroll,"<BR>\n");
} // end execute
public final int getNumProcessed()
{
return processed;
} // end getNumProcessed
public final int getNumErrors()
{
return errors;
} // end getNumErrors
public final String getMessage()
{
return message;
} // end getMessage
} // end class AdminImportUser

View File

@@ -35,6 +35,7 @@ public class SystemAdminTop extends ContentMenuPanel
addChoice("View/Edit Banned Users","TODO");
addChoice("User Account Management","sysadmin?cmd=UF");
addChoice("System Audit Logs","sysadmin?cmd=A");
addChoice("Import User Accounts","sysadmin?cmd=IMP");
} // end constructor

View File

@@ -0,0 +1,527 @@
/*
* 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 Communities 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.util;
import java.util.*;
import org.apache.log4j.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.venice.except.*;
public class VCard
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Category logger = Category.getInstance(VCard.class);
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String formatted_name = null;
private String family_name = null;
private String given_name = null;
private String middle_name = null;
private String prefix = null;
private String suffix = null;
private String nickname = null;
private ArrayList addresses = new ArrayList();
private ArrayList phones = new ArrayList();
private ArrayList email_addresses = new ArrayList();
private String mailer = null;
private String timezone = null;
private String title = null;
private String role = null;
private String orgname = null;
private String note = null;
private String sort_string = null;
private String url = null;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public VCard(Element xml) throws ValidationException
{
if (!(xml.getTagName().equals("vCard")))
{ // not a vCard!
logger.error("top-level element should be <vCard/>, but it's <" + xml.getTagName() + "/>");
throw new ValidationException("not a valid XML vCard");
} // end if
boolean version_seen = false;
boolean fn_seen = false;
boolean n_seen = false;
NodeList nl = xml.getChildNodes();
for (int i=0; i<nl.getLength(); i++)
{ // read off each node from the list in turn
Node n = nl.item(i);
if (n.getNodeType()==Node.ELEMENT_NODE)
{ // get its name and compare it to one of the defined vCard node names
String nm = n.getNodeName();
if (nm.equals("VERSION"))
{ // Version tag - must contain "2.0" to be compliant
if (version_seen)
throw new ValidationException("double VERSION element seen in vCard");
version_seen = true;
DOMElementHelper h = new DOMElementHelper((Element)n);
String verstr = h.getElementText();
if (verstr==null)
throw new ValidationException("invalid vCard version");
if (logger.isDebugEnabled())
logger.debug("vCard VERSION = " + verstr.trim());
if (!(verstr.trim().equals("2.0")))
throw new ValidationException("invalid vCard version: " + verstr.trim());
} // end if ("VERSION" element)
else if (nm.equals("FN"))
{ // Formatted Name tag
if (fn_seen)
throw new ValidationException("double FN element seen in vCard");
fn_seen = true;
formatted_name = readElemText((Element)n);
if (logger.isDebugEnabled())
logger.debug("vCard FN = " + formatted_name);
} // end else if ("FN" element)
else if (nm.equals("N"))
{ // Structured Name tag
if (n_seen)
throw new ValidationException("double N element seen in vCard");
n_seen = true;
DOMElementHelper h = new DOMElementHelper((Element)n);
family_name = cleanup(h.getSubElementText("FAMILY"));
given_name = cleanup(h.getSubElementText("GIVEN"));
middle_name = cleanup(h.getSubElementText("MIDDLE"));
prefix = cleanup(h.getSubElementText("PREFIX"));
suffix = cleanup(h.getSubElementText("SUFFIX"));
if (logger.isDebugEnabled())
logger.debug("vCard N = (pfx=" + prefix + ", given=" + given_name + ", middle=" + middle_name
+ ", family=" + family_name + ", sfx=" + suffix + ")");
} // end else if ("N" element)
else if (nm.equals("NICKNAME")) // nickname (simple)
nickname = readElemText((Element)n);
else if (nm.equals("ADR")) // address record
addresses.add(new VCardAddress((Element)n));
else if (nm.equals("TEL")) // phone number record
phones.add(new VCardPhone((Element)n));
else if (nm.equals("EMAIL"))
email_addresses.add(new VCardEmail((Element)n));
else if (nm.equals("MAILER"))
mailer = readElemText((Element)n);
else if (nm.equals("TZ"))
timezone = readTimeZoneText((Element)n);
else if (nm.equals("TITLE"))
title = readElemText((Element)n);
else if (nm.equals("ROLE"))
role = readElemText((Element)n);
else if (nm.equals("ORG"))
{ // Organization element - get the organization name
DOMElementHelper h = new DOMElementHelper((Element)n);
orgname = h.getSubElementText("ORGNAME");
// we don't support ORGUNIT elements yet
} // end else if ("ORG" element)
else if (nm.equals("NOTE"))
note = readElemText((Element)n);
else if (nm.equals("SORTSTR") || nm.equals("SORT-STRING"))
sort_string = readElemText((Element)n);
else if (nm.equals("URL"))
url = readElemText((Element)n);
else if ( nm.equals("PHOTO") || nm.equals("BDAY") || nm.equals("LABEL") || nm.equals("GEO")
|| nm.equals("LOGO") || nm.equals("AGENT") || nm.equals("CATEGORIES") || nm.equals("PRODID")
|| nm.equals("REV") || nm.equals("SOUND") || nm.equals("UID") || nm.equals("CLASS")
|| nm.equals("KEY"))
{ // a catch-all for elements that we don't support yet
logger.warn("vCard <" + nm + "/> element is not yet supported");
} // end else if (not-supported element)
else
{ // unrecognized tag element
logger.error("unrecognized tag <" + nm + "/> in vCard");
throw new ValidationException("unrecognized element in vCard");
} // end else (other tags)
} // end if
// else ignore it
} // end for
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
static final String cleanup(String data)
{
return ((data==null) ? null : data.trim());
} // end cleanup
private static final String readElemText(Element elt)
{
DOMElementHelper h = new DOMElementHelper(elt);
return cleanup(h.getElementText());
} // end readElemText
private static final String readTimeZoneText(Element elt) throws ValidationException
{
DOMElementHelper h = new DOMElementHelper(elt);
String s = h.getElementText();
if (s==null)
return null;
s = s.trim();
// Validate that this is a proper ISO 8601 time zone offset.
boolean valid;
if (s.equals("Z") || s.equals("z"))
valid = true; // "Z" = Zulu time!
else
{ // validate the offset string
valid = (s.length()>=3) && ((s.charAt(0)=='+') || (s.charAt(0)=='-'));
if (valid)
valid = ((s.charAt(1)>='0') && (s.charAt(1)<='9'));
if (valid)
valid = ((s.charAt(2)>='0') && (s.charAt(2)<='9'));
if (s.length()>3)
{ // validate the last bit of the string
if (s.charAt(3)==':') // +hh:mm or -hh:mm
valid = ( (s.length()==6) && (s.charAt(4)>='0') && (s.charAt(4)<='9') && (s.charAt(5)>='0')
&& (s.charAt(5)<='9'));
else // +hhmm or -hhmm
valid = ( (s.length()==5) && (s.charAt(3)>='0') && (s.charAt(3)<='9') && (s.charAt(4)>='0')
&& (s.charAt(4)<='9'));
} // end if
// else it's just a +hh or -hh notation
} // end else
if (!valid)
{ // the time zone text is not valid
logger.error("<TZ/> text invalid (" + s + ")");
throw new ValidationException("<TZ/> value is not a valid ISO 8601 time zone offset");
} // end if
return s;
} // end readTimeZoneText
private VCardAddress findAddress(VCardAddress.Predicate pred)
{
Iterator it = addresses.iterator();
while (it.hasNext())
{ // search for address matching the predicate
VCardAddress addr = (VCardAddress)(it.next());
if (pred.test(addr))
return addr;
} // end while
return null;
} // end findAddress
private VCardPhone findPhone(VCardPhone.Predicate pred)
{
Iterator it = phones.iterator();
while (it.hasNext())
{ // search for phone number matching the predicate
VCardPhone p = (VCardPhone)(it.next());
if (pred.test(p))
return p;
} // end while
return null;
} // end findPhone
private VCardEmail findEmail(VCardEmail.Predicate pred)
{
Iterator it = email_addresses.iterator();
while (it.hasNext())
{ // search for phone number matching the predicate
VCardEmail e = (VCardEmail)(it.next());
if (pred.test(e))
return e;
} // end while
return null;
} // end findEmail
/*--------------------------------------------------------------------------------
* Public getters/setters
*--------------------------------------------------------------------------------
*/
public final String getFormattedName()
{
return formatted_name;
} // end getFormattedName
public final String getFamilyName()
{
return family_name;
} // end getFamilyName
public final String getGivenName()
{
return given_name;
} // end getGivenName
public final String getMiddleName()
{
return middle_name;
} // end getMiddleName
public final String getPrefix()
{
return prefix;
} // end getPrefix
public final String getSuffix()
{
return suffix;
} // end getSuffix
public final String getNickname()
{
return nickname;
} // end getNickname
public final String getMailer()
{
return mailer;
} // end getMailer
public final String getTimeZone()
{
return timezone;
} // end getTimeZone
public final String getTitle()
{
return title;
} // end getTitle
public final String getRole()
{
return role;
} // end getRole
public final String getOrganizationName()
{
return orgname;
} // end getOrganizationName
public final String getNote()
{
return note;
} // end getNode
public final String getSortString()
{
return sort_string;
} // end getSortString
public final String getURL()
{
return url;
} // end getURL
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public final VCardAddress getPreferredAddress()
{
return findAddress(new VCardAddress.Predicate(){
public final boolean test(VCardAddress addr) { return addr.isPreferred(); }
});
} // end getPreferredAddress
public final VCardAddress getWorkAddress()
{
return findAddress(new VCardAddress.Predicate(){
public final boolean test(VCardAddress addr) { return addr.isWorkAddress(); }
});
} // end getWorkAddress
public final VCardAddress getHomeAddress()
{
return findAddress(new VCardAddress.Predicate(){
public final boolean test(VCardAddress addr) { return addr.isHomeAddress(); }
});
} // end getHomeAddress
public final VCardAddress getPreferredWorkAddress()
{
return findAddress(new VCardAddress.Predicate(){
public final boolean test(VCardAddress addr) { return addr.isPreferred() && addr.isWorkAddress(); }
});
} // end getPreferredWorkAddress
public final VCardAddress getPreferredHomeAddress()
{
return findAddress(new VCardAddress.Predicate(){
public final boolean test(VCardAddress addr) { return addr.isPreferred() && addr.isHomeAddress(); }
});
} // end getPreferredHomeAddress
public final VCardAddress getAnyAddress()
{
return (addresses.isEmpty() ? null : (VCardAddress)(addresses.get(0)));
} // end getAnyAddress
public final VCardPhone getPreferredPhone()
{
return findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isPreferred(); }
});
} // end getPreferredPhone
public final VCardPhone getVoicePhone()
{
return findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isVoicePhone(); }
});
} // end getVoicePhone
public final VCardPhone getHomePhone()
{
return findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isHomePhone() && p.isVoicePhone(); }
});
} // end getHomePhone
public final VCardPhone getWorkPhone()
{
return findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isWorkPhone() && p.isVoicePhone(); }
});
} // end getWorkPhone
public final VCardPhone getPreferredFax()
{
return findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isPreferred() && p.isFax(); }
});
} // end getPreferredFax
public final VCardPhone getHomeFax()
{
return findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isHomePhone() && p.isFax(); }
});
} // end getHomeFax
public final VCardPhone getWorkFax()
{
return findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isWorkPhone() && p.isFax(); }
});
} // end getHomeFax
public final VCardPhone getAnyFax()
{
return findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isFax(); }
});
} // end getAnyFax
public final VCardPhone getCellPhone()
{
VCardPhone rc = findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isCellPhone(); }
});
if (rc==null)
rc = findPhone(new VCardPhone.Predicate(){
public final boolean test(VCardPhone p) { return p.isPCSPhone(); }
});
return rc;
} // end getHomeFax
public final VCardPhone getAnyPhone()
{
return ((phones.isEmpty()) ? null : (VCardPhone)(phones.get(0)));
} // end getAnyPhone
public final VCardEmail getPreferredEmail()
{
return findEmail(new VCardEmail.Predicate(){
public final boolean test(VCardEmail e) { return e.isPreferred(); }
});
} // end getPreferredEmail
public final VCardEmail getInternetEmail()
{
return findEmail(new VCardEmail.Predicate(){
public final boolean test(VCardEmail e) { return e.isInternetEmail(); }
});
} // end getInternetEmail
} // end class VCard

View File

@@ -0,0 +1,173 @@
/*
* 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 Communities 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.util;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.venice.except.*;
public class VCardAddress
{
/*--------------------------------------------------------------------------------
* Predicate class to use for searches
*--------------------------------------------------------------------------------
*/
static abstract class Predicate
{
public abstract boolean test(VCardAddress addr);
} // end class Predicate
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private boolean home_adr;
private boolean work_adr;
private boolean postal_adr;
private boolean parcel_adr;
private boolean domestic_adr;
private boolean intl_adr;
private boolean preferred;
private String pobox;
private String ext_address;
private String street;
private String locality;
private String region;
private String postal_code;
private String country;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
VCardAddress(Element adr) throws ValidationException
{
DOMElementHelper h = new DOMElementHelper(adr);
home_adr = h.hasChildElement("HOME");
work_adr = h.hasChildElement("WORK");
postal_adr = h.hasChildElement("POSTAL");
parcel_adr = h.hasChildElement("PARCEL");
domestic_adr = h.hasChildElement("DOM");
intl_adr = h.hasChildElement("INTL");
if (domestic_adr && intl_adr)
throw new ValidationException("same address can't be both DOM and INTL");
preferred = h.hasChildElement("PREF");
pobox = VCard.cleanup(h.getSubElementText("POBOX"));
ext_address = VCard.cleanup(h.getSubElementText("EXTADR"));
street = VCard.cleanup(h.getSubElementText("STREET"));
locality = VCard.cleanup(h.getSubElementText("LOCALITY"));
region = VCard.cleanup(h.getSubElementText("REGION"));
postal_code = VCard.cleanup(h.getSubElementText("PCODE"));
country = VCard.cleanup(h.getSubElementText("CTRY"));
} // end constructor
/*--------------------------------------------------------------------------------
* External getters/setters
*--------------------------------------------------------------------------------
*/
public final boolean isHomeAddress()
{
return home_adr;
} // end isHomeAddress
public final boolean isWorkAddress()
{
return work_adr;
} // end isWorkAddress
public final boolean isPostalAddress()
{
return postal_adr;
} // end isPostalAddress
public final boolean isParcelAddress()
{
return parcel_adr;
} // end isParcelAddress
public final boolean isDomesticAddress()
{
return domestic_adr;
} // end isDomesticAddress
public final boolean isInternationalAddress()
{
return intl_adr;
} // end isInternationalAddress
public final boolean isPreferred()
{
return preferred;
} // end isPreferred
public final String getPOBox()
{
return pobox;
} // end getPOBox
public final String getExtension()
{
return ext_address;
} // end getExtension
public final String getStreet()
{
return street;
} // end getStreet
public final String getLocality()
{
return locality;
} // end getLocality
public final String getRegion()
{
return region;
} // end getRegion
public final String getPostalCode()
{
return postal_code;
} // end getPostalCode
public final String getCountry()
{
return country;
} // end getCountry
} // end class VCardAddress

View File

@@ -0,0 +1,111 @@
/*
* 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 Communities 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.util;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.venice.except.*;
public class VCardEmail
{
/*--------------------------------------------------------------------------------
* Predicate class to use for searches
*--------------------------------------------------------------------------------
*/
static abstract class Predicate
{
public abstract boolean test(VCardEmail e);
} // end class Predicate
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private boolean home_email;
private boolean work_email;
private boolean internet_email;
private boolean x400_email;
private boolean preferred;
private String address;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
VCardEmail(Element elt)
{
DOMElementHelper h = new DOMElementHelper(elt);
home_email = h.hasChildElement("HOME");
work_email = h.hasChildElement("WORK");
internet_email = h.hasChildElement("INTERNET");
x400_email = h.hasChildElement("X400");
preferred = h.hasChildElement("PREF");
if (!internet_email && !x400_email)
internet_email = true; // default
address = VCard.cleanup(h.getSubElementText("USERID"));
if (address==null)
address = VCard.cleanup(h.getElementText());
} // end constructor
/*--------------------------------------------------------------------------------
* External getters/setters
*--------------------------------------------------------------------------------
*/
public final boolean isHomeEmail()
{
return home_email;
} // end isHomeEmail
public final boolean isWorkEmail()
{
return work_email;
} // end isHomeEmail
public final boolean isInternetEmail()
{
return internet_email;
} // end isInternetEmail
public final boolean isX400Email()
{
return x400_email;
} // end isX400Email
public final boolean isPreferred()
{
return preferred;
} // end isPreferred
public final String getAddress()
{
return address;
} // end getAddress
} // end class VCardEmail

View File

@@ -0,0 +1,173 @@
/*
* 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 Communities 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.util;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.venice.except.*;
public class VCardPhone
{
/*--------------------------------------------------------------------------------
* Predicate class to use for searches
*--------------------------------------------------------------------------------
*/
static abstract class Predicate
{
public abstract boolean test(VCardPhone p);
} // end class Predicate
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private boolean home_phone;
private boolean work_phone;
private boolean voice_phone;
private boolean fax_phone;
private boolean pager;
private boolean message;
private boolean cell_phone;
private boolean video_phone;
private boolean bbs_phone;
private boolean modem_phone;
private boolean isdn_phone;
private boolean pcs_phone;
private boolean preferred;
private String number;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
VCardPhone(Element elt)
{
DOMElementHelper h = new DOMElementHelper(elt);
home_phone = h.hasChildElement("HOME");
work_phone = h.hasChildElement("WORK");
voice_phone = h.hasChildElement("VOICE");
fax_phone = h.hasChildElement("FAX");
pager = h.hasChildElement("PAGER");
message = h.hasChildElement("MSG");
cell_phone = h.hasChildElement("CELL");
video_phone = h.hasChildElement("VIDEO");
bbs_phone = h.hasChildElement("BBS");
modem_phone = h.hasChildElement("MODEM");
isdn_phone = h.hasChildElement("ISDN");
pcs_phone = h.hasChildElement("PCS");
preferred = h.hasChildElement("PREF");
number = VCard.cleanup(h.getSubElementText("NUMBER"));
if (number==null)
number = VCard.cleanup(h.getElementText());
} // end constructor
/*--------------------------------------------------------------------------------
* External getters/setters
*--------------------------------------------------------------------------------
*/
public final boolean isHomePhone()
{
return home_phone;
} // end isHomePhone
public final boolean isWorkPhone()
{
return work_phone;
} // end isWorkPhone
public final boolean isVoicePhone()
{
return voice_phone;
} // end isVoicePhone
public final boolean isFax()
{
return fax_phone;
} // end isFax
public final boolean isPager()
{
return pager;
} // end isPager
public final boolean isMessage()
{
return message;
} // end isMessage
public final boolean isCellPhone()
{
return cell_phone;
} // end isCellPhone
public final boolean isVideoPhone()
{
return video_phone;
} // end isVideoPhone
public final boolean isBBS()
{
return bbs_phone;
} // end isBBS
public final boolean isModemPhone()
{
return modem_phone;
} // end isModemPhone
public final boolean isISDNPhone()
{
return isdn_phone;
} // end isISDNPhone
public final boolean isPCSPhone()
{
return pcs_phone;
} // end isPCSPhone
public final boolean isPreferred()
{
return preferred;
} // end isPreferred
public final String getNumber()
{
return number;
} // end getNumber
} // end class VCardPhone

View File

@@ -111,6 +111,65 @@ public class XMLLoader
} // end loadConfigDocument
public final Document loadPostData(InputStream stm) throws ValidationException
{
if (logger.isDebugEnabled())
logger.debug("loadPostData()...");
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
Document rc = parser.parse(stm);
if (logger.isDebugEnabled())
logger.debug("post data loaded successfully");
return rc;
} // end try
catch (FactoryConfigurationError fce)
{ // if the document builder factory could not be created
logger.error("Parser factory configuration error: " + fce.getMessage(),fce);
throw new ValidationException("XML parser factory could not be created - " + fce.getMessage());
} // end catch
catch (ParserConfigurationException pce)
{ // if the XML parser itself could not be created
logger.error("Parser configuration error: " + pce.getMessage(),pce);
throw new ValidationException("XML parser could not be created - " + pce.getMessage(),pce);
} // end catch
catch (SAXException se)
{ // if the XML parser choked on our document
if (se instanceof SAXParseException)
{ // we have a detailed message - make a proper exception
SAXParseException spe = (SAXParseException)se;
logger.error("Error in post data [" + spe.getLineNumber() + "," + spe.getColumnNumber() + "]: "
+ spe.getMessage(),spe);
throw new ValidationException("Error in post data: " + spe.getMessage() + " at line "
+ spe.getLineNumber() + ", column " + spe.getColumnNumber(),spe);
} // end if
else
{ // generic exception - just send up a simple error message
logger.error("Error in post data: " + se.getMessage(),se);
throw new ValidationException("Error in post data - " + se.getMessage(),se);
} // end else
} // end catch
catch (IOException ioe)
{ // error reading the post data itself out of the buffer
logger.error("IO error reading post data: " + ioe.getMessage(),ioe);
throw new ValidationException("unable to read post data - " + ioe.getMessage(),ioe);
} // end catch
} // end loadPostData
public final Element configGetRootElement(Document doc, String expected_name) throws ConfigException
{
Element rc = doc.getDocumentElement();
@@ -182,6 +241,15 @@ public class XMLLoader
} // end configVerifyNodeName
public final void configVerifyTagName(Element tag, String name) throws ConfigException
{
if (tag.getTagName().equals(name))
return;
logger.fatal("expected a <" + name + "/> element here, but got a <" + tag.getTagName() + "/>");
throw new ConfigException("element must be a <" + name + "/>",tag);
} // end configVerifyTagName
public final String configGetAttribute(Element elt, String attr_name) throws ConfigException
{
String rc = elt.getAttribute(attr_name);