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

@@ -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