*** empty log message ***

This commit is contained in:
Eric J. Bowersox
2003-05-20 03:25:31 +00:00
commit b80fa05ed1
682 changed files with 85738 additions and 0 deletions

View File

@@ -0,0 +1,189 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo;
import java.util.*;
import org.apache.commons.lang.enum.*;
/**
* A type-safe enumerated type that indicates the capabilities of a browser. These objects are returned
* in a set by the {@link com.silverwrist.dynamo.iface.BrowserData#getBrowserFlags() BrowserData.getBrowserFlags()}
* method.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public final class BrowserFlag extends Enum
{
/*--------------------------------------------------------------------------------
* The actual enumeration values
*--------------------------------------------------------------------------------
*/
/**
* Indicates that the browser supports frames (the &lt;FRAMESET&gt; and &lt;FRAME&gt; tags).
*/
public static final BrowserFlag FRAMES = new BrowserFlag("FRAMES");
/**
* Indicates that the browser supports in-line frames (the &lt;IFRAME&gt; tag).
*/
public static final BrowserFlag IFRAMES = new BrowserFlag("IFRAMES");
/**
* Indicates that the browser supports tables.
*/
public static final BrowserFlag TABLES = new BrowserFlag("TABLES");
/**
* Indicates that the browser supports cookies.
*/
public static final BrowserFlag COOKIES = new BrowserFlag("COOKIES");
/**
* Indicates that the browser supports background sounds (the &lt;BGSOUND&gt; tag).
*/
public static final BrowserFlag BACKGROUND_SOUNDS = new BrowserFlag("BACKGROUND_SOUNDS");
/**
* Indicates that the browser supports client-side scripting using Visual Basic Script.
*/
public static final BrowserFlag VBSCRIPT = new BrowserFlag("VBSCRIPT");
/**
* Indicates that the browser supports client-side scripting using JavaScript (JScript).
*/
public static final BrowserFlag JAVASCRIPT = new BrowserFlag("JAVASCRIPT");
/**
* Indicates that the browser supports client-side Java applets.
*/
public static final BrowserFlag JAVA_APPLETS = new BrowserFlag("JAVA_APPLETS");
/**
* Indicates that the browser supports client-side ActiveX controls.
*/
public static final BrowserFlag ACTIVEX_CONTROLS = new BrowserFlag("ACTIVEX_CONTROLS");
/**
* Indicates that the browser supports CDF.
*/
public static final BrowserFlag CDF = new BrowserFlag("CDF");
/**
* Indicates that this browser is an America Online client.
*/
public static final BrowserFlag AOL = new BrowserFlag("AOL");
/**
* Indicates that this browser is a beta version.
*/
public static final BrowserFlag BETA = new BrowserFlag("BETA");
/**
* Indicates that the browser is running on a 16-bit Windows operating system.
*/
public static final BrowserFlag WIN16 = new BrowserFlag("WIN16");
/**
* Indicates that this browser is not a browser at all, but a "crawler," which may be used to index the
* site's content by a search engine, or for other (nefarious) purposes.
*/
public static final BrowserFlag CRAWLER = new BrowserFlag("CRAWLER");
/**
* Indicates that this browser is not a browser at all, but a "stripper," which is copying the HTML of the
* site to another location. This may or may not be benign.
*/
public static final BrowserFlag STRIPPER = new BrowserFlag("STRIPPER");
/**
* Indicates that the browser is a cellphone or other handheld device, possibly supporting
* Wireless Access Protocol (WAP).
*/
public static final BrowserFlag WAP = new BrowserFlag("WAP");
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Internal constructor which creates a new element of this enumerated type.
*
* @param name The name of the <CODE>BrowserFlag</CODE> to be created.
*/
private BrowserFlag(String name)
{
super(name);
} // end constructor
/*--------------------------------------------------------------------------------
* Standard static method implementations
*--------------------------------------------------------------------------------
*/
/**
* Gets a <CODE>BrowserFlag</CODE> by name.
*
* @param name The name of the <CODE>BrowserFlag</CODE> to get; may be <CODE>null</CODE>.
* @return The <CODE>BrowserFlag</CODE> object, or <CODE>null</CODE> if the <CODE>BrowserFlag</CODE> does not exist.
*/
public static BrowserFlag getEnum(String name)
{
return (BrowserFlag)getEnum(BrowserFlag.class,name);
} // end getEnum
/**
* Gets the <CODE>Map</CODE> of <CODE>BrowserFlag</CODE> objects by name.
*
* @return The <CODE>BrowserFlag</CODE> object <CODE>Map</CODE>.
*/
public static Map getEnumMap()
{
return getEnumMap(BrowserFlag.class);
} // end getEnumMap
/**
* Gets the <CODE>List</CODE> of <CODE>BrowserFlag</CODE> objects, in the order in which the objects are listed
* in the code above.
*
* @return The <CODE>BrowserFlag</CODE> object <CODE>List</CODE>.
*/
public static List getEnumList()
{
return getEnumList(BrowserFlag.class);
} // end getEnumList
/**
* Gets an iterator over all <CODE>BrowserFlag</CODE> objects, in the order in which the objects are listed
* in the code above.
*
* @return The <CODE>BrowserFlag</CODE> object iterator.
*/
public static Iterator iterator()
{
return iterator(BrowserFlag.class);
} // end iterator
} // end class BrowserFlag

View File

@@ -0,0 +1,33 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo;
/**
* Class that holds the Dynamo version number.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public final class DynamoVersion
{
/**
* The current version number of the Dynamo framework.
*/
public static final String VERSION = "0.05";
} // end class DynamoVersion

View File

@@ -0,0 +1,482 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo;
import java.util.*;
import org.apache.commons.lang.enum.*;
import javax.servlet.http.HttpServletResponse;
/**
* A type-safe enumerated type that encapsulates the HTTP status codes. We use an enumerated type here
* so that it can be extended to support additional status codes (the ones defined, say, by WebDAV)
* without affecting <CODE>HttpServletResponse</CODE>.
* <p>The descriptions of the status codes are taken from the HTTP 1.1 Specification,
* <a href="ftp://ftp.rfc-editor.org/in-notes/rfc2616.txt">RFC 2616</a>.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class HttpStatusCode extends ValuedEnum
{
/*--------------------------------------------------------------------------------
* The actual enumeration values
*--------------------------------------------------------------------------------
*/
// N.B.: We copy the status codes here to allow extending them independent of the codes
// listed in HttpServletResponse, but we point to the originals in HttpServletResponse
// to maintain compatibility.
/**
* <b>100 Continue</b>. The client SHOULD continue with its request. This interim response is used to
* inform the client that the initial part of the request has been received and has not yet been rejected
* by the server. The client SHOULD continue by sending the remainder of the request or, if the request
* has already been completed, ignore this response. The server MUST send a final response after the
* request has been completed.
*/
public static final HttpStatusCode I_CONTINUE =
new HttpStatusCode("I_CONTINUE",HttpServletResponse.SC_CONTINUE);
/**
* <b>101 Switching Protocols</b>. The server understands and is willing to comply with the client's request,
* via the Upgrade message header field, for a change in the application protocol being used on this connection.
* The server will switch protocols to those defined by the response's Upgrade header field immediately after
* the empty line which terminates the 101 response.
*/
public static final HttpStatusCode I_SWITCH =
new HttpStatusCode("I_SWITCH",HttpServletResponse.SC_SWITCHING_PROTOCOLS);
/**
* <b>200 OK</b>. The request has succeeded. The information returned with the response is dependent on
* the method used in the request. (Default status code)
*/
public static final HttpStatusCode S_OK =
new HttpStatusCode("S_OK",HttpServletResponse.SC_OK);
/**
* <b>201 Created</b>. The request has been fulfilled and resulted in a new resource being created. The
* newly created resource can be referenced by the URI(s) returned in the entity of the response, with
* the most specific URI for the resource given by a Location header field. The response SHOULD include
* an entity containing a list of resource characteristics and location(s) from which the user or user
* agent can choose the one most appropriate. The entity format is specified by the media type given in
* the Content-Type header field. The origin server MUST create the resource before returning the 201
* status code. If the action cannot be carried out immediately, the server SHOULD respond with 202
* (Accepted) response instead.
*/
public static final HttpStatusCode S_CREATED =
new HttpStatusCode("S_CREATED",HttpServletResponse.SC_CREATED);
/**
* <b>202 Accepted</b>. The request has been accepted for processing, but the processing has not been
* completed. The request might or might not eventually be acted upon, as it might be disallowed when
* processing actually takes place.
*/
public static final HttpStatusCode S_ACCEPTED =
new HttpStatusCode("S_ACCEPTED",HttpServletResponse.SC_ACCEPTED);
/**
* <b>203 Non-Authoritative Information</b>. The returned metainformation in the entity-header is not the
* definitive set as available from the origin server, but is gathered from a local or a third-party copy.
* The set presented MAY be a subset or superset of the original version. For example, including local
* annotation information about the resource might result in a superset of the metainformation known by
* the origin server. Use of this response code is not required and is only appropriate when the response
* would otherwise be 200 (OK).
*/
public static final HttpStatusCode S_NONAUTHORITATIVE =
new HttpStatusCode("S_NONAUTHORITATIVE",HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION);
/**
* <b>204 No Content</b>. The server has fulfilled the request but does not need to return an entity-body,
* and might want to return updated metainformation. The response MAY include new or updated metainformation
* in the form of entity-headers, which if present SHOULD be associated with the requested variant. If the
* client is a user agent, it SHOULD NOT change its document view from that which caused the request to be
* sent. This response is primarily intended to allow input for actions to take place without causing a
* change to the user agent's active document view, although any new or updated metainformation SHOULD be
* applied to the document currently in the user agent's active view.
*/
public static final HttpStatusCode S_NODATA =
new HttpStatusCode("S_NODATA",HttpServletResponse.SC_NO_CONTENT);
/**
* <b>205 Reset Content</b>. The server has fulfilled the request and the user agent SHOULD reset the document
* view which caused the request to be sent. This response is primarily intended to allow input for actions
* to take place via user input, followed by a clearing of the form in which the input is given so that the
* user can easily initiate another input action.
*/
public static final HttpStatusCode S_RESET =
new HttpStatusCode("S_RESET",HttpServletResponse.SC_RESET_CONTENT);
/**
* <b>206 Partial Content</b>. The server has fulfilled the partial GET request for the resource. The
* request MUST have included a Range header field indicating the desired range, and MAY have included
* an If-Range header field to make the request conditional.
*/
public static final HttpStatusCode S_PARTIAL =
new HttpStatusCode("S_PARTIAL",HttpServletResponse.SC_PARTIAL_CONTENT);
/**
* <b>300 Multiple Choices</b>. The requested resource corresponds to any one of a set of representations,
* each with its own specific location, and agent-driven negotiation information is being provided so that
* the user (or user agent) can select a preferred representation and redirect its request to that location.
*/
public static final HttpStatusCode S_CHOICE =
new HttpStatusCode("S_CHOICE",HttpServletResponse.SC_MULTIPLE_CHOICES);
/**
* <b>301 Moved Permanently</b>. The requested resource has been assigned a new permanent URI and any future
* references to this resource SHOULD use one of the returned URIs. Clients with link editing capabilities
* ought to automatically re-link references to the Request-URI to one or more of the new references returned
* by the server, where possible.
*/
public static final HttpStatusCode S_MOVED =
new HttpStatusCode("S_MOVED",HttpServletResponse.SC_MOVED_PERMANENTLY);
/**
* <b>302 Moved Temporarily</b> (Redirect). The requested resource resides temporarily under a different URI.
* Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for
* future requests.
*/
public static final HttpStatusCode S_REDIRECT =
new HttpStatusCode("S_REDIRECT",HttpServletResponse.SC_MOVED_TEMPORARILY);
/**
* <b>303 See Other</b>. The response to the request can be found under a different URI and SHOULD be
* retrieved using a GET method on that resource. This method exists primarily to allow the output of a
* POST-activated script to redirect the user agent to a selected resource. The new URI is not a
* substitute reference for the originally requested resource.
*/
public static final HttpStatusCode S_SEE_OTHER =
new HttpStatusCode("S_SEE_OTHER",HttpServletResponse.SC_SEE_OTHER);
/**
* <b>304 Not Modified</b>. If the client has performed a conditional GET request and access is allowed,
* but the document has not been modified, the server SHOULD respond with this status code.
*/
public static final HttpStatusCode S_NOTMODIFIED =
new HttpStatusCode("S_NOTMODIFIED",HttpServletResponse.SC_NOT_MODIFIED);
/**
* <b>305 Use Proxy</b>. The requested resource MUST be accessed through the proxy given by the Location
* field. The Location field gives the URI of the proxy. The recipient is expected to repeat this single
* request via the proxy.
*/
public static final HttpStatusCode S_USE_PROXY =
new HttpStatusCode("S_USEPROXY",HttpServletResponse.SC_USE_PROXY);
/**
* <b>307 Temporary Redirect</b>. The requested resource resides temporarily under a different URI.
* Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI
* for future requests.
*/
public static final HttpStatusCode S_REDIRECT_TEMP =
new HttpStatusCode("S_REDIRECT_TEMP",HttpServletResponse.SC_TEMPORARY_REDIRECT);
/**
* <b>400 Bad Request</b>. The request could not be understood by the server due to malformed syntax. The
* client SHOULD NOT repeat the request without modifications.
*/
public static final HttpStatusCode E_BAD_REQUEST =
new HttpStatusCode("E_BAD_REQUEST",HttpServletResponse.SC_BAD_REQUEST);
/**
* <b>401 Unauthorized</b>. The request requires user authentication. The response MUST include a
* WWW-Authenticate header field containing a challenge applicable to the requested resource. The client
* MAY repeat the request with a suitable Authorization header field. If the request already included
* Authorization credentials, then the 401 response indicates that authorization has been refused for those
* credentials. If the 401 response contains the same challenge as the prior response, and the user agent
* has already attempted authentication at least once, then the user SHOULD be presented the entity that
* was given in the response, since that entity might include relevant diagnostic information.
*/
public static final HttpStatusCode E_AUTH =
new HttpStatusCode("E_AUTH",HttpServletResponse.SC_UNAUTHORIZED);
/**
* <b>402 Payment Required</b>. This code is reserved for future use.
*/
public static final HttpStatusCode E_PAYMENT =
new HttpStatusCode("E_PAYMENT",HttpServletResponse.SC_PAYMENT_REQUIRED);
/**
* <b>403 Forbidden</b>. The server understood the request, but is refusing to fulfill it. Authorization
* will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server
* wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the
* refusal in the entity. If the server does not wish to make this information available to the client,
* the status code 404 (Not Found) can be used instead.
*/
public static final HttpStatusCode E_FORBIDDEN =
new HttpStatusCode("E_FORBIDDEN",HttpServletResponse.SC_FORBIDDEN);
/**
* <b>404 Not Found</b>. The server has not found anything matching the Request-URI. No indication is given
* of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the
* server knows, through some internally configurable mechanism, that an old resource is permanently
* unavailable and has no forwarding address. This status code is commonly used when the server does not
* wish to reveal exactly why the request has been refused, or when no other response is applicable.
*/
public static final HttpStatusCode E_NOTFOUND =
new HttpStatusCode("E_NOTFOUND",HttpServletResponse.SC_NOT_FOUND);
/**
* <b>405 Method Not Allowed</b>. The method specified in the Request-Line is not allowed for the resource
* identified by the Request-URI. The response MUST include an Allow header containing a list of valid
* methods for the requested resource.
*/
public static final HttpStatusCode E_METHOD =
new HttpStatusCode("E_METHOD",HttpServletResponse.SC_METHOD_NOT_ALLOWED);
/**
* <b>406 Not Acceptable</b>. The resource identified by the request is only capable of generating response
* entities which have content characteristics not acceptable according to the accept headers sent in the request.
*/
public static final HttpStatusCode E_NOTACCEPTABLE =
new HttpStatusCode("E_NOTACCEPTABLE",HttpServletResponse.SC_NOT_ACCEPTABLE);
/**
* <b>407 Proxy Authentication Required</b>. This code is similar to 401 (Unauthorized), but indicates that
* the client must first authenticate itself with the proxy. The proxy MUST return a Proxy-Authenticate
* header field containing a challenge applicable to the proxy for the requested resource. The client MAY
* repeat the request with a suitable Proxy-Authorization header field.
*/
public static final HttpStatusCode E_PROXY_AUTH =
new HttpStatusCode("E_PROXY_AUTH",HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
/**
* <b>408 Request Timeout</b>. The client did not produce a request within the time that the server was
* prepared to wait. The client MAY repeat the request without modifications at any later time.
*/
public static final HttpStatusCode E_TIMEOUT =
new HttpStatusCode("E_TIMEOUT",HttpServletResponse.SC_REQUEST_TIMEOUT);
/**
* <b>409 Conflict</b>. The request could not be completed due to a conflict with the current state of the
* resource. This code is only allowed in situations where it is expected that the user might be able to
* resolve the conflict and resubmit the request. The response body SHOULD include enough information for
* the user to recognize the source of the conflict. Ideally, the response entity would include enough
* information for the user or user agent to fix the problem; however, that might not be possible and is
* not required.
*/
public static final HttpStatusCode E_CONFLICT =
new HttpStatusCode("E_CONFLICT",HttpServletResponse.SC_CONFLICT);
/**
* <b>410 Gone</b>. The requested resource is no longer available at the server and no forwarding address
* is known. This condition is expected to be considered permanent. Clients with link editing capabilities
* SHOULD delete references to the Request-URI after user approval. If the server does not know, or has no
* facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) SHOULD
* be used instead.
*/
public static final HttpStatusCode E_GONE =
new HttpStatusCode("E_GONE",HttpServletResponse.SC_GONE);
/**
* <b>411 Length Required</b>. The server refuses to accept the request without a defined Content-Length.
* The client MAY repeat the request if it adds a valid Content-Length header field containing the length
* of the message-body in the request message.
*/
public static final HttpStatusCode E_NOLENGTH =
new HttpStatusCode("E_NOLENGTH",HttpServletResponse.SC_LENGTH_REQUIRED);
/**
* <b>412 Precondition Failed</b>. The precondition given in one or more of the request-header fields
* evaluated to false when it was tested on the server. This response code allows the client to place
* preconditions on the current resource metainformation (header field data) and thus prevent the
* requested method from being applied to a resource other than the one intended.
*/
public static final HttpStatusCode E_PRECONDITION =
new HttpStatusCode("E_PRECONDITION",HttpServletResponse.SC_PRECONDITION_FAILED);
/**
* <b>413 Request Entity Too Large</b>. The server is refusing to process a request because the request
* entity is larger than the server is willing or able to process. The server MAY close the connection to
* prevent the client from continuing the request. If the condition is temporary, the server SHOULD include
* a Retry-After header field to indicate that it is temporary and after what time the client MAY try again.
*/
public static final HttpStatusCode E_ENTITYTOOBIG =
new HttpStatusCode("E_ENTITYTOOBIG",HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
/**
* <b>414 Request URI Too Long</b>. The server is refusing to service the request because the Request-URI is
* longer than the server is willing to interpret. This rare condition is only likely to occur when a client
* has improperly converted a POST request to a GET request with long query information, when the client has
* descended into a URI "black hole" of redirection (e.g., a redirected URI prefix that points to a suffix of
* itself), or when the server is under attack by a client attempting to exploit security holes present in
* some servers using fixed-length buffers for reading or manipulating the Request-URI.
*/
public static final HttpStatusCode E_URITOOLONG =
new HttpStatusCode("E_URITOOLONG",HttpServletResponse.SC_REQUEST_URI_TOO_LONG);
/**
* <b>415 Media Type Not Supported</b>. The server is refusing to service the request because the entity of
* the request is in a format not supported by the requested resource for the requested method.
*/
public static final HttpStatusCode E_BAD_TYPE =
new HttpStatusCode("E_BAD_TYPE",HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
/**
* <b>416 Requested Range Not Satisfiable</b>. A server SHOULD return a response with this status code if
* a request included a Range request-header field, and none of the range-specifier values in this field
* overlap the current extent of the selected resource, and the request did not include an If-Range
* request-header field. (For byte-ranges, this means that the first-byte-pos of all of the byte-range-spec
* values were greater than the current length of the selected resource.) When this status code is returned
* for a byte-range request, the response SHOULD include a Content-Range entity-header field specifying the
* current length of the selected resource. This response MUST NOT use the multipart/byteranges content-type.
*/
public static final HttpStatusCode E_BAD_RANGE =
new HttpStatusCode("E_BAD_RANGE",HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
/**
* <b>417 Expectation Failed</b>. The expectation given in an Expect request-header field could not be met by
* this server, or, if the server is a proxy, the server has unambiguous evidence that the request could not
* be met by the next-hop server.
*/
public static final HttpStatusCode E_EXPECTATION =
new HttpStatusCode("E_EXPECTATION",HttpServletResponse.SC_EXPECTATION_FAILED);
/**
* <b>500 Internal Server Error</b>. The server encountered an unexpected condition which prevented it
* from fulfilling the request.
*/
public static final HttpStatusCode E_INTERNAL =
new HttpStatusCode("E_INTERNAL",HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
/**
* <b>501 Not Implemented</b>. The server does not support the functionality required to fulfill the request.
* This is the appropriate response when the server does not recognize the request method and is not capable
* of supporting it for any resource.
*/
public static final HttpStatusCode E_NOTIMPL =
new HttpStatusCode("E_NOTIMPL",HttpServletResponse.SC_NOT_IMPLEMENTED);
/**
* <b>502 Bad Gateway</b>. The server, while acting as a gateway or proxy, received an invalid response from
* the upstream server it accessed in attempting to fulfill the request.
*/
public static final HttpStatusCode E_BAD_GATEWAY =
new HttpStatusCode("E_BAD_GATEWAY",HttpServletResponse.SC_BAD_GATEWAY);
/**
* <b>503 Service Unavailable</b>. The server is currently unable to handle the request due to a temporary
* overloading or maintenance of the server. The implication is that this is a temporary condition which will
* be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header.
* If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.
*/
public static final HttpStatusCode E_UNAVAILABLE =
new HttpStatusCode("E_UNAVAILABLE",HttpServletResponse.SC_SERVICE_UNAVAILABLE);
/**
* <b>504 Gateway Timeout</b>. The server, while acting as a gateway or proxy, did not receive a timely
* response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary
* server (e.g. DNS) it needed to access in attempting to complete the request.
*/
public static final HttpStatusCode E_GATEWAY_TIMEOUT =
new HttpStatusCode("E_GATEWAY_TIMEOUT",HttpServletResponse.SC_GATEWAY_TIMEOUT);
/**
* <b>505 HTTP Version Not Supported</b>. The server does not support, or refuses to support, the HTTP
* protocol version that was used in the request message. The server is indicating that it is unable or
* unwilling to complete the request using the same major version as the client, other than with this
* error message. The response SHOULD contain an entity describing why that version is not supported and
* what other protocols are supported by that server.
*/
public static final HttpStatusCode E_BAD_VERSION =
new HttpStatusCode("E_BAD_VERSION",HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED);
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Internal constructor which creates a new element of this enumerated type.
*
* @param name The name of the <CODE>HttpStatusCode</CODE> to be created.
* @param value The numeric value to assign to the <CODE>HttpStatusCode</CODE>.
*/
private HttpStatusCode(String name, int value)
{
super(name,value);
} // end constructor
/*--------------------------------------------------------------------------------
* Standard static method implementations
*--------------------------------------------------------------------------------
*/
/**
* Gets a <CODE>HttpStatusCode</CODE> by name.
*
* @param name The name of the <CODE>HttpStatusCode</CODE> to get; may be <CODE>null</CODE>.
* @return The <CODE>HttpStatusCode</CODE> object, or <CODE>null</CODE> if the <CODE>HttpStatusCode</CODE>
* does not exist.
*/
public static HttpStatusCode getEnum(String name)
{
return (HttpStatusCode)getEnum(HttpStatusCode.class,name);
} // end getEnum
/**
* Gets a <CODE>HttpStatusCode</CODE> by numeric value.
*
* @param code The numeric value of the <CODE>HttpStatusCode</CODE> to get.
* @return The <CODE>HttpStatusCode</CODE> object, or <CODE>null</CODE> if the <CODE>HttpStatusCode</CODE>
* does not exist.
*/
public static HttpStatusCode getEnum(int code)
{
return (HttpStatusCode)getEnum(HttpStatusCode.class,code);
} // end getEnum
/**
* Gets the <CODE>Map</CODE> of <CODE>HttpStatusCode</CODE> objects by name.
*
* @return The <CODE>HttpStatusCode</CODE> object <CODE>Map</CODE>.
*/
public static Map getEnumMap()
{
return getEnumMap(HttpStatusCode.class);
} // end getEnumMap
/**
* Gets the <CODE>List</CODE> of <CODE>HttpStatusCode</CODE> objects, in the order in which the objects are listed
* in the code above.
*
* @return The <CODE>HttpStatusCode</CODE> object <CODE>List</CODE>.
*/
public static List getEnumList()
{
return getEnumList(HttpStatusCode.class);
} // end getEnumList
/**
* Gets an iterator over all <CODE>HttpStatusCode</CODE> objects, in the order in which the objects are listed
* in the code above.
*
* @return The <CODE>HttpStatusCode</CODE> object iterator.
*/
public static Iterator iterator()
{
return iterator(HttpStatusCode.class);
} // end iterator
} // end class HttpStatusCode

View File

@@ -0,0 +1,77 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo;
/**
* Contains various namespaces which are used to designate objects in the global
* {@link com.silverwrist.dynamo.iface.ObjectProvider ObjectProvider} and other contexts.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public interface Namespaces
{
/**
* Namespace used for objects provided by the application substrate object.
*/
public static final String SUBSTRATE_NAMESPACE =
"http://www.silverwrist.com/NS/dynamo/2002/11/29/substrate.objects";
/**
* Namespace used to retrieve servlet initialization parameters.
*/
public static final String SERVLET_INIT_NAMESPACE =
"http://www.silverwrist.com/NS/dynamo/2002/12/22/servlet.init.params";
/**
* Namespace used to retrieve servlet context initialization parameters.
*/
public static final String SERVLET_CONTEXT_NAMESPACE =
"http://www.silverwrist.com/NS/dynamo/2002/12/22/servlet.context.params";
/**
* Namespace under which the database connections are stored.
*/
public static final String DATABASE_CONNECTIONS_NAMESPACE =
"http://www.silverwrist.com/NS/dynamo/2002/12/08/database.connections";
/**
* Namespace under which the Dynamo objects are stored.
*/
public static final String DYNAMO_OBJECT_NAMESPACE =
"http://www.silverwrist.com/NS/dynamo/2002/12/07/dynamo.objects";
/**
* Namespace under which the Dynamo application-level objects are stored.
*/
public static final String DYNAMO_APPLICATION_NAMESPACE =
"http://www.silverwrist.com/NS/dynamo/2002/12/08/dynamo.application";
/**
* Namespace used to retrieve user information for mail messages.
*/
public static final String DYNAMO_USER_INFO_NAMESPACE =
"http://www.silverwrist.com/NS/dynamo/2002/12/13/user.information";
/**
* Namespace used to designate group permissions.
*/
public static final String GROUP_PERMISSIONS_NAMESPACE =
"http://www.silverwrist.com/NS/dynamo/2002/12/27/group.permissions";
} // end interface Namespaces

View File

@@ -0,0 +1,142 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo;
import java.util.*;
import org.apache.commons.lang.enum.*;
/**
* A type-safe enumerated type that indicates the type of a {@link com.silverwrist.dynamo.iface.Request Request}
* that comes in from the framework. It is also used to indicate the type of a
* {@link com.silverwrist.dynamo.iface.SessionInfo SessionInfo} object.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public final class RequestType extends Enum
{
/*--------------------------------------------------------------------------------
* The actual enumeration values
*--------------------------------------------------------------------------------
*/
/**
* A "null" request type, only used to label certain sessions.
*
* @see com.silverwrist.dynamo.util.NullSessionInfo
*/
public static final RequestType _NULL = new RequestType("_NULL");
/**
* This <CODE>RequestType</CODE> is used to label the {@link com.silverwrist.dynamo.iface.Request Request} passed
* along with the event that is fired when the application starts up.
*
* @see com.silverwrist.dynamo.event.ApplicationEvent
*/
public static final RequestType _APPLICATION = new RequestType("_APPLICATION");
/**
* This <CODE>RequestType</CODE> is used to label the {@link com.silverwrist.dynamo.iface.Request Request} passed
* along with the event that is fired when a new session is created.
*
* @see com.silverwrist.dynamo.event.SessionInfoEvent
*/
public static final RequestType _SESSION = new RequestType("_SESSION");
/**
* Designates a {@link com.silverwrist.dynamo.iface.Request Request} or
* {@link com.silverwrist.dynamo.iface.SessionInfo SessionInfo} associated with standard HTTP requests.
*/
public static final RequestType HTTP = new RequestType("HTTP");
/**
* Designates a {@link com.silverwrist.dynamo.iface.Request Request} or
* {@link com.silverwrist.dynamo.iface.SessionInfo SessionInfo} associated with XML-RPC requests, usually
* transmitted over HTTP.
*/
public static final RequestType XMLRPC = new RequestType("XMLRPC");
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Internal constructor which creates a new element of this enumerated type.
*
* @param name The name of the <CODE>RequestType</CODE> to be created.
*/
private RequestType(String name)
{
super(name);
} // end constructor
/*--------------------------------------------------------------------------------
* Standard static method implementations
*--------------------------------------------------------------------------------
*/
/**
* Gets a <CODE>RequestType</CODE> by name.
*
* @param name The name of the <CODE>RequestType</CODE> to get; may be <CODE>null</CODE>.
* @return The <CODE>RequestType</CODE> object, or <CODE>null</CODE> if the <CODE>RequestType</CODE> does not exist.
*/
public static RequestType getEnum(String name)
{
return (RequestType)getEnum(RequestType.class,name);
} // end getEnum
/**
* Gets the <CODE>Map</CODE> of <CODE>RequestType</CODE> objects by name.
*
* @return The <CODE>RequestType</CODE> object <CODE>Map</CODE>.
*/
public static Map getEnumMap()
{
return getEnumMap(RequestType.class);
} // end getEnumMap
/**
* Gets the <CODE>List</CODE> of <CODE>RequestType</CODE> objects, in the order in which the objects are listed
* in the code above.
*
* @return The <CODE>RequestType</CODE> object <CODE>List</CODE>.
*/
public static List getEnumList()
{
return getEnumList(RequestType.class);
} // end getEnumList
/**
* Gets an iterator over all <CODE>RequestType</CODE> objects, in the order in which the objects are listed
* in the code above.
*
* @return The <CODE>RequestType</CODE> object iterator.
*/
public static Iterator iterator()
{
return iterator(RequestType.class);
} // end iterator
} // end class RequestType

View File

@@ -0,0 +1,64 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo;
/**
* Describes the attributes used by the Dynamo mail component to retrieve user information. Also contains
* the name for the default authenticator and default user permissons.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public interface UserInfoNamespace
{
/**
* The property namespace that contains the user information.
*/
public static final String NAMESPACE = Namespaces.DYNAMO_USER_INFO_NAMESPACE;
/**
* Property name designating the user's full name.
*/
public static final String ATTR_FULLNAME = "full.name";
/**
* Property name designating the user E-mail address.
*/
public static final String ATTR_EMAIL_ADDRESS = "email.address";
/**
* Property name designating the numeric user ID.
*/
public static final String ATTR_ID = "user.id";
/**
* Property name designating the user name.
*/
public static final String ATTR_USERNAME = "user.name";
/**
* Used to designate the default hash password authenticator.
*/
public static final String AUTH_DEFAULT = "default.hash.password";
/**
* The permission that allows user information to be edited.
*/
public static final String PERM_EDIT_ALL = "edit.all";
} // end interface UserInfoNamespace

View File

@@ -0,0 +1,132 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo;
import java.util.*;
import org.apache.commons.lang.enum.*;
/**
* A type-safe enumerated type that indicates the action of a {@link com.silverwrist.dynamo.iface.Request Request}
* that comes in from the framework. <CODE>Verb</CODE> objects correspond roughly to HTTP methods.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public final class Verb extends Enum
{
/*--------------------------------------------------------------------------------
* The actual enumeration values
*--------------------------------------------------------------------------------
*/
/**
* Indicates a request to delete a resource identified by a URI. Corresponds to HTTP DELETE method.
*/
public static final Verb DELETE = new Verb("DELETE"); // (standard)
/**
* Indicates a request to retrieve a resource identified by a URI. Corresponds to HTTP GET method.
*/
public static final Verb GET = new Verb("GET"); // (standard)
/**
* Indicates a request to interact with a resource identified by a URI. Corresponds to HTTP POST method.
* All XML-RPC requests use this verb.
*/
public static final Verb POST = new Verb("POST"); // (standard)
/**
* Indicates a request to overwrite a resource identified by a URI. Corresponds to HTTP PUT method.
*/
public static final Verb PUT = new Verb("PUT"); // (standard)
/**
* Indicates a request to get the last modification time of a resource identified by a URI. Often associated
* with a HTTP GET method.
*/
public static final Verb _LASTMOD = new Verb("_LASTMOD"); // extended for getLastModified
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Internal constructor which creates a new element of this enumerated type.
*
* @param name The name of the <CODE>Verb</CODE> to be created.
*/
private Verb(String name)
{
super(name);
} // end constructor
/*--------------------------------------------------------------------------------
* Standard static method implementations
*--------------------------------------------------------------------------------
*/
/**
* Gets a <CODE>Verb</CODE> by name.
*
* @param name The name of the <CODE>Verb</CODE> to get; may be <CODE>null</CODE>.
* @return The <CODE>Verb</CODE> object, or <CODE>null</CODE> if the <CODE>Verb</CODE> does not exist.
*/
public static Verb getEnum(String name)
{
return (Verb)getEnum(Verb.class,name);
} // end getEnum
/**
* Gets the <CODE>Map</CODE> of <CODE>Verb</CODE> objects by name.
*
* @return The <CODE>Verb</CODE> object <CODE>Map</CODE>.
*/
public static Map getEnumMap()
{
return getEnumMap(Verb.class);
} // end getEnumMap
/**
* Gets the <CODE>List</CODE> of <CODE>Verb</CODE> objects, in the order in which the objects are listed
* in the code above.
*
* @return The <CODE>Verb</CODE> object <CODE>List</CODE>.
*/
public static List getEnumList()
{
return getEnumList(Verb.class);
} // end getEnumList
/**
* Gets an iterator over all <CODE>Verb</CODE> objects, in the order in which the objects are listed
* in the code above.
*
* @return The <CODE>Verb</CODE> object iterator.
*/
public static Iterator iterator()
{
return iterator(Verb.class);
} // end iterator
} // end class Verb

View File

@@ -0,0 +1,134 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo;
/**
* Contains the names of various application, session, and request attributes and initialization parameters
* used by the Dynamo servlet interface.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public interface WebConstants
{
/**
* Prefix for all Dynamo-specific application (<CODE>ServletContext</CODE>) attributes.
*/
public static final String APPLICATION_PREFIX = "com.silverwrist.dynamo.";
/**
* Application attribute that records whether or not logging has been initiated.
*/
public static final String LOGGING_ATTRIBUTE = APPLICATION_PREFIX + "LoggingStarted";
/**
* Application attribute that holds the Dynamo
* {@link com.silverwrist.dynamo.app.ApplicationContainer ApplicationContainer} object.
*/
public static final String APPLICATION_ATTRIBUTE = APPLICATION_PREFIX + "app.ApplicationContainer";
/**
* Application attribute used to store the {@link com.silverwrist.dynamo.iface.MIMETypeMapper MIMETypeMapper}
* object created to tap into the servlet container's MIME type maps.
*/
public static final String SERVLET_MAPPER_ATTRIBUTE = APPLICATION_PREFIX + "servlet.MIMETypeMapper";
/**
* Servlet context initialization parameter that tells Dynamo where to find the logging configuration file.
*/
public static final String LOGGING_INIT_PARAM = "logging.config";
/**
* Servlet context initialization parameter that tells Dynamo where to find the Dynamo XML configuration file.
*/
public static final String CONFIG_INIT_PARAM = "dynamo.config";
/**
* Prefix for all Dynamo-specific session (<CODE>HttpSession</CODE>) attributes.
*/
public static final String SESSION_PREFIX = "com.silverwrist.dynamo.";
/**
* Session attribute used to store the HTTP-specific {@link com.silverwrist.dynamo.iface.SessionInfo SessionInfo}
* object.
*/
public static final String SESSION_PARAM = SESSION_PREFIX + "session";
/**
* Session attribute used to store the connection-specific
* {@link com.silverwrist.dynamo.iface.BrowserData BrowserData} object.
*/
public static final String SESSION_BROWSER_DATA_PARAM = SESSION_PREFIX + "browser.data";
/**
* Prefix for all Dynamo-specific request (<CODE>ServletRequest</CODE>) attributes.
*/
public static final String REQUEST_PREFIX = "com.silverwrist.dynamo.";
/**
* Request attribute which stores the per-request
* {@link com.silverwrist.dynamo.iface.SessionInfoProvider SessionInfoProvider} object.
*/
public static final String REQUEST_SESSION_PROVIDER_ATTR = REQUEST_PREFIX + "session.provider";
/**
* Request attribute which contains a reference to a new HTTP session that must be initialized.
*/
public static final String REQUEST_SESSIONINIT_ATTR = REQUEST_PREFIX + "HTTPsession.init";
/**
* Request attribute which contains a reference to the connection-specific
* {@link com.silverwrist.dynamo.iface.BrowserData BrowserData} object.
*/
public static final String REQUEST_BROWSER_DATA_ATTR = REQUEST_PREFIX + "browser.data";
/**
* Request attribute which contains a reference to the set of all cookies currently defined
* on the connection.
*/
public static final String REQUEST_COOKIESET_ATTR = REQUEST_PREFIX + "browser.cookieset";
/**
* Request attribute containing a list of all new cookies set on the output, which cannot be set until
* the start of the output phase.
*/
public static final String REQUEST_NEWCOOKIEHOLDER_ATTR = REQUEST_PREFIX + "browser.NewCookieHolder";
/**
* Request attribute containing a list of all new headers set on the output, which cannot be set until
* the start of the output phase.
*/
public static final String REQUEST_NEWHEADERHOLDER_ATTR = REQUEST_PREFIX + "servlet.NewHeaderHolder";
/**
* Request attribute containing a backreference to the {@link com.silverwrist.dynamo.iface.Request Request}
* object for the current request.
*/
public static final String REQUEST_SELF_ATTR = REQUEST_PREFIX + "request.self";
/**
* The HTTP header which requests a page only if it's been modified since a specific time.
*/
public static final String HDR_IF_MODIFIED_SINCE = "If-Modified-Since";
/**
* The HTTP header which returns when a page was last modified.
*/
public static final String HDR_LAST_MODIFIED = "Last-Modified";
} // end interface WebConstants

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
# 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# ---------------------------------------------------------------------------------
# This file has been localized for the en_US locale
creation.ioError=Unable to read from configuration file {0}.
no.classNotFound=The object class {0} was not found.
no.createError=Unable to create new object of class {0}.
no.notDynamo=The object class {0} is not a valid Dynamo NamedObject,
no.notDBPool=The object class {0} is not a valid Dynamo database connection pool.
no.notApp=The object class {0} is not a valid Dynamo application.
resource.rootErr=The resource root directory {0} does not exist.
mountRP.badName=Invalid mount path for resources: {0}
mountRP.already=Resource provider already mounted on path {0}.
registerRenderer.already=Renderer already registered for class {0}.

View File

@@ -0,0 +1,675 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import java.util.*;
import org.apache.log4j.Logger;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class ApplicationServiceManager implements HookServiceProviders
{
/*--------------------------------------------------------------------------------
* Internal class implementing initialization services
*--------------------------------------------------------------------------------
*/
private class InitServices extends BaseDelegatingServiceProvider
{
/*====================================================================
* Constructors
*====================================================================
*/
InitServices()
{
super("Initialization Services");
} // end constructor
InitServices(ServiceProvider sp)
{
super("Initialization Services",sp);
} // end constructor
/*====================================================================
* Overrides from class BaseDelegatingServiceProvider
*====================================================================
*/
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass)
{
Object rc = m_init_service_cache.get(klass);
if (rc!=null) // found in the cache!
return rc;
for (int i=(m_init_service_hooks.size()-1); i>=0; i--)
{ // call the hooks
try
{ // get hooks in reverse order of installation and try them
ServiceProvider sp = (ServiceProvider)(m_init_service_hooks.get(i));
rc = sp.queryService(klass);
m_init_service_cache.put(klass,rc);
return rc;
} // end try
catch (NoSuchServiceException e)
{ // cycle around and keep trying
} // end catch
} // end for
rc = m_init_services.get(klass);
if (rc!=null)
{ // cache the service
m_init_service_cache.put(klass,rc);
return rc;
} // end if
return super.queryService(klass);
} // end queryService
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @param serviceid ID for the service to be requested, to further discriminate between requests.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass, String serviceid)
{
ServiceKey key = new ServiceKey(klass,serviceid);
Object rc = m_init_service_cache.get(key);
if (rc!=null)
return rc;
for (int i=(m_init_service_hooks.size()-1); i>=0; i--)
{ // call the hooks
try
{ // get hooks in reverse order of installation and try them
ServiceProvider sp = (ServiceProvider)(m_init_service_hooks.get(i));
rc = sp.queryService(klass,serviceid);
m_init_service_cache.put(key,rc);
return rc;
} // end try
catch (NoSuchServiceException e)
{ // cycle around and keep trying
} // end catch
} // end for
try
{ // call through to superclass
return super.queryService(klass,serviceid);
} // end try
catch (NoSuchServiceException e)
{ // OK, try it without the service ID
rc = queryService(klass);
m_init_service_cache.put(key,rc);
return rc;
} // end catch
} // end queryService
} // end class InitServices
/*--------------------------------------------------------------------------------
* Internal class implementing runtime services
*--------------------------------------------------------------------------------
*/
private class RuntimeServices extends BaseDelegatingServiceProvider
{
/*====================================================================
* Constructors
*====================================================================
*/
RuntimeServices()
{
super("Application Services");
} // end constructor
RuntimeServices(ServiceProvider sp)
{
super("Application Services",sp);
} // end constructor
/*====================================================================
* Overrides from class BaseDelegatingServiceProvider
*====================================================================
*/
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass)
{
Object rc = m_runtime_service_cache.get(klass);
if (rc!=null)
return rc;
for (int i=(m_runtime_service_hooks.size()-1); i>=0; i--)
{ // call the hooks
try
{ // get hooks in reverse order of installation and try them
ServiceProvider sp = (ServiceProvider)(m_runtime_service_hooks.get(i));
rc = sp.queryService(klass);
m_runtime_service_cache.put(klass,rc);
return rc;
} // end try
catch (NoSuchServiceException e)
{ // cycle around and keep trying
} // end catch
} // end for
rc = m_runtime_services.get(klass);
if (rc!=null)
{ // cache the service
m_runtime_service_cache.put(klass,rc);
return rc;
} // end if
return super.queryService(klass);
} // end queryService
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @param serviceid ID for the service to be requested, to further discriminate between requests.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass, String serviceid)
{
ServiceKey key = new ServiceKey(klass,serviceid);
Object rc = m_runtime_service_cache.get(key);
if (rc!=null)
return rc;
for (int i=(m_runtime_service_hooks.size()-1); i>=0; i--)
{ // call the hooks
try
{ // get hooks in reverse order of installation and try them
ServiceProvider sp = (ServiceProvider)(m_runtime_service_hooks.get(i));
rc = sp.queryService(klass,serviceid);
m_runtime_service_cache.put(key,rc);
return rc;
} // end try
catch (NoSuchServiceException e)
{ // cycle around and keep trying
} // end catch
} // end for
try
{ // call through to superclass
return super.queryService(klass,serviceid);
} // end try
catch (NoSuchServiceException e)
{ // OK, try it without the service ID
rc = queryService(klass);
m_runtime_service_cache.put(key,rc);
return rc;
} // end catch
} // end queryService
} // end class RuntimeServices
/*--------------------------------------------------------------------------------
* Internal class implementing output services
*--------------------------------------------------------------------------------
*/
private class OutputServices extends BaseDelegatingServiceProvider
{
/*====================================================================
* Constructors
*====================================================================
*/
OutputServices()
{
super("Application Output Services");
} // end constructor
OutputServices(ServiceProvider sp)
{
super("Application Output Services",sp);
} // end constructor
/*====================================================================
* Overrides from class BaseDelegatingServiceProvider
*====================================================================
*/
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass)
{
Object rc = m_output_service_cache.get(klass);
if (rc!=null)
return rc;
for (int i=(m_output_service_hooks.size()-1); i>=0; i--)
{ // call the hooks
try
{ // get hooks in reverse order of installation and try them
ServiceProvider sp = (ServiceProvider)(m_output_service_hooks.get(i));
rc = sp.queryService(klass);
m_output_service_cache.put(klass,rc);
return rc;
} // end try
catch (NoSuchServiceException e)
{ // cycle around and keep trying
} // end catch
} // end for
rc = m_output_services.get(klass);
if (rc!=null)
{ // cache the service
m_output_service_cache.put(klass,rc);
return rc;
} // end if
return super.queryService(klass);
} // end queryService
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @param serviceid ID for the service to be requested, to further discriminate between requests.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass, String serviceid)
{
ServiceKey key = new ServiceKey(klass,serviceid);
Object rc = m_output_service_cache.get(key);
if (rc!=null)
return rc;
for (int i=(m_output_service_hooks.size()-1); i>=0; i--)
{ // call the hooks
try
{ // get hooks in reverse order of installation and try them
ServiceProvider sp = (ServiceProvider)(m_output_service_hooks.get(i));
rc = sp.queryService(klass,serviceid);
m_output_service_cache.put(key,rc);
return rc;
} // end try
catch (NoSuchServiceException e)
{ // cycle around and keep trying
} // end catch
} // end for
try
{ // call through to superclass
return super.queryService(klass,serviceid);
} // end try
catch (NoSuchServiceException e)
{ // OK, try it without the service ID
rc = queryService(klass);
m_output_service_cache.put(key,rc);
return rc;
} // end catch
} // end queryService
} // end class OutputServices
/*--------------------------------------------------------------------------------
* Internal class implementing removal of init service hook
*--------------------------------------------------------------------------------
*/
private class RemoveInitServiceHook implements ComponentShutdown
{
/*====================================================================
* Attributes
*====================================================================
*/
private ServiceProvider m_sp;
/*====================================================================
* Constructor
*====================================================================
*/
RemoveInitServiceHook(ServiceProvider sp)
{
m_sp = sp;
} // end constructor
/*====================================================================
* Implementations from interface ComponentShutdown
*====================================================================
*/
public void shutdown()
{
m_init_service_hooks.remove(m_sp);
m_init_service_cache.clear();
} // end shutdown
} // end class RemoveInitServiceHook
/*--------------------------------------------------------------------------------
* Internal class implementing removal of runtime service hook
*--------------------------------------------------------------------------------
*/
private class RemoveRuntimeServiceHook implements ComponentShutdown
{
/*====================================================================
* Attributes
*====================================================================
*/
private ServiceProvider m_sp;
/*====================================================================
* Constructor
*====================================================================
*/
RemoveRuntimeServiceHook(ServiceProvider sp)
{
m_sp = sp;
} // end constructor
/*====================================================================
* Implementations from interface ComponentShutdown
*====================================================================
*/
public void shutdown()
{
m_runtime_service_hooks.remove(m_sp);
m_runtime_service_cache.clear();
} // end shutdown
} // end class RemoveRuntimeServiceHook
/*--------------------------------------------------------------------------------
* Internal class implementing removal of output service hook
*--------------------------------------------------------------------------------
*/
private class RemoveOutputServiceHook implements ComponentShutdown
{
/*====================================================================
* Attributes
*====================================================================
*/
private ServiceProvider m_sp;
/*====================================================================
* Constructor
*====================================================================
*/
RemoveOutputServiceHook(ServiceProvider sp)
{
m_sp = sp;
} // end constructor
/*====================================================================
* Implementations from interface ComponentShutdown
*====================================================================
*/
public void shutdown()
{
m_output_service_hooks.remove(m_sp);
m_output_service_cache.clear();
} // end shutdown
} // end class RemoveOutputServiceHook
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Logger logger = Logger.getLogger(ApplicationServiceManager.class);
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Hashtable m_init_services = new Hashtable(); // initializing services
private Vector m_init_service_hooks = new Vector(); // hooks for initializing services
private Hashtable m_init_service_cache = new Hashtable(); // cache of init services
private Hashtable m_runtime_services = new Hashtable(); // runtime services
private Vector m_runtime_service_hooks = new Vector(); // hooks for runtime services
private Hashtable m_runtime_service_cache = new Hashtable(); // cache of runtime services
private Hashtable m_output_services = new Hashtable(); // output services
private Vector m_output_service_hooks = new Vector(); // hooks for output services
private Hashtable m_output_service_cache = new Hashtable(); // cache of output services
private InitServices m_solo_init = null; // only one "null" init service
private RuntimeServices m_solo_runtime = null; // only one "null" runtime service
private OutputServices m_solo_output = null; // only one "null" output service
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
ApplicationServiceManager()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface HookServiceProviders
*--------------------------------------------------------------------------------
*/
public ServiceProvider getCurrentInitServices()
{
return createInitServices();
} // end getCurrentInitServices
public ServiceProvider getCurrentRuntimeServices()
{
return createRuntimeServices();
} // end getCurrentRuntimeServices
public ServiceProvider getCurrentOutputServices()
{
return createOutputServices();
} // end getCurrentOutputServices
public ComponentShutdown hookInitServiceProvider(ServiceProvider sp)
{
m_init_service_hooks.add(sp);
m_init_service_cache.clear();
return new RemoveInitServiceHook(sp);
} // end hookInitServiceProvider
public ComponentShutdown hookRuntimeServiceProvider(ServiceProvider sp)
{
m_runtime_service_hooks.add(sp);
m_runtime_service_cache.clear();
return new RemoveRuntimeServiceHook(sp);
} // end hookRuntimeServiceProvider
public ComponentShutdown hookOutputServiceProvider(ServiceProvider sp)
{
m_output_service_hooks.add(sp);
m_output_service_cache.clear();
return new RemoveOutputServiceHook(sp);
} // end hookOutputServiceProvider
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
void addInitService(Class klass, Object svc)
{
m_init_services.put(klass,svc);
} // end addInitService
void addRuntimeService(Class klass, Object svc)
{
m_runtime_services.put(klass,svc);
} // end addRuntimeService
void addOutputService(Class klass, Object svc)
{
m_output_services.put(klass,svc);
} // end addRuntimeService
ServiceProvider createInitServices()
{
if (m_solo_init==null)
m_solo_init = new InitServices();
return m_solo_init;
} // end createInitServices
ServiceProvider createInitServices(ServiceProvider sp)
{
if (sp==null)
return createInitServices();
return new InitServices(sp);
} // end createRuntimeServices
ServiceProvider createRuntimeServices()
{
if (m_solo_runtime==null)
m_solo_runtime = new RuntimeServices();
return m_solo_runtime;
} // end createRuntimeServices
ServiceProvider createRuntimeServices(ServiceProvider sp)
{
if (sp==null)
return createRuntimeServices();
return new RuntimeServices(sp);
} // end createRuntimeServices
ServiceProvider createOutputServices()
{
if (m_solo_output==null)
m_solo_output = new OutputServices();
return m_solo_output;
} // end createOutputServices
ServiceProvider createOutputServices(ServiceProvider sp)
{
if (sp==null)
return createOutputServices();
return new OutputServices(sp);
} // end createOutputServices
} // end class ApplicationServiceManager

View File

@@ -0,0 +1,490 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import java.util.*;
import org.apache.log4j.Logger;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
/**
* A class used internally by the {@link com.silverwrist.dynamo.app.ApplicationContainer ApplicationContainer}
* to handle background execution of tasks. It implements the
* {@link com.silverwrist.dynamo.iface.BackgroundScheduler BackgroundScheduler} service.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
class BackgroundProcessor implements BackgroundScheduler, ComponentShutdown
{
/*--------------------------------------------------------------------------------
* Internal thread class for scheduling normal-priority background tasks
*--------------------------------------------------------------------------------
*/
private class NormalPriorityThread extends Thread
{
/*====================================================================
* Constructor
*====================================================================
*/
NormalPriorityThread(int index)
{
super("BG-Normal-" + index);
setPriority(NORM_PRIORITY);
} // end constructor
/*====================================================================
* Overrides from class Thread
*====================================================================
*/
public void run()
{
while (m_running)
{ // get tasks then execute them
BackgroundTask task = null;
synchronized (m_normal_sync)
{ // test and remove from normal queue
boolean get_task = true;
while (get_task && m_normal_queue.isEmpty())
{ // nothing to run right now...
try
{ // sleep waiting for a new background task
m_normal_sync.wait();
} // end try
catch (InterruptedException e)
{ // don't bother getting a task
get_task = false;
} // end catch
} // end if
if (get_task)
task = (BackgroundTask)(m_normal_queue.removeFirst());
} // end synchronized block
if (task!=null)
{ // found a task to run, now execute it
try
{ // run the task
task.run(m_services);
task = null;
} // end try
catch (Exception e)
{ // whoops! don't let this stop us
logger.warn("BackgroundTask threw exception",e);
} // end catch
} // end if
} // end while
} // end run
} // end class NormalPriorityThread
/*--------------------------------------------------------------------------------
* Internal thread class for scheduling low-priority background tasks
*--------------------------------------------------------------------------------
*/
private class LowPriorityThread extends Thread
{
/*====================================================================
* Constructor
*====================================================================
*/
LowPriorityThread(int index)
{
super("BG-Low-" + index);
setPriority(MIN_PRIORITY);
} // end constructor
/*====================================================================
* Overrides from class Thread
*====================================================================
*/
public void run()
{
while (m_running)
{ // get tasks then execute them
BackgroundTask task = null;
synchronized (m_lp_sync)
{ // test and remove from normal queue
boolean get_task = true;
while (get_task && m_lp_queue.isEmpty())
{ // nothing to run right now...
try
{ // sleep waiting for a new background task
m_lp_sync.wait();
} // end try
catch (InterruptedException e)
{ // don't bother getting a task
get_task = false;
} // end catch
} // end if
// Get the task we waited for.
if (get_task)
task = (BackgroundTask)(m_lp_queue.removeFirst());
} // end synchronized block
if (task!=null)
{ // found a task to run, now execute it
try
{ // run the task
task.run(m_services);
task = null;
} // end try
catch (Exception e)
{ // whoops! don't let this stop us
logger.warn("BackgroundTask threw exception",e);
} // end catch
} // end if
} // end while
} // end run
} // end class LowPriorityThread
/*--------------------------------------------------------------------------------
* Internal class for timer operations
*--------------------------------------------------------------------------------
*/
private class MyTimerTask extends TimerTask implements ComponentShutdown
{
/*====================================================================
* Attributes
*====================================================================
*/
private BackgroundTask m_task;
/*====================================================================
* Constructor
*====================================================================
*/
MyTimerTask(BackgroundTask task)
{
super();
m_task = task;
} // end constructor
/*====================================================================
* Overrides from class TimerTask
*====================================================================
*/
public void run()
{
try
{ // run the task
m_task.run(m_services);
} // end try
catch (Exception e)
{ // whoops! don't let this stop us
logger.warn("BackgroundTask threw exception",e);
} // end catch
} // end run
/*====================================================================
* Implementations from interface ComponentShutdown
*====================================================================
*/
/**
* Shuts down the component associated with this interface, in a component-specific manner.
*/
public void shutdown()
{
cancel();
} // end shutdown
} // end class MyTimerTask
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Logger logger = Logger.getLogger(BackgroundProcessor.class);
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private ServiceProvider m_services;
private volatile boolean m_running = true;
private Object m_normal_sync = new Object();
private LinkedList m_normal_queue = new LinkedList();
private Thread[] m_normal_threads;
private Object m_lp_sync = new Object();
private LinkedList m_lp_queue = new LinkedList();
private Thread[] m_lp_threads;
private Timer m_timer;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Constructs the instance of the <CODE>BackgroundProcessor</CODE> internal to the
* {@link com.silverwrist.dynamo.app.ApplicationContainer ApplicationContainer}.
*
* @param num_normal_threads Number of "normal" threads in our runtime thread pool.
* @param num_lp_threads Number of "low priority" threads in our runtime thread pool.
* @param services The {@link com.silverwrist.dynamo.iface.ServiceProvider ServiceProvider} to be supplied
* to all {@link com.silverwrist.dynamo.iface.BackgroundTask BackgroundTask}s.
*/
BackgroundProcessor(int num_norm_threads, int num_lp_threads, ServiceProvider services)
{
m_services = new SingletonServiceProvider("BackgroundProcessor",services,BackgroundScheduler.class,this);
// Create the normal priority background threads.
m_normal_threads = new Thread[num_norm_threads];
int i;
for (i=0; i<num_norm_threads; i++)
m_normal_threads[i] = new NormalPriorityThread(i);
// Create the low priority background threads.
m_lp_threads = new Thread[num_lp_threads];
for (i=0; i<num_lp_threads; i++)
m_lp_threads[i] = new LowPriorityThread(i);
// Create the timer.
m_timer = new Timer();
// Start everything up.
for (i=0; i<num_norm_threads; i++)
m_normal_threads[i].start();
for (i=0; i<num_lp_threads; i++)
m_lp_threads[i].start();
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface BackgroundScheduler
*--------------------------------------------------------------------------------
*/
/**
* Schedule a task to be run "later," i.e., at any time after the present time, without interrupting the
* current thread's processing. Background processing of tasks submitted by this method are handled by a
* pool of threads.
*
* @param task The task to be scheduled to run later.
* @param low_priority If this is <CODE>true</CODE>, the task is handled by a pool of low-priority threads
* instead of by a pool of normal-priority threads. Low-priority threads will generally
* execute only after normal-priority threads, but are not guaranteed to.
*/
public void runTaskLater(BackgroundTask task, boolean low_priority)
{
if (low_priority)
{ // add to low priority queue
synchronized (m_lp_sync)
{ // add item and notify a thread to wake up
m_lp_queue.addLast(task);
m_lp_sync.notify();
} // end synchronized block
} // end if
else
{ // add to normal queue
synchronized (m_normal_sync)
{ // add item and notify a thread to wake up
m_normal_queue.addLast(task);
m_normal_sync.notify();
} // end synchronized block
} // end else
} // end runTaskLater
/**
* Schedule a task to be run on a one-shot basis after a delay.
*
* @param task The task to be scheduled to run.
* @param delay The delay, in milliseconds, before this task is to be run. The actual delay may be longer
* than this.
* @return An instance of a {@link com.silverwrist.dynamo.iface.ComponentShutdown ComponentShutdown} object,
* whose {@link com.silverwrist.dynamo.iface.ComponentShutdown#shutdown() shutdown()} method may be
* called to abort the execution of this task at any time before it is actually run. If this is called
* after the task is run, it has no effect.
*/
public ComponentShutdown runTaskAfter(BackgroundTask task, long delay)
{
MyTimerTask my_task = new MyTimerTask(task);
m_timer.schedule(my_task,delay);
return my_task;
} // end runTaskAfter
/**
* Schedule a task to be run on a one-shot basis at a certain time.
*
* @param task The task to be scheduled to run.
* @param when The date/time at which the task is to be run. The actual task start time may be any time
* after this.
* @return An instance of a {@link com.silverwrist.dynamo.iface.ComponentShutdown ComponentShutdown} object,
* whose {@link com.silverwrist.dynamo.iface.ComponentShutdown#shutdown() shutdown()} method may be
* called to abort the execution of this task at any time before it is actually run. If this is called
* after the task is run, it has no effect.
*/
public ComponentShutdown runTaskAt(BackgroundTask task, Date when)
{
MyTimerTask my_task = new MyTimerTask(task);
m_timer.schedule(my_task,when);
return my_task;
} // end runTaskAt
/**
* Schedule a task to be run periodically, after a delay.
*
* @param task The task to be scheduled to run.
* @param delay The delay, in milliseconds, before this task is to be run for the first time. The actual
* delay may be longer than this.
* @param period The time, in milliseconds, between successive executions of the task. The task will be
* scheduled for repeated execution, delaying at least this long between executions.
* @return An instance of a {@link com.silverwrist.dynamo.iface.ComponentShutdown ComponentShutdown} object,
* whose {@link com.silverwrist.dynamo.iface.ComponentShutdown#shutdown() shutdown()} method may be
* called to abort the periodic execution of this task at any time.
*/
public ComponentShutdown runTaskPeriodic(BackgroundTask task, long delay, long period)
{
MyTimerTask my_task = new MyTimerTask(task);
m_timer.schedule(my_task,delay,period);
return my_task;
} // end runTaskPeriodic
/**
* Schedule a task to be run periodically, beginning at a specified time.
*
* @param task The task to be scheduled to run.
* @param when The date/time at which the task is to be run for the first time. The actual task start time
* may be any time after this.
* @param period The time, in milliseconds, between successive executions of the task. The task will be
* scheduled for repeated execution, delaying at least this long between executions.
* @return An instance of a {@link com.silverwrist.dynamo.iface.ComponentShutdown ComponentShutdown} object,
* whose {@link com.silverwrist.dynamo.iface.ComponentShutdown#shutdown() shutdown()} method may be
* called to abort the periodic execution of this task at any time.
*/
public ComponentShutdown runTaskPeriodic(BackgroundTask task, Date start, long period)
{
MyTimerTask my_task = new MyTimerTask(task);
m_timer.schedule(my_task,start,period);
return my_task;
} // end runTaskPeriodic
/**
* Schedule a task to be run periodically, after a delay.
*
* @param task The task to be scheduled to run.
* @param delay The delay, in milliseconds, before this task is to be run for the first time. The actual
* delay may be longer than this.
* @param period The time, in milliseconds, between successive executions of the task. The task will be
* scheduled for repeated execution, with the task being started with roughly this many
* milliseconds between each start attempt. If execution is delayed, this task will try to
* "catch up" by scheduling executions more frequently.
* @return An instance of a {@link com.silverwrist.dynamo.iface.ComponentShutdown ComponentShutdown} object,
* whose {@link com.silverwrist.dynamo.iface.ComponentShutdown#shutdown() shutdown()} method may be
* called to abort the periodic execution of this task at any time.
*/
public ComponentShutdown runTaskFixedRate(BackgroundTask task, long delay, long period)
{
MyTimerTask my_task = new MyTimerTask(task);
m_timer.scheduleAtFixedRate(my_task,delay,period);
return my_task;
} // end runTaskFixedRate
/**
* Schedule a task to be run periodically, beginning at a specified time.
*
* @param task The task to be scheduled to run.
* @param when The date/time at which the task is to be run for the first time. The actual task start time
* may be any time after this.
* @param period The time, in milliseconds, between successive executions of the task. The task will be
* scheduled for repeated execution, with the task being started with roughly this many
* milliseconds between each start attempt. If execution is delayed, this task will try to
* "catch up" by scheduling executions more frequently.
* @return An instance of a {@link com.silverwrist.dynamo.iface.ComponentShutdown ComponentShutdown} object,
* whose {@link com.silverwrist.dynamo.iface.ComponentShutdown#shutdown() shutdown()} method may be
* called to abort the periodic execution of this task at any time.
*/
public ComponentShutdown runTaskFixedRate(BackgroundTask task, Date start, long period)
{
MyTimerTask my_task = new MyTimerTask(task);
m_timer.scheduleAtFixedRate(my_task,start,period);
return my_task;
} // end runTaskFixedRate
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
/**
* Shuts down the <CODE>BackgroundProcessor</CODE>, stopping all its associated threads and tasks.
*/
public void shutdown()
{
m_timer.cancel();
m_running = false;
int i;
for (i=0; i<m_normal_threads.length; i++)
m_normal_threads[i].interrupt();
for (i=0; i<m_lp_threads.length; i++)
m_lp_threads[i].interrupt();
} // end shutdown
} // end class BackgroundProcessor

View File

@@ -0,0 +1,123 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
class ComponentResName
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String[] m_components;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
ComponentResName(String resource_path)
{
if (!(resource_path.startsWith("/")))
throw new NoSuchResourceException(resource_path);
m_components = StringUtils.split(resource_path.substring(1),"/");
if ((m_components==null) || (m_components.length==0))
throw new NoSuchResourceException(resource_path);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class Object
*--------------------------------------------------------------------------------
*/
public boolean equals(Object obj)
{
if ((obj==null) || !(obj instanceof ComponentResName))
return false;
ComponentResName other = (ComponentResName)obj;
if (m_components.length!=other.m_components.length)
return false;
return (getMatchCount(other)==m_components.length);
} // end equals
public int hashCode()
{
int rc = 0;
for (int i=0; i<m_components.length; i++)
rc ^= m_components[i].hashCode();
return rc;
} // end hashCode
public String toString()
{
return getStringValue(0,true);
} // end toString
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
int getComponentCount()
{
return m_components.length;
} // end getComponentCount
int getMatchCount(ComponentResName other)
{
int max_count = Math.min(other.m_components.length,m_components.length);
for (int i=0; i<max_count; i++)
{ // if a component does not match, return the count immediately
if (!(m_components[i].equals(other.m_components[i])))
return i;
} // end for
return max_count; // all components matched
} // end getMatchCount
String getStringValue(int skip_initial, boolean prefix_slash)
{
StringBuffer rc = new StringBuffer();
if (prefix_slash)
rc.append('/');
boolean need_sep = false;
for (int i=skip_initial; i<m_components.length; i++)
{ // append together components
if (need_sep)
rc.append('/');
else
need_sep = true;
rc.append(m_components[i]);
} // end for
return rc.toString();
} // end getStringValue
} // end class ComponentResName

View File

@@ -0,0 +1,221 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
public class ConnectionManager implements NamedObject, ComponentInitialize, ComponentShutdown
{
/*--------------------------------------------------------------------------------
* Internal class implementing the initialization service hook
*--------------------------------------------------------------------------------
*/
private class InitService implements ServiceProvider, ConnectionFrontEnd, ConnectionBackEnd
{
/*====================================================================
* Constructor
*====================================================================
*/
InitService()
{ // do nothing
} // end constructor
/*====================================================================
* Implementations from interface ServiceProvider
*====================================================================
*/
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass)
{
if (klass==ConnectionFrontEnd.class)
return (ConnectionFrontEnd)this;
if (klass==ConnectionBackEnd.class)
return (ConnectionBackEnd)this;
throw new NoSuchServiceException("ConnectionManager.InitService",klass);
} // end queryService
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @param serviceid ID for the service to be requested, to further discriminate between requests.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass, String serviceid)
{
if (klass==ConnectionFrontEnd.class)
return (ConnectionFrontEnd)this;
if (klass==ConnectionBackEnd.class)
return (ConnectionBackEnd)this;
throw new NoSuchServiceException("ConnectionManager.InitService",klass,serviceid);
} // end queryService
/*====================================================================
* Implementations from interface ConnectionFrontEnd
*====================================================================
*/
public Object getInterface(String connection_point, Class expected_class) throws ConfigException
{
return getConnectionPoint(connection_point).getInterface(expected_class);
} // end getInterface
/*====================================================================
* Implementations from interface ConnectionBackEnd
*====================================================================
*/
public void connectObject(String connection_point, Object object) throws ConfigException
{
getConnectionPoint(connection_point).connectObject(object);
} // end connectObject
} // end class InitService
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name;
private Hashtable m_connection_points = new Hashtable();
private ComponentShutdown m_shutdown_hook;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ConnectionManager()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private final ConnectionPoint getConnectionPoint(String name) throws ConfigException
{
ConnectionPoint rc = (ConnectionPoint)(m_connection_points.get(name));
if (rc!=null)
return rc;
ConfigException ce = new ConfigException(ConnectionPoint.class,"ConnectionMessages","cpoint.notFound");
ce.setParameter(0,name);
throw ce;
} // end getConnectionPoint
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentInitialize
*--------------------------------------------------------------------------------
*/
public void initialize(Element config_root, ServiceProvider services) throws ConfigException
{
XMLLoader loader = XMLLoader.get();
try
{ // verify the right node name
loader.verifyNodeName(config_root,"object");
// get the object's name
m_name = loader.getAttribute(config_root,"name");
// get the connection points list and try to load them
List l = loader.getMatchingSubElements(config_root,"connection-point");
Iterator it = l.iterator();
while (it.hasNext())
{ // create the connection points
Element elt = (Element)(it.next());
ConnectionPoint cpoint = new ConnectionPoint(elt);
m_connection_points.put(cpoint.getName(),cpoint);
} // end while
} // end try
catch (XMLLoadException e)
{ // error loading XML config data
throw new ConfigException(e);
} // end catch
// Hook the init service provider to provide our services.
HookServiceProviders hooker = (HookServiceProviders)(services.queryService(HookServiceProviders.class));
m_shutdown_hook = hooker.hookInitServiceProvider(new InitService());
} // end initialize
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
public void shutdown()
{
m_shutdown_hook.shutdown();
Iterator it = m_connection_points.values().iterator();
while (it.hasNext())
{ // shut down those connection points
ComponentShutdown cs = (ComponentShutdown)(it.next());
cs.shutdown();
} // end while
m_connection_points.clear();
} // end shutdown
} // end class ConnectionManager

View File

@@ -0,0 +1,23 @@
# The contents of this file are subject to the Mozilla Public License Version 1.1
# (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
#
# Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
# WARRANTY OF ANY KIND, either express or implied. See the License for the specific
# language governing rights and limitations under the License.
#
# The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# ---------------------------------------------------------------------------------
# This file has been localized for the en_US locale
cpoint.noInterface=Unable to find the connection point interface class "{0}".
cpoint.notValid=The connection point class "{0}" is not a valid interface.
iface.type=Connection point "{0}"'s interface type {1} cannot be assigned to the desired type {2}.
connect.already=The connection point "{0}" has already been connected.
connect.wrongType=The connection point "{0}" expects to connect to an object of type {1}.
cpoint.notFound=No connection point "{0}" defined.

View File

@@ -0,0 +1,179 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import java.lang.reflect.*;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
class ConnectionPoint implements NamedObject, InvocationHandler, ComponentShutdown
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name; // name of this connection point
private Class m_interface; // interface associated with this connection point
private Object m_proxy_obj; // proxy object that provides the "head end" of the cpoint
private Object m_target_obj = null; // object on the "tail end" of the cpoint
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
ConnectionPoint(Element config) throws ConfigException
{
XMLLoader loader = XMLLoader.get();
String iface_name = null;
try
{ // verify the right node name
loader.verifyNodeName(config,"connection-point");
// get the connection point's name
m_name = loader.getAttribute(config,"name");
// get the interface represented by this proxy
iface_name = loader.getAttribute(config,"interface");
m_interface = Class.forName(iface_name);
if (!(m_interface.isInterface()))
{ // the class name does not specify an interface
ConfigException ce = new ConfigException(ConnectionPoint.class,"ConnectionMessages",
"cpoint.notValid");
ce.setParameter(0,iface_name);
throw ce;
} // end if
// Create the proxy object.
Class[] arg = new Class[1];
arg[0] = m_interface;
m_proxy_obj = Proxy.newProxyInstance(m_interface.getClassLoader(),arg,this);
} // end try
catch (XMLLoadException e)
{ // error loading XML config data
throw new ConfigException(e);
} // end catch
catch (ClassNotFoundException e)
{ // unable to find the interface
ConfigException ce = new ConfigException(ConnectionPoint.class,"ConnectionMessages",
"cpoint.noInterface",e);
ce.setParameter(0,iface_name);
throw ce;
} // end catch
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface InvocationHandler
*--------------------------------------------------------------------------------
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
if (m_target_obj==null)
throw new ProxyException(new NullPointerException("target not yet connected for " + m_name + "/"
+ m_interface.getName()));
try
{ // invoke the method on the real target!
return method.invoke(m_target_obj,args);
} // end try
catch (IllegalAccessException e)
{ // turn into the runtime ProxyException
throw new ProxyException(e);
} // end catch
catch (InvocationTargetException e)
{ // "unwrap" this exception type and throw it
throw e.getCause();
} // end catch
} // end invoke
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
public void shutdown()
{
m_proxy_obj = null;
m_target_obj = null;
} // end shutdown
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
Object getInterface(Class expected_class) throws ConfigException
{
if (expected_class.isAssignableFrom(m_interface))
return m_proxy_obj;
ConfigException ce = new ConfigException(ConnectionPoint.class,"ConnectionMessages","iface.type");
ce.setParameter(0,m_name);
ce.setParameter(1,m_interface.getName());
ce.setParameter(2,expected_class.getName());
throw ce;
} // end getInterface
synchronized void connectObject(Object obj) throws ConfigException
{
if (m_target_obj!=null)
{ // this connection point has already been connected
ConfigException ce = new ConfigException(ConnectionPoint.class,"ConnectionMessages","connect.already");
ce.setParameter(0,m_name);
throw ce;
} // end if
if (!(m_interface.isInstance(obj)))
{ // the object is of the wrong type
ConfigException ce = new ConfigException(ConnectionPoint.class,"ConnectionMessages","connect.wrongType");
ce.setParameter(0,m_name);
ce.setParameter(1,m_interface.getName());
throw ce;
} // end if
m_target_obj = obj;
} // end connectObject
} // end class ConnectionPoint

View File

@@ -0,0 +1,52 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import java.io.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.RenderingException;
import com.silverwrist.dynamo.iface.*;
class DataItemRenderer implements BinaryRenderer
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
DataItemRenderer()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface BinaryRenderer
*--------------------------------------------------------------------------------
*/
public void render(Object obj, BinaryRenderControl control) throws IOException, RenderingException
{
DataItem di = (DataItem)obj;
control.setContentType(di.getMimeType());
control.setContentLength(di.getSize());
OutputStream stm = control.getStream();
IOUtils.copy(di.getDataStream(),stm);
stm.flush();
} // end render
} // end class DataItemRenderer

View File

@@ -0,0 +1,88 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import org.w3c.dom.Element;
import com.silverwrist.util.xml.*;
class HeapContents implements Comparable
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
Element m_elt; // element we're sorting
int m_priority; // its priority
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
HeapContents(Element elt) throws XMLLoadException
{
m_elt = elt;
m_priority = XMLLoader.get().getAttributeInt(elt,"priority",0);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class Object
*--------------------------------------------------------------------------------
*/
public boolean equals(Object o)
{
if (!(o instanceof HeapContents))
return false;
HeapContents other = (HeapContents)o;
return (m_priority==other.m_priority);
} // end equals
public int hashCode()
{
return m_priority;
} // end hashCode
/*--------------------------------------------------------------------------------
* Implementations from interface Comparable
*--------------------------------------------------------------------------------
*/
public int compareTo(Object o)
{
HeapContents other = (HeapContents)o; // may throw ClassCastException
return m_priority - other.m_priority;
} // end compareTo
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
Element getElement()
{
return m_elt;
} // end getElement
} // end class HeapContents

View File

@@ -0,0 +1,50 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import java.io.IOException;
import java.util.*;
import com.silverwrist.dynamo.except.RenderingException;
import com.silverwrist.dynamo.iface.*;
class ListRenderer implements TextRenderer
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
ListRenderer()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface TextRenderer
*--------------------------------------------------------------------------------
*/
public void render(Object obj, TextRenderControl control) throws IOException, RenderingException
{
List list = (List)obj;
Iterator it = list.iterator();
while (it.hasNext())
control.renderSubObject(it.next());
} // end render
} // end class ListRenderer

View File

@@ -0,0 +1,270 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import java.text.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class PropertySerializationSupport implements PropertySerializer, PropertySerializerRegistration
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final Map SIMPLE_TYPE_SERIALIZE;
private static final DateFormat s_iso8601;
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private static Vector m_extern_calls = new Vector();
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
PropertySerializationSupport()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private final String builtinSerialize(Object value)
{
String prefix = (String)(SIMPLE_TYPE_SERIALIZE.get(value.getClass()));
if (prefix!=null)
return prefix + value.toString();
if (value instanceof Boolean)
return (((Boolean)value).booleanValue() ? "Y" : "Z");
if (value instanceof java.util.Date)
return "T" + s_iso8601.format((java.util.Date)value);
if (value instanceof TimeZone)
return "_TZ:" + ((TimeZone)value).getID();
if (value instanceof Language)
return "_LANG:" + ((Language)value).getCode();
if (value instanceof Country)
return "_CTRY:" + ((Country)value).getCode();
if (value instanceof OptionSet)
return "_OS:" + ((OptionSet)value).asString();
return null;
} // end builtInSerialize
private final Object extendedDecode(String s)
{
if (s.startsWith("_LOC:"))
{ // need to break down
s = s.substring(5);
int p = s.indexOf('_');
if (p>=0)
{ // language + country, maybe + variant
String language = s.substring(0,p);
s = s.substring(p+1);
p = s.indexOf('_');
if (p>=0)
return new Locale(language,s.substring(0,p),s.substring(p+1));
else
return new Locale(language,s);
} // end if
else // just language
return new Locale(s);
} // end if
else if (s.startsWith("_TZ:"))
return TimeZone.getTimeZone(s.substring(4));
else if (s.startsWith("_LANG:"))
return International.get().getLanguageForCode(s.substring(6));
else if (s.startsWith("_CTRY:"))
return International.get().getCountryForCode(s.substring(6));
else if (s.startsWith("_OS:"))
return new OptionSet(s.substring(4));
else
return null;
} // end extendedDecode
/*--------------------------------------------------------------------------------
* Implementations from interface PropertySerializer
*--------------------------------------------------------------------------------
*/
public String serializeProperty(Object value)
{
if (value==null)
return null;
String rc = builtinSerialize(value);
if (rc!=null)
return rc;
Iterator it = m_extern_calls.iterator();
while (it.hasNext())
{ // try the external serializers
PropertySerializer psz = (PropertySerializer)(it.next());
rc = psz.serializeProperty(value);
if (rc!=null)
return "." + rc;
} // end while
return null; // cannot serialize
} // end serializeProperty
public Object deserializeProperty(String value)
{
if (value==null)
return null;
try
{ // the first character is the flag...
switch (value.charAt(0))
{
case 'B':
return new Byte(value.substring(1));
case 'C':
return new Character(value.charAt(1));
case 'D':
return new Double(value.substring(1));
case 'F':
return new Float(value.substring(1));
case 'I':
return new Integer(value.substring(1));
case 'J':
return new Long(value.substring(1));
case 'S':
return new Short(value.substring(1));
case 'T':
return s_iso8601.parse(value.substring(1));
case 'Y':
return Boolean.TRUE;
case 'Z':
return Boolean.FALSE;
case '!':
return value.substring(1);
case '_':
return extendedDecode(value);
case '.':
{ // run through the external decoders
String s = value.substring(1);
Iterator it = m_extern_calls.iterator();
while (it.hasNext())
{ // try the external serializers
PropertySerializer psz = (PropertySerializer)(it.next());
Object rc = psz.deserializeProperty(s);
if (rc!=null)
return rc;
} // end while
} // end case
break;
default:
break;
} // end switch
} // end try
catch (ParseException e)
{ // if we threw this, we're h0s3d anyway
return null;
} // end catch
return null;
} // end deserializeProperty
/*--------------------------------------------------------------------------------
* Implementations from interface PropertySerializerRegistration
*--------------------------------------------------------------------------------
*/
public ComponentShutdown registerPropertySerializer(PropertySerializer psz)
{
m_extern_calls.add(psz);
return new ShutdownVectorRemove(m_extern_calls,psz);
} // end registerPropertySerializer
/*--------------------------------------------------------------------------------
* Static initializer
*--------------------------------------------------------------------------------
*/
static
{
HashMap tmp = new HashMap();
tmp.put(Byte.class,"B");
tmp.put(Byte.TYPE,"B");
tmp.put(Character.class,"C");
tmp.put(Character.TYPE,"C");
tmp.put(Double.class,"D");
tmp.put(Double.TYPE,"D");
tmp.put(Float.class,"F");
tmp.put(Float.TYPE,"F");
tmp.put(Integer.class,"I");
tmp.put(Integer.TYPE,"I");
tmp.put(Long.class,"J");
tmp.put(Long.TYPE,"J");
tmp.put(Short.class,"S");
tmp.put(Short.TYPE,"S");
tmp.put(String.class,"!");
tmp.put(StringBuffer.class,"!");
tmp.put(Locale.class,"_LOC:");
SIMPLE_TYPE_SERIALIZE = Collections.unmodifiableMap(tmp);
SimpleDateFormat iso = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
iso.setCalendar(new GregorianCalendar(new SimpleTimeZone(0,"UTC")));
s_iso8601 = iso;
} // end static initializer
} // end class PropertySerializationSupport

View File

@@ -0,0 +1,71 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
public class RewriteRule
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name;
private boolean m_encode;
private String m_template;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
RewriteRule(Element elt) throws XMLLoadException
{
XMLLoader loader = XMLLoader.get();
m_name = loader.getAttribute(elt,"type").trim().toUpperCase();
m_encode = loader.getAttributeBoolean(elt,"encode");
m_template = loader.getText(elt);
} // end constructor
/*--------------------------------------------------------------------------------
* Public getters
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
public boolean getEncode()
{
return m_encode;
} // end getEncode
public String getTemplate()
{
return m_template;
} // end getTemplate
} // end class RewriteRule

View File

@@ -0,0 +1,62 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
class ServiceKey
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Class m_class;
private String m_serviceid;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
ServiceKey(Class klass, String serviceid)
{
m_class = klass;
m_serviceid = serviceid;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class Object
*--------------------------------------------------------------------------------
*/
public boolean equals(Object obj)
{
if ((obj==null) || !(obj instanceof ServiceKey))
return false;
ServiceKey other = (ServiceKey)obj;
return (m_class==other.m_class) && m_serviceid.equals(other.m_serviceid);
} // end equals
public int hashCode()
{
return m_class.hashCode() ^ m_serviceid.hashCode();
} // end hashCode
} // end class ServiceKey

View File

@@ -0,0 +1,98 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.app;
import java.io.InputStream;
import java.io.IOException;
import com.silverwrist.dynamo.except.NoSuchResourceException;
import com.silverwrist.dynamo.iface.ResourceProvider;
class WrappedResourceProvider
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private ComponentResName m_mount_point;
private ResourceProvider m_provider;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
WrappedResourceProvider(ComponentResName mount_point, ResourceProvider provider)
{
m_mount_point = mount_point;
m_provider = provider;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class Object
*--------------------------------------------------------------------------------
*/
public boolean equals(Object obj)
{
if ((obj==null) || !(obj instanceof WrappedResourceProvider))
return false;
WrappedResourceProvider other = (WrappedResourceProvider)obj;
return m_mount_point.equals(other.m_mount_point);
} // end equals
public int hashCode()
{
return m_mount_point.hashCode();
} // end hashCode
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
int getMatchCount(ComponentResName crn)
{
int rc = m_mount_point.getMatchCount(crn);
if (rc!=m_mount_point.getComponentCount())
return -1;
return rc;
} // end getMatchCount
InputStream getResource(ComponentResName crn) throws IOException
{
if (m_mount_point.getMatchCount(crn)!=m_mount_point.getComponentCount())
throw new NoSuchResourceException(crn.getStringValue(0,true));
return m_provider.getResource(crn.getStringValue(m_mount_point.getComponentCount(),true));
} // end getResource
long getResourceModTime(ComponentResName crn)
{
if (m_mount_point.getMatchCount(crn)!=m_mount_point.getComponentCount())
return 0;
return m_provider.getResourceModTime(crn.getStringValue(m_mount_point.getComponentCount(),true));
} // end getResourceModTime
} // end class WrappedResourceProvider

View File

@@ -0,0 +1,141 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.lang.reflect.*;
import java.sql.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.iface.DBUtilities;
abstract class DBUtilitiesImpl implements DBUtilities
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final Class[] ARGS_TYPE = new Class[0];
private static final Object[] ARGS = new Object[0];
private static final String SQL_WILDCARD_CHARS = "%_'";
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected DBUtilitiesImpl()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface DBUtilities
*--------------------------------------------------------------------------------
*/
public String encodeString(String data)
{
if (data==null)
return null; // safety feature
int ndx = data.indexOf('\'');
if (ndx<0)
return data;
StringBuffer buf = new StringBuffer();
while (ndx>=0)
{ // convert each single quote mark to a pair of them
if (ndx>0)
buf.append(data.substring(0,ndx));
buf.append("''");
data = data.substring(ndx+1);
ndx = data.indexOf('\'');
} // end while
buf.append(data);
return buf.toString();
} // end encodeString
public String encodeStringWildcards(String data)
{
if (data==null)
return null; // safety feature
AnyCharMatcher nhc = new AnyCharMatcher(SQL_WILDCARD_CHARS);
int ndx = nhc.get(data);
if (ndx<0)
return data; // trivial short-circuit case
StringBuffer buf = new StringBuffer();
while (ndx>=0)
{ // append the matched "head" and then the encoded character
if (ndx>0)
buf.append(data.substring(0,ndx));
switch (data.charAt(ndx++))
{
case '%':
buf.append("\\%");
break;
case '_':
buf.append("\\_");
break;
case '\'':
buf.append("\'\'");
break;
} // end switch
if (ndx==data.length())
return buf.toString(); // munched the entire string - all done!
data = data.substring(ndx);
ndx = nhc.get(data);
} // end while
buf.append(data); // append the unmatched tail
return buf.toString();
} // end encodeStringWildcards
/*--------------------------------------------------------------------------------
* Abstract declarations from interface DBUtilities
*--------------------------------------------------------------------------------
*/
public abstract java.util.Date getDateTime(ResultSet rs, String column) throws SQLException;
public abstract java.util.Date getDateTime(ResultSet rs, int column) throws SQLException;
public abstract void setDateTime(PreparedStatement stmt, int index, java.util.Date date) throws SQLException;
public abstract void testDatabase(Connection conn) throws SQLException;
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static DBUtilities get(String type) throws Exception
{
String impl_class_name = DBUtilitiesImpl.class.getName() + "_" + type.toLowerCase();
Method m = Class.forName(impl_class_name).getMethod("get",ARGS_TYPE);
return (DBUtilities)(m.invoke(null,ARGS));
} // end get
} // end class DBUtilitiesImpl

View File

@@ -0,0 +1,201 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.SQLUtils;
import com.silverwrist.dynamo.iface.DBUtilities;
public class DBUtilitiesImpl_mysql extends DBUtilitiesImpl
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static DBUtilitiesImpl_mysql _self = null;
// used to convert dates and times to UTC for sending to SQL
private static SimpleTimeZone utc = new SimpleTimeZone(0,"UTC");
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
private DBUtilitiesImpl_mysql()
{
super();
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
/**
* Converts a date-and-time string (an SQL DATETIME value) to a standard Java date.
*
* @param dstr The date-and-time string to convert, presumed to be in UTC.
* @return The converted date and time.
* @exception java.sql.SQLException The date and time string was in an invalid format.
*/
private static final java.util.Date convertDateTimeString(String dstr) throws SQLException
{
if (dstr==null)
return null; // null values are the same
try
{ // do almost the reverse process of formatting it into a string
GregorianCalendar cal = new GregorianCalendar(utc);
cal.set(Calendar.YEAR,Integer.parseInt(dstr.substring(0,4)));
cal.set(Calendar.MONTH,Integer.parseInt(dstr.substring(5,7)) - 1 + Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH,Integer.parseInt(dstr.substring(8,10)));
cal.set(Calendar.HOUR_OF_DAY,Integer.parseInt(dstr.substring(11,13)));
cal.set(Calendar.MINUTE,Integer.parseInt(dstr.substring(14,16)));
cal.set(Calendar.SECOND,Integer.parseInt(dstr.substring(17,19)));
return cal.getTime();
} // end try
catch (NumberFormatException e)
{ // the NumberFormatException becomes an SQLException
throw new SQLException("invalid DATETIME field format");
} // end catch
} // end convertDateString
/**
* Encodes a date as an SQL date/time string, expressed in UTC.
*
* @param d The date to be encoded.
* @return The string equivalent of that date.
*/
private static final String encodeDate(java.util.Date d)
{
// Break down the date as a UTC value.
GregorianCalendar cal = new GregorianCalendar(utc);
cal.setTime(d);
// Create the two string buffers converting the date.
StringBuffer rc = new StringBuffer();
StringBuffer conv = new StringBuffer();
String c;
// Encode the year first.
conv.append("0000").append(cal.get(Calendar.YEAR));
c = conv.toString();
rc.append(c.substring(c.length()-4)).append('-');
// Now the month...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.MONTH) - Calendar.JANUARY + 1);
c = conv.toString();
rc.append(c.substring(c.length()-2)).append('-');
// And the day...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.DAY_OF_MONTH));
c = conv.toString();
rc.append(c.substring(c.length()-2)).append(' ');
// And the hour...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.HOUR_OF_DAY));
c = conv.toString();
rc.append(c.substring(c.length()-2)).append(':');
// And the minute...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.MINUTE));
c = conv.toString();
rc.append(c.substring(c.length()-2)).append(':');
// And the second...
conv.setLength(0);
conv.append("00").append(cal.get(Calendar.SECOND));
c = conv.toString();
rc.append(c.substring(c.length()-2));
// This is the resulting date/time value.
return rc.toString();
} // end encodeDate
/*--------------------------------------------------------------------------------
* Abstract implementations from class DBUtilitiesImpl
*--------------------------------------------------------------------------------
*/
public java.util.Date getDateTime(ResultSet rs, String column) throws SQLException
{
return convertDateTimeString(rs.getString(column));
} // end getDateTime
public java.util.Date getDateTime(ResultSet rs, int column) throws SQLException
{
return convertDateTimeString(rs.getString(column));
} // end getDateTime
public void setDateTime(PreparedStatement stmt, int index, java.util.Date date) throws SQLException
{
stmt.setString(index,encodeDate(date));
} // end setDateTime
public void testDatabase(Connection conn) throws SQLException
{
Statement stmt = null;
ResultSet rs = null;
try
{ // execute a simple SQL statement
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT 1;");
if (!rs.next())
throw new SQLException("MySQL database test failed(1)");
if (rs.getInt(1)!=1)
throw new SQLException("MySQL database test failed(2)");
} // end try
finally
{ // close down statement and result set
SQLUtils.shutdown(rs);
SQLUtils.shutdown(conn);
} // end finally
} // end testDatabase
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static DBUtilities get()
{
if (_self==null)
_self = new DBUtilitiesImpl_mysql();
return _self;
} // end get
} // end class DBUtilitiesImpl_mysql

View File

@@ -0,0 +1,652 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import java.util.*;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.Namespaces;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
/**
* A simple pooling system for JDBC connections, which allows connections to be kept in a pool until
* they're needed, avoiding the overhead of opening and closing connections for each transaction, or
* keeping one database connection open for each user.<P>
* Based on some code from Marty Hall's <EM>Core Servlets and Java Server Pages</EM> (Prentice Hall/
* Sun Microsystems, 2000).
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class DatabaseConnectionPool implements DBConnectionPool, ComponentInitialize, ComponentShutdown
{
/*--------------------------------------------------------------------------------
* Internal background thread object
*--------------------------------------------------------------------------------
*/
private class BackgroundThread extends Thread
{
/*====================================================================
* Constructor
*====================================================================
*/
BackgroundThread()
{
super("DatabaseConnectionPool_bkgd_" + (s_thread_counter++));
} // end constructor
/*====================================================================
* Overrides from class Thread
*====================================================================
*/
public void run()
{
try
{ // attempt to create another connection in the background
Connection c = makeNewConnection();
synchronized (DatabaseConnectionPool.this)
{ // we've got a new available connection - let everyone know
if (logger.isDebugEnabled())
logger.debug("created new connection in the background");
m_avail_connections.addElement(c);
m_pending = false;
DatabaseConnectionPool.this.notifyAll();
} // end synchronized block
} // end try
catch (Exception e)
{ // caught an SQLException or an OutOfMemory exception
logger.warn("background connection thread caught exception",e);
// ditch this new connection and wait until an existing one frees up
} // end catch
} // end run
} // end BackgroundThread
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Logger logger = Logger.getLogger(DatabaseConnectionPool.class);
private static final Map INFER_TYPE_MAP; // used to infer database type from JDBC driver classname
private static int s_thread_counter = 1; // counter for data pool threads
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name; // name of connection pool
private String m_dbtype; // database type
private String m_driver; // name of JDBC driver class
private String m_url; // URL for JDBC connection
private String m_username; // username for JDBC connection
private String m_password; // password for JDBC connection
private int m_max_conns; // maximum number of possible connections
private boolean m_wait_if_busy; // do we wait for a connection if none is available?
private boolean m_pending = false; // pending connection being created?
private Vector m_avail_connections = null; // connections which are available for use
private Vector m_busy_connections = null; // connections which are currently in use
private DBUtilities m_util_object; // utilities object
private PropertySerializer m_psz; // property serializer object
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Creates a new <CODE>DatabaseCOnnectionPool</CODE> object. Commonly called at initialization time,
* when the objects are created from the Dynamo XML configuration file.
*/
public DatabaseConnectionPool()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
/**
* Creates a standard database exception.
*
* @param message The message ID from the "DatabaseMessages" bundle to load.
* @return The new exception object.
*/
private static final DatabaseException newException(String message)
{
return new DatabaseException(DatabaseConnectionPool.class,"DatabaseMessages",message);
} // end newException
/**
* Creates a standard database exception.
*
* @param message The message ID from the "DatabaseMessages" bundle to load.
* @param inner The exception to wrap in the new
* {@link com.silverwrist.dynamo.except.DatabaseException DatabaseException} object.
* @return The new exception object.
*/
private static final DatabaseException newException(String message, Throwable inner)
{
return new DatabaseException(DatabaseConnectionPool.class,"DatabaseMessages",message,inner);
} // end newException
/**
* Closes all database connections in the specified vector.
*
* @param vconn Vector of connections to be closed.
*/
private static final void closeConnections(Vector vconn)
{
if (logger.isDebugEnabled())
logger.debug("closeConnections(" + vconn.size() + " to be closed)");
for (int i=0; i<vconn.size(); i++)
{ // loop over the entire vector
try
{ // take each connection and close it
Connection c = (Connection)(vconn.get(i));
if (!(c.isClosed()))
c.close();
} // end try
catch (SQLException e)
{ // what do we care, this connection is dying anyhow
logger.warn("got a SQLException in closeConnections (ignored): " + e.getMessage());
} // end catch
} // end for
} // end closeConnections
/**
* Creates and returns a new database connection.
*
* @return The new database connection object.
* @exception com.silverwrist.dynamo.except.DatabaseException An error prevented the creation
* of the connection.
*/
private final Connection makeNewConnection() throws DatabaseException
{
if (m_busy_connections==null)
throw newException("dbx.notInitialized");
try
{ // make the connection and return it
Class.forName(m_driver).newInstance(); // preload driver class
// the newInstance() call above is to work around some broken Java implementations
return DriverManager.getConnection(m_url,m_username,m_password);
} // end try
catch (ClassNotFoundException e)
{ // convert a ClassNotFoundException to a nicer DatabaseException
logger.error("JDBC driver class \"" + m_driver + "\" not found",e);
DatabaseException d = newException("dbx.classNotFound");
d.setParameter(0,m_driver);
throw d;
} // end catch
catch (IllegalAccessException e2)
{ // convert this to a nicer DatabaseException
logger.fatal("Can't access \"" + m_driver + "\" constructor",e2);
DatabaseException d = newException("dbx.illegalAccess");
d.setParameter(0,m_driver);
throw d;
} // end catch
catch (InstantiationException e3)
{ // convert this to a nicer DatabaseException
logger.fatal("Can't create instance of \"" + m_driver + "\"",e3);
DatabaseException d = newException("dbx.instantiation");
d.setParameter(0,m_driver);
throw d;
} // end catch
catch (SQLException e4)
{ // convert this to a DatabaseException, too
logger.fatal("Can't create database connection",e4);
throw newException("dbx.sqlMakeNewConn",e4);
} // end catch
} // end makeNewConnection
/**
* Spins off a background thread to create a new database connection.
*/
private final void makeBackgroundConnection()
{
m_pending = true;
try
{ // spin off the connection attempt to the background
BackgroundThread thrd = new BackgroundThread();
thrd.start();
} // end try
catch (OutOfMemoryError e)
{ // give up on new connection
logger.warn("memory failure spinning off background-connect thread");
m_pending = false;
} // end catch
} // end makeBackgroundConnection
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
/**
* Returns the name of this object.
*
* @return The name of this object.
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ServiceProvider
*--------------------------------------------------------------------------------
*/
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass)
{
if (klass==DBUtilities.class)
return m_util_object;
if (klass==PropertySerializer.class)
return m_psz;
if (klass==DBConnectionPool.class)
return (DBConnectionPool)this;
throw new NoSuchServiceException("DatabaseConnectionPool",klass);
} // end queryService
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @param serviceid ID for the service to be requested, to further discriminate between requests.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass, String serviceid)
{
return this.queryService(klass);
} // end queryService
/*--------------------------------------------------------------------------------
* Implementations from interface DBConnectionPool
*--------------------------------------------------------------------------------
*/
/**
* Returns a simple string identifying the database type. This is commonly used in database operations
* classes to create classnames that are dynamically loaded.
*
* @return The database identifier.
*/
public String getDatabaseType()
{
return m_dbtype;
} // end getDatabaseType
/**
* Returns the number of connections currently being managed by this connection pool.
*
* @return The number of connections currently being managed by this connection pool.
*/
public int numConnections()
{
if (m_busy_connections==null)
return 0;
int rc = m_avail_connections.size() + m_busy_connections.size();
if (logger.isDebugEnabled())
logger.debug("numConnections() => " + rc);
return rc;
} // end numConnections
/**
* Obtains a database connection object from the connection pool.
*
* @return The <CODE>Connection</CODE> object.
* @exception com.silverwrist.dynamo.except.DatabaseException If a connection could not be obtained.
*/
public synchronized Connection getConnection() throws DatabaseException
{
if (m_busy_connections==null)
throw newException("dbx.notInitialized");
for (;;)
{ // loop until we get a connection or throw an exception
if (m_avail_connections.isEmpty())
{ // no connections available - we may need to make a new one
if (logger.isDebugEnabled())
logger.debug("no connections available - looking to get one");
if ((numConnections() < m_max_conns) && !m_pending)
makeBackgroundConnection(); // try to create a new connection
else if (!m_wait_if_busy)
{ // don't want to wait? tough, we're h0sed!
logger.error("exhausted maximum connection limit (" + m_max_conns + ")");
throw newException("dbx.connectionLimit");
} // end else if
// Wait for the background connect attempt to finish, or for
// someone to return a connection.
try
{ // park the thread here until we know what's up
wait();
} // end try
catch (InterruptedException e)
{ // do nothing
} // end catch
// now fall through the loop and try again
} // end if
else
{ // pull the last connection off the available list...
int ndx = m_avail_connections.size() - 1;
Connection rc = (Connection)(m_avail_connections.elementAt(ndx));
m_avail_connections.removeElementAt(ndx);
try
{ // see if this is a good connection or not...
if (rc.isClosed())
{ // this connection is closed - discard it, and notify any waiters that a slot
// has opened up
if (logger.isDebugEnabled())
logger.debug("discarding closed connection");
notifyAll();
rc = null;
// fall out to the end of the loop and try again
} // end if
else
{ // this connection is OK - return it
m_busy_connections.addElement(rc);
return rc;
} // end else
} // end try
catch (SQLException e)
{ // if isClosed() throws a SQLException, the connection is somehow broken
logger.warn("connection is borked, discarding",e);
notifyAll();
rc = null;
// fall out to the end of the loop and try again
} // end catch
} // end else (at least one connection available)
} // end for (ever)
} // end getConnection
/**
* Returns a database connection object to the connection pool.
*
* @param conn The <CODE>Connection</CODE> object to be released.
* @exception com.silverwrist.dynamo.except.DatabaseException If there was an error returning the connection.
*/
public synchronized void releaseConnection(Connection conn) throws DatabaseException
{
if (m_busy_connections==null)
throw newException("dbx.notInitialized");
if (conn!=null)
{ // move from one vector to another
m_busy_connections.removeElement(conn);
m_avail_connections.addElement(conn);
notifyAll(); // wake up! Got a new connection for you!
} // end if
} // end releaseConnection
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentInitialize
*--------------------------------------------------------------------------------
*/
/**
* Initialize the database connection.
*
* @param config_root Pointer to the &lt;dbconnection/&gt; section of the Dynamo XML configuration file that
* configures this database connection. This is to be considered "read-only" by the component.
* @param services An implementation of {@link com.silverwrist.dynamo.iface.ServiceProvider ServiceProvider}
* which provides initialization services to the component. This will include an implementation
* of {@link com.silverwrist.dynamo.iface.ObjectProvider ObjectProvider} which may be used to
* get information about other objects previously initialized by the application.
* @exception com.silverwrist.dynamo.except.ConfigException If an error is encountered in the component
* configuration.
*/
public void initialize(Element config_root, ServiceProvider services) throws ConfigException
{
XMLLoader loader = XMLLoader.get();
try
{ // verify the right node name
loader.verifyNodeName(config_root,"dbconnection");
// get the object's name
m_name = loader.getAttribute(config_root,"name");
// get the various settings
DOMElementHelper h = new DOMElementHelper(config_root);
m_dbtype = h.getSubElementText("dbtype");
if (logger.isDebugEnabled() && (m_dbtype!=null))
logger.debug("DatabaseConnectionPool specified database type: " + m_dbtype);
m_driver = loader.getSubElementText(h,"driver");
if (logger.isDebugEnabled())
logger.debug("DatabaseConnectionPool driver: " + m_driver);
// If the database type is not known, try to infer it from the driver name.
if (m_dbtype==null)
m_dbtype = (String)(INFER_TYPE_MAP.get(m_driver));
if (m_dbtype==null)
{ // wasn't specified, can't infer it - we are HOSED!
ConfigException ce = new ConfigException(DatabaseConnectionPool.class,"DatabaseMessages",
"config.inferType");
ce.setParameter(0,m_driver);
throw ce;
} // end if
else if (logger.isDebugEnabled())
logger.debug("DatabaseConnectionPool inferred database type: " + m_dbtype);
m_url = loader.getSubElementText(h,"uri");
if (logger.isDebugEnabled())
logger.debug("DatabaseConnectionPool URI: " + m_url);
m_username = loader.getSubElementText(h,"username");
if (logger.isDebugEnabled())
logger.debug("DatabaseConnectionPool user name: " + m_username);
m_password = loader.getSubElementText(h,"password");
Element elt = loader.getSubElement(h,"connections");
int initial_conn = loader.getAttributeInt(elt,"initial",0);
if (initial_conn<0)
throw new ConfigException(DatabaseConnectionPool.class,"DatabaseMessages","config.initialConn");
if (logger.isDebugEnabled())
logger.debug("DatabaseConnectionPool initial connections: " + initial_conn);
m_max_conns = loader.getAttributeInt(elt,"max");
if (m_max_conns<0)
throw new ConfigException(DatabaseConnectionPool.class,"DatabaseMessages","config.maxConn");
if (logger.isDebugEnabled())
logger.debug("DatabaseConnectionPool maximum connections: " + m_max_conns);
m_wait_if_busy = loader.getAttributeBoolean(elt,"busywait",true);
if (logger.isDebugEnabled())
logger.debug("DatabaseConnectionPool wait if busy: " + m_wait_if_busy);
if (initial_conn>m_max_conns)
{ // fix initial value if above maximum
if (logger.isDebugEnabled())
logger.debug("N.B.: reducing configured initial connections");
initial_conn = m_max_conns;
} // end if
try
{ // get the appropriate utilities object
m_util_object = DBUtilitiesImpl.get(m_dbtype);
} // end if
catch (Exception e)
{ // the utilities are not implemented
ConfigException ce = new ConfigException(DatabaseConnectionPool.class,"DatabaseMessages",
"utils.impl",e);
ce.setParameter(0,m_dbtype);
throw ce;
} // end catch
// Get the master property serializer so we can offer it as a service.
m_psz = (PropertySerializer)(services.queryService(PropertySerializer.class));
// Create the vectors that hold connections.
m_avail_connections = new Vector(initial_conn);
m_busy_connections = new Vector();
// Populate the "available connection" vector.
for (int i=0; i<initial_conn; i++)
m_avail_connections.addElement(makeNewConnection());
// See if we need to test the database.
boolean do_test = false;
elt = h.getSubElement("initialize");
if (elt!=null)
do_test = loader.getAttributeBoolean(elt,"test",false);
if (do_test)
{ // database must be tested
Connection conn = null;
try
{ // get connection and test it
conn = this.getConnection();
m_util_object.testDatabase(conn);
} // end try
catch (SQLException e)
{ // translate SQL exception into ConfigException
ConfigException ce = new ConfigException(DatabaseConnectionPool.class,"DatabaseMessages","dbx.testfail",e);
ce.setParameter(0,m_name);
ce.setParameter(1,m_url);
ce.setParameter(2,e.getMessage());
throw ce;
} // end catch
finally
{ // release the connection we got
this.releaseConnection(conn);
} // end finally
} // end if (testing database)
logger.info("DatabaseConnectionPool initialized");
} // end try
catch (XMLLoadException e)
{ // error loading XML config data
throw new ConfigException(e);
} // end catch
catch (DatabaseException e)
{ // error creating initial connections
throw new ConfigException(DatabaseConnectionPool.class,"DatabaseMessages","config.create",e);
} // end catch
} // end initialize
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
/**
* Shuts down the database connection, closing all cached <CODE>Connection</CODE> objects.
*/
public void shutdown()
{
closeConnections(m_avail_connections);
m_avail_connections = null;
closeConnections(m_busy_connections);
m_busy_connections = null;
} // end shutdown
/*--------------------------------------------------------------------------------
* Static initializer
*--------------------------------------------------------------------------------
*/
static
{ // Create the database type inference map.
HashMap map = new HashMap();
map.put("com.mysql.jdbc.Driver","mysql");
map.put("org.gjt.mm.mysql.Driver","mysql");
INFER_TYPE_MAP = Collections.unmodifiableMap(map);
} // end static initializer
} // end class DatabaseConnectionPool

View File

@@ -0,0 +1,58 @@
# 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# ---------------------------------------------------------------------------------
# This file has been localized for the en_US locale
dbx.notInitialized=The connection pool object has not been initialized
dbx.classNotFound=Can't find JDBC driver class: {0}
dbx.illegalAccess=Can't access JDBC driver class: {0}
dbx.instantiation=Can't create JDBC driver class: {0}
dbx.sqlMakeNewConn=Can't create new database connection
dbx.connectionLimit=Connection limit reached
dbx.testfail=Test failed on database {0} (url {1}): {2}
config.inferType=Database type was not specified, and unable to infer it from JDBC driver name "{0}".
config.initialConn=Invalid initial connections parameter
config.maxConn=Invalid maximum connections parameter
config.create=Unable to create initial database connections
utils.impl=Database utilities are not implemented for database type "{0}".
load.opsClass=Unable to load {2} class for database "{1}": {0}
general=Database access failure: {0}
nsCache.notFound=Unknown namespace ID seen; possible internal error.
property.serialize=The value of property "{0}" could not be serialized.
property.deserialize=The value of property "{0}" could not be deserialized.
ose.setProperty=Unable to set the value of property "{1}" in namespace "{0}".
ose.removeProperty=Unable to remove the value of property "{1}" in namespace "{0}".
ose.getNamespaces=Unable to enumerate the namespaces in this ObjectStore.
ose.getNames=Unable to enumerate the object names in namespace "{0}".
auth.register=Authenticator already registered for namespace "{0}", name "{1}".
auth.notFound=No authenticator registered for namespace "{0}", name "{1}".
auth.noUserData=User cannot authenticate with authenticator namespace "{0}", name "{1}".
ose.setBlock=Unable to set the value of block "{1}" in namespace "{0}".
ose.removeBlock=Unable to remove the value of block "{1}" in namespace "{0}".
sec.changeUser=You are not permitted to change the attributes of user "{0}".
sec.needSec=You cannot perform this operation on a group without specifying a user making the change.
sec.setGroupProperty=You are not permitted to set property values for group "{0}".
sec.removeGroupProperty=You are not permitted to remove property values from group "{0}".
sec.addGroupMember=You are not permitted to add members to group "{0}".
sec.removeGroupMember=You are not permitted to remove members from group "{0}".
sec.setGroupAcl=You are not permitted to change the access control list of group "{0}".
sec.setGlobalProperty=You are not permitted to set the global property.
sec.removeGlobalProperty=You are not permitted to remove the global property.
sec.setGlobalBlock=You are not permitted to set the global block.
sec.removeGlobalBlock=You are not permitted to remove the global block.
img.loadFail=Failed to load image {0} due to I/O error.
img.badOwner=Invalid owner for new image.
img.notOwner=You are not the owner of image {0}.
img.normalize=Image normalization of {0} failed: {1}.

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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.security.MessageDigest;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
class DefaultHashAuthenticator implements Authenticator
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
DefaultHashAuthenticator()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* IMplementations from interface Authenticator
*--------------------------------------------------------------------------------
*/
public boolean authenticate(String stored_data, String input_data) throws AuthenticationException
{
return stored_data.equals(hashPassword(input_data));
} // end authenticate
public String processInputData(String input_data) throws AuthenticationException
{
return hashPassword(input_data);
} // end processInputData
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
public static final String hashPassword(String password)
{
if ((password!=null) && (password.length()>0))
{ // hash the password and save the hash value
MessageDigest hasher;
try
{ // get a hasher implementing the Secure Hashing Algorithm
hasher = MessageDigest.getInstance("SHA");
} // end try
catch (java.security.NoSuchAlgorithmException e)
{ // SHA should be a standard algorithm...if it isn't, we're h0sed
throw new RuntimeException("HOSED JRE - SHA should be a standard algorithm");
} // end catch
try
{ // update the hasher with the UTF-8 bytes of the password
hasher.update(password.getBytes("UTF8"));
} // end try
catch (java.io.UnsupportedEncodingException e)
{ // WTF? How can the JRE NOT know about UTF-8? HOW?!?
throw new RuntimeException("HOSED JRE - UTF-8 encoding should be supported");
} // end catch
// Retrieve the raw hash value (should be 160 bits, or 20 bytes)
byte[] raw_hash = hasher.digest();
// Convert the hash value to a hexadecimal string (40 chars in length)
StringBuffer hash_buf = new StringBuffer(raw_hash.length * 2);
StringBuffer tmp_buf = new StringBuffer();
String tmp;
for (int i=0; i<raw_hash.length; i++)
{ // N.B.: Integer.toHexString does not zero-pad on the left, so that's why this is
// a little complex
tmp_buf.setLength(0);
tmp_buf.append("00").append(Integer.toHexString(raw_hash[i]).trim());
tmp = tmp_buf.toString();
hash_buf.append(tmp.substring(tmp.length()-2));
} // end for
// finally, save off the password hash value
return hash_buf.toString().toUpperCase();
} // end if
else // no password
return "";
} // end hashPassword
} // end class DefaultHashAuthenticator

View File

@@ -0,0 +1,185 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.event.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;
class GlobalBlocksObject implements SecureObjectStore
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private GlobalBlocksOps m_ops; // operations object
private NamespaceCache m_ns_cache; // namespace cache
private SecurityReferenceMonitor m_srm; // security reference monitor
private PostDynamicUpdate m_post; // where we post dynamic events
private HardSoftCache m_cache; // our cache
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
GlobalBlocksObject(DBConnectionPool pool, NamespaceCache ns_cache, SecurityReferenceMonitor srm,
PostDynamicUpdate post, int hard_limit, int soft_limit) throws ConfigException
{
m_ops = GlobalBlocksOps.get(pool);
m_ns_cache = ns_cache;
m_srm = srm;
m_post = post;
m_cache = new HardSoftCache(hard_limit,soft_limit);
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private final void testPermission(DynamoUser caller, String perm_namespace, String perm_name,
String fail_message) throws DatabaseException, DynamoSecurityException
{
if (caller.equals(m_srm.getAdminUser()))
return; // Administrator can do anything
if (m_srm.getGlobalAcl().testPermission(caller,perm_namespace,perm_name))
return; // we have the right permission in the ACL
throw new DynamoSecurityException(GroupObject.class,"DatabaseMessages",fail_message);
} // end testPermission
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectProvider
*--------------------------------------------------------------------------------
*/
/**
* Retrieves an object from this <CODE>ObjectProvider</CODE>.
*
* @param namespace The namespace to interpret the name relative to.
* @param name The name of the object to be retrieved.
* @return The object reference specified.
*/
public Object getObject(String namespace, String name)
{
try
{ // convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
Object rc = null;
synchronized (this)
{ // start by looking in the block cache
rc = m_cache.get(key);
if (rc==null)
{ // no use - need to try the database
rc = m_ops.getBlock(key);
if (rc!=null)
m_cache.put(key,rc);
} // end if
} // end synchronized block
if (rc==null)
throw new NoSuchObjectException(this.toString(),namespace,name);
return rc;
} // end try
catch (DatabaseException e)
{ // translate into our NoSuchObjectException but retain the DatabaseException
throw new NoSuchObjectException(this.toString(),namespace,name,e);
} // end catch
} // end getObject
/*--------------------------------------------------------------------------------
* Implementations from interface SecureObjectStore
*--------------------------------------------------------------------------------
*/
public Object setObject(DynamoUser caller, String namespace, String name, Object value)
throws DatabaseException, DynamoSecurityException
{
testPermission(caller,namespace,"set.block","sec.setGlobalBlock");
Object rc = null;
// convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
synchronized (this)
{ // start by setting the database value
rc = m_ops.putBlock(key,value.toString());
// and cache it, too
m_cache.put(key,value.toString());
} // end synchronized block
m_post.postUpdate(new GlobalBlockUpdateEvent(this,namespace,name));
return rc;
} // end setObject
public Object removeObject(DynamoUser caller, String namespace, String name)
throws DatabaseException, DynamoSecurityException
{
testPermission(caller,namespace,"remove.block","sec.removeGlobalBlock");
Object rc = null;
// convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
synchronized (this)
{ // start by killing the database value
rc = m_ops.removeBlock(key);
// and remove the cached value, too
m_cache.remove(key);
} // end synchronized block
m_post.postUpdate(new GlobalBlockUpdateEvent(this,namespace,name));
return rc;
} // end removeObject
public Collection getNamespaces() throws DatabaseException
{
// call through to the database to get the list of namespace IDs
int[] ids = m_ops.getBlockNamespaceIDs();
ArrayList rc = new ArrayList(ids.length);
for (int i=0; i<ids.length; i++)
rc.add(m_ns_cache.namespaceIdToName(ids[i]));
return Collections.unmodifiableList(rc);
} // end getNamespaces
public Collection getNamesForNamespace(String namespace) throws DatabaseException
{
// call through to the database to get the data for this namespace, then get names
return m_ops.getAllBlockNames(m_ns_cache.namespaceNameToId(namespace));
// N.B.: we do not retrieve all blocks and cache them the way we do with properties because
// blocks can potentially be HUGE, and our cache size is limited at best
} // end getNamesForNamespace
} // end class GlobalBlocksObject

View File

@@ -0,0 +1,76 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.util.*;
abstract class GlobalBlocksOps extends OpsBase
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected GlobalBlocksOps(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class OpsBase
*--------------------------------------------------------------------------------
*/
public void dispose()
{
super.dispose();
} // end dispose
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
abstract String getBlock(PropertyKey key) throws DatabaseException;
abstract String putBlock(PropertyKey key, String data) throws DatabaseException;
abstract String removeBlock(PropertyKey key) throws DatabaseException;
abstract int[] getBlockNamespaceIDs() throws DatabaseException;
abstract Collection getAllBlockNames(int nsid) throws DatabaseException;
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
static GlobalBlocksOps get(DBConnectionPool pool) throws ConfigException
{
return (GlobalBlocksOps)get(pool,GlobalBlocksOps.class.getClassLoader(),
GlobalBlocksOps.class.getName() + "_","GlobalBlocksOps");
} // end get
} // end class GlobalBlocksOps

View File

@@ -0,0 +1,284 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class GlobalBlocksOps_mysql extends GlobalBlocksOps
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DBUtilities m_utils; // reference to utilities object
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public GlobalBlocksOps_mysql(DBConnectionPool pool)
{
super(pool);
m_utils = (DBUtilities)(pool.queryService(DBUtilities.class));
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class GlobalBlocksOps
*--------------------------------------------------------------------------------
*/
String getBlock(PropertyKey key) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// look up the block
stmt = conn.prepareStatement("SELECT block FROM globalblock WHERE nsid = ? AND block_name = ?;");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
rs = stmt.executeQuery();
if (!(rs.next()))
return null; // block not found
return rs.getString(1);
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getBlock
String putBlock(PropertyKey key, String data) throws DatabaseException
{
String old_value = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES globalblock WRITE;");
// look to see if the block value is already there
stmt = conn.prepareStatement("SELECT block FROM globalblock WHERE nsid = ? AND block_name = ?;");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
rs = stmt.executeQuery();
if (rs.next())
old_value = rs.getString(1);
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
if (old_value!=null)
{ // prepare the statement to update the existing record
stmt = conn.prepareStatement("UPDATE globalblock SET block = ? WHERE nsid = ? AND block_name = ?;");
stmt.setString(1,data);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
} // end if
else
{ // prepare the statement to insert a new record
stmt = conn.prepareStatement("INSERT INTO globalblock (nsid, block_name, block) VALUES (?, ?, ?);");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
stmt.setString(3,data);
} // end else
stmt.executeUpdate(); // execute it!
return old_value; // return previous value
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end putBlock
String removeBlock(PropertyKey key) throws DatabaseException
{
String old_value = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES globalblock WRITE;");
// look to see if the property value is already there
stmt = conn.prepareStatement("SELECT block FROM globalblock WHERE nsid = ? AND block_name = ?;");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
rs = stmt.executeQuery();
if (rs.next())
old_value = rs.getString(1);
else
return null; // no need to remove anything
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
// delete the database row
stmt = conn.prepareStatement("DELETE FROM globalblock WHERE nsid = ? AND block_name = ?;");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
stmt.executeUpdate();
return old_value;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end removeBlock
int[] getBlockNamespaceIDs() throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the query!
stmt = conn.prepareStatement("SELECT DISTINCT nsid FROM globalblock;");
rs = stmt.executeQuery();
// read out a list of the namespace IDs
ArrayList tmp = new ArrayList();
while (rs.next())
tmp.add(new Integer(rs.getInt(1)));
// create and return the array
int[] rc = new int[tmp.size()];
for (int i=0; i<tmp.size(); i++)
rc[i] = ((Integer)(tmp.get(i))).intValue();
tmp.clear();
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getBlockNamespaceIDs
Collection getAllBlockNames(int nsid) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the query!
stmt = conn.prepareStatement("SELECT block_name FROM globalblock WHERE nsid = ?;");
stmt.setInt(1,nsid);
rs = stmt.executeQuery();
// prepare the return value
ArrayList rc = new ArrayList();
while (rs.next())
rc.add(rs.getString(1));
rc.trimToSize();
return Collections.unmodifiableList(rc);
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getAllBlockNames
} // end class GlobalBlocksOps_mysql

View File

@@ -0,0 +1,207 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;
public class GlobalDataManagerObject
implements NamedObject, ComponentInitialize, ComponentShutdown, ServiceProvider
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final int DEFAULT_HARD_LIMIT = 5;
private static final int DEFAULT_SOFT_LIMIT = 20;
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name; // object name
private DBConnectionPool m_pool; // database connection pool
private NamespaceCache m_ns_cache; // namespace cache object
private SecurityReferenceMonitor m_srm; // security reference monitor
private PostDynamicUpdate m_post; // dynamic update poster
private GlobalPropertiesObject m_properties; // global properties object
private GlobalBlocksObject m_blocks; // global blocks object
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public GlobalDataManagerObject()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentInitialize
*--------------------------------------------------------------------------------
*/
public void initialize(Element config_root, ServiceProvider services) throws ConfigException
{
String conn_name = null;
String nscache_name = null;
String srm_name = null;
int hard_limit = DEFAULT_HARD_LIMIT;
int soft_limit = DEFAULT_SOFT_LIMIT;
XMLLoader loader = XMLLoader.get();
try
{ // verify the right node name
loader.verifyNodeName(config_root,"object");
// get the object's name
m_name = loader.getAttribute(config_root,"name");
// get the database configuration connection
DOMElementHelper config_root_h = new DOMElementHelper(config_root);
Element elt = loader.getSubElement(config_root_h,"database");
conn_name = loader.getAttribute(elt,"connection");
nscache_name = loader.getAttribute(elt,"namespaces");
// get the security reference monitor reference
elt = loader.getSubElement(config_root_h,"security");
srm_name = loader.getAttribute(elt,"object");
// get the block cache information
elt = config_root_h.getSubElement("block-cache");
if (elt!=null)
{ // get the cache limits
hard_limit = loader.getAttributeInt(elt,"hardlimit",DEFAULT_HARD_LIMIT);
soft_limit = loader.getAttributeInt(elt,"softlimit",DEFAULT_SOFT_LIMIT);
} // end if
} // end try
catch (XMLLoadException e)
{ // error loading XML config data
throw new ConfigException(e);
} // end catch
// Get the database connection pool and the namespace cache.
m_pool = GetObjectUtils.getDatabaseConnection(services,conn_name);
m_ns_cache =
(NamespaceCache)(GetObjectUtils.getDynamoComponent(services,NamespaceCache.class,nscache_name));
m_srm =
(SecurityReferenceMonitor)(GetObjectUtils.getDynamoComponent(services,SecurityReferenceMonitor.class,
srm_name));
m_post = (PostDynamicUpdate)(services.queryService(PostDynamicUpdate.class));
// Create the subobjects.
m_properties = new GlobalPropertiesObject(m_pool,m_ns_cache,m_srm,m_post);
m_blocks = new GlobalBlocksObject(m_pool,m_ns_cache,m_srm,m_post,hard_limit,soft_limit);
} // end initialize
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
public void shutdown()
{
m_pool = null;
m_ns_cache = null;
m_srm = null;
m_post = null;
} // end shutdown
/*--------------------------------------------------------------------------------
* Implementations from interface ServiceProvider
*--------------------------------------------------------------------------------
*/
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass)
{
if ((klass==SecureObjectStore.class) || (klass==ObjectProvider.class))
return (SecureObjectStore)m_properties;
throw new NoSuchServiceException("GlobalDataManagerObject",klass);
} // end queryService
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @param serviceid ID for the service to be requested, to further discriminate between requests.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass, String serviceid)
{
if ((klass==SecureObjectStore.class) || (klass==ObjectProvider.class))
{ // return service
if ((serviceid==null) || serviceid.equals("properties"))
return (SecureObjectStore)m_properties;
if (serviceid.equals("blocks"))
return (SecureObjectStore)m_blocks;
throw new NoSuchServiceException("GlobalDataManagerObject",klass,serviceid);
} // end if
try
{ // look for the class without a service ID
return this.queryService(klass);
} // end try
catch (NoSuchServiceException e)
{ // transform exception for return
throw new NoSuchServiceException(e.getContext(),klass,serviceid,e);
} // end catch
} // end queryService
} // end class GlobalDataManagerObject

View File

@@ -0,0 +1,201 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import org.apache.commons.collections.*;
import com.silverwrist.dynamo.event.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;
class GlobalPropertiesObject implements SecureObjectStore
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private GlobalPropertiesOps m_ops; // operations object
private NamespaceCache m_ns_cache; // namespace cache
private SecurityReferenceMonitor m_srm; // security reference monitor
private PostDynamicUpdate m_post; // where we post dynamic events
private ReferenceMap m_properties; // cached property values
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
GlobalPropertiesObject(DBConnectionPool pool, NamespaceCache ns_cache, SecurityReferenceMonitor srm,
PostDynamicUpdate post) throws ConfigException
{
m_ops = GlobalPropertiesOps.get(pool);
m_ns_cache = ns_cache;
m_srm = srm;
m_post = post;
m_properties = new ReferenceMap(ReferenceMap.HARD,ReferenceMap.SOFT);
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private final void testPermission(DynamoUser caller, String perm_namespace, String perm_name,
String fail_message) throws DatabaseException, DynamoSecurityException
{
if (caller.equals(m_srm.getAdminUser()))
return; // Administrator can do anything
if (m_srm.getGlobalAcl().testPermission(caller,perm_namespace,perm_name))
return; // we have the right permission in the ACL
throw new DynamoSecurityException(GroupObject.class,"DatabaseMessages",fail_message);
} // end testPermission
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectProvider
*--------------------------------------------------------------------------------
*/
/**
* Retrieves an object from this <CODE>ObjectProvider</CODE>.
*
* @param namespace The namespace to interpret the name relative to.
* @param name The name of the object to be retrieved.
* @return The object reference specified.
*/
public Object getObject(String namespace, String name)
{
try
{ // convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
Object rc = null;
synchronized (this)
{ // start by looking in the properties map
rc = m_properties.get(key);
if (rc==null)
{ // no use - need to try the database
rc = m_ops.getProperty(key);
if (rc!=null)
m_properties.put(key,rc);
} // end if
} // end synchronized block
if (rc==null)
throw new NoSuchObjectException(this.toString(),namespace,name);
return rc;
} // end try
catch (DatabaseException e)
{ // translate into our NoSuchObjectException but retain the DatabaseException
throw new NoSuchObjectException(this.toString(),namespace,name,e);
} // end catch
} // end getObject
/*--------------------------------------------------------------------------------
* Implementations from interface SecureObjectStore
*--------------------------------------------------------------------------------
*/
public Object setObject(DynamoUser caller, String namespace, String name, Object value)
throws DatabaseException, DynamoSecurityException
{
testPermission(caller,namespace,"set.property","sec.setGlobalProperty");
Object rc = null;
// convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
synchronized (this)
{ // start by setting the database value
rc = m_ops.setProperty(key,value);
// and cache it, too
m_properties.put(key,value);
} // end synchronized block
m_post.postUpdate(new GlobalPropertyUpdateEvent(this,namespace,name));
return rc;
} // end setObject
public Object removeObject(DynamoUser caller, String namespace, String name)
throws DatabaseException, DynamoSecurityException
{
testPermission(caller,namespace,"remove.property","sec.removeGlobalProperty");
Object rc = null;
// convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
synchronized (this)
{ // start by killing the database value
rc = m_ops.removeProperty(key);
// and remove the cached value, too
m_properties.remove(key);
} // end synchronized block
m_post.postUpdate(new GlobalPropertyUpdateEvent(this,namespace,name));
return rc;
} // end removeObject
public Collection getNamespaces() throws DatabaseException
{
// call through to the database to get the list of namespace IDs
int[] ids = m_ops.getPropertyNamespaceIDs();
ArrayList rc = new ArrayList(ids.length);
for (int i=0; i<ids.length; i++)
rc.add(m_ns_cache.namespaceIdToName(ids[i]));
return Collections.unmodifiableList(rc);
} // end getNamespaces
public Collection getNamesForNamespace(String namespace) throws DatabaseException
{
// call through to the database to get the data for this namespace
int nsid = m_ns_cache.namespaceNameToId(namespace);
Map data = m_ops.getAllProperties(nsid);
// we both create the return value and cache the data values
ArrayList rc = new ArrayList(data.size());
synchronized (this)
{ // do the transfer...
Iterator it = data.entrySet().iterator();
while (it.hasNext())
{ // copy one entry at a time
Map.Entry ntry = (Map.Entry)(it.next());
rc.add(ntry.getKey().toString());
m_properties.put(new PropertyKey(nsid,ntry.getKey().toString()),ntry.getValue());
} // end while
} // end synchronized block
return Collections.unmodifiableList(rc);
} // end getNamesForNamespace
} // end class GlobalPropertiesObject

View File

@@ -0,0 +1,76 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.util.*;
abstract class GlobalPropertiesOps extends OpsBase
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected GlobalPropertiesOps(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class OpsBase
*--------------------------------------------------------------------------------
*/
public void dispose()
{
super.dispose();
} // end dispose
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
abstract Object getProperty(PropertyKey key) throws DatabaseException;
abstract Object setProperty(PropertyKey key, Object value) throws DatabaseException;
abstract Object removeProperty(PropertyKey key) throws DatabaseException;
abstract int[] getPropertyNamespaceIDs() throws DatabaseException;
abstract Map getAllProperties(int namespace) throws DatabaseException;
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
static GlobalPropertiesOps get(DBConnectionPool pool) throws ConfigException
{
return (GlobalPropertiesOps)get(pool,GlobalPropertiesOps.class.getClassLoader(),
GlobalPropertiesOps.class.getName() + "_","GlobalPropertiesOps");
} // end get
} // end class GlobalPropertiesOps

View File

@@ -0,0 +1,344 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class GlobalPropertiesOps_mysql extends GlobalPropertiesOps
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DBUtilities m_utils; // reference to utilities object
private PropertySerializer m_psz; // reference to property serializer
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public GlobalPropertiesOps_mysql(DBConnectionPool pool)
{
super(pool);
m_utils = (DBUtilities)(pool.queryService(DBUtilities.class));
m_psz = (PropertySerializer)(pool.queryService(PropertySerializer.class));
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class GlobalPropertiesOps
*--------------------------------------------------------------------------------
*/
Object getProperty(PropertyKey key) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String rc_str = null;
try
{ // get a connection
conn = getConnection();
// look up the property
stmt = conn.prepareStatement("SELECT prop_value FROM globalprop WHERE nsid = ? AND prop_name = ?;");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
rs = stmt.executeQuery();
if (!(rs.next()))
return null; // property not found
rc_str = rs.getString(1);
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(rc_str);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(GlobalPropertiesOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end getProperty
Object setProperty(PropertyKey key, Object value) throws DatabaseException
{
String serialized_value = m_psz.serializeProperty(value);
if (serialized_value==null)
{ // serialization exception - throw it
DatabaseException de = new DatabaseException(GlobalPropertiesOps_mysql.class,"DatabaseMessages",
"property.serialize");
de.setParameter(0,key.getName());
throw de;
} // end if
String old_value = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES globalprop WRITE;");
// look to see if the property value is already there
stmt = conn.prepareStatement("SELECT prop_value FROM globalprop WHERE nsid = ? AND prop_name = ?;");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
rs = stmt.executeQuery();
if (rs.next())
old_value = rs.getString(1);
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
if (old_value!=null)
{ // prepare the statement to update the existing record
stmt = conn.prepareStatement("UPDATE globalprop SET prop_value = ? WHERE nsid = ? AND prop_name = ?;");
stmt.setString(1,serialized_value);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
} // end if
else
{ // prepare the statement to insert a new record
stmt = conn.prepareStatement("INSERT INTO globalprop (nsid, prop_name, prop_value) VALUES (?, ?, ?);");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
stmt.setString(3,serialized_value);
} // end else
stmt.executeUpdate(); // execute it!
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
if (old_value==null)
return null; // no previous value
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(old_value);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(GlobalPropertiesOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end setProperty
Object removeProperty(PropertyKey key) throws DatabaseException
{
String old_value = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES globalprop WRITE;");
// look to see if the property value is already there
stmt = conn.prepareStatement("SELECT prop_value FROM globalprop WHERE nsid = ? AND prop_name = ?;");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
rs = stmt.executeQuery();
if (rs.next())
old_value = rs.getString(1);
else
return null; // no need to remove anything
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
// delete the database row
stmt = conn.prepareStatement("DELETE FROM globalprop WHERE nsid = ? AND prop_name = ?;");
stmt.setInt(1,key.getNamespaceID());
stmt.setString(2,key.getName());
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(old_value);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(GlobalPropertiesOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end removeProperty
int[] getPropertyNamespaceIDs() throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the query!
stmt = conn.prepareStatement("SELECT DISTINCT nsid FROM globalprop;");
rs = stmt.executeQuery();
// read out a list of the namespace IDs
ArrayList tmp = new ArrayList();
while (rs.next())
tmp.add(new Integer(rs.getInt(1)));
// create and return the array
int[] rc = new int[tmp.size()];
for (int i=0; i<tmp.size(); i++)
rc[i] = ((Integer)(tmp.get(i))).intValue();
tmp.clear();
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getPropertyNamespaceIDs
Map getAllProperties(int namespace) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the query!
stmt = conn.prepareStatement("SELECT prop_name, prop_value FROM globalprop WHERE nsid = ?;");
stmt.setInt(1,namespace);
rs = stmt.executeQuery();
// prepare the return value
HashMap rc = new HashMap();
while (rs.next())
{ // copy data out, deserializing properties as we go
String key = rs.getString(1);
Object value = m_psz.deserializeProperty(rs.getString(2));
if (value==null)
{ // deserialization exception - throw it
DatabaseException de = new DatabaseException(GlobalPropertiesOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key);
throw de;
} // end if
rc.put(key,value);
} // end while
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getAllProperties
} // end class GlobalPropertiesOps_mysql

View File

@@ -0,0 +1,611 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.security.Principal;
import java.security.acl.AclNotFoundException;
import java.util.*;
import org.apache.commons.collections.*;
import com.silverwrist.dynamo.Namespaces;
import com.silverwrist.dynamo.UserInfoNamespace;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;
class GroupObject implements DynamoGroup
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String PERM_NAMESPACE = Namespaces.GROUP_PERMISSIONS_NAMESPACE;
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private GroupObjectOps m_ops; // operations object
private NamespaceCache m_ns_cache; // namespace cache object
private SecurityReferenceMonitor m_srm; // security reference monitor
private UserProxyManagement m_upm; // user proxy manager
private int m_gid; // group ID
private String m_groupname; // group name
private int m_gaclid; // group ACL ID
private ReferenceMap m_properties; // cached property values
private Object m_properties_sync = new Object(); // synchronization for above
private HashSet m_known_members = new HashSet(); // known members
private HashSet m_known_nonmembers = new HashSet(); // known nonmembers
private Object m_members_sync = new Object(); // synchronization for above
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
GroupObject(Map data, GroupObjectOps ops, NamespaceCache ns_cache, SecurityReferenceMonitor srm,
UserProxyManagement upm)
{
m_ops = ops;
m_ns_cache = ns_cache;
m_srm = srm;
m_upm = upm;
m_gid = ((Integer)(data.get(UserManagerOps.HMKEY_GID))).intValue();
m_groupname = (String)(data.get(UserManagerOps.HMKEY_GROUPNAME));
m_gaclid = ((Integer)(data.get(UserManagerOps.HMKEY_GACLID))).intValue();
m_properties = new ReferenceMap(ReferenceMap.HARD,ReferenceMap.SOFT);
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private static final int getPrincipalUID(Principal p)
{
if (p instanceof DynamoUser)
return ((DynamoUser)p).getUID();
else
return -1;
} // end getPrincipalUID
private final void testOperationWithoutSecurity()
{
if (m_gaclid==-1)
return;
throw new GroupRuntimeException(new DynamoSecurityException(GroupObject.class,"DatabaseMessages",
"sec.needSec"));
} // end testOperationWithoutSecurity
private final void testPermission(DynamoUser caller, String perm_namespace, String perm_name,
String fail_message) throws DatabaseException, DynamoSecurityException
{
if (m_gaclid==-1)
return;
if (caller==null)
throw new DynamoSecurityException(GroupObject.class,"DatabaseMessages","sec.needSec");
if (caller.equals(m_srm.getAdminUser()))
return; // Administrator can do anything
if (m_srm.testPermission(m_gaclid,caller,perm_namespace,perm_name))
return; // we have the right permission in the ACL
DynamoSecurityException dse = new DynamoSecurityException(GroupObject.class,"DatabaseMessages",
fail_message);
dse.setParameter(0,m_groupname);
throw dse;
} // end testPermission
private final void testPermission(DynamoUser caller, int target_uid, String perm_namespace, String perm_name,
String perm2_name, String fail_message)
throws DatabaseException, DynamoSecurityException
{
if (m_gaclid==-1)
return;
if (caller==null)
throw new DynamoSecurityException(GroupObject.class,"DatabaseMessages","sec.needSec");
if (caller.equals(m_srm.getAdminUser()))
return; // Administrator can do anything
if ((caller.getUID()==target_uid) && m_srm.testPermission(m_gaclid,caller,perm_namespace,perm2_name))
return; // we can "join group" or "unjoin group" if we have the right permissions
if (m_srm.testPermission(m_gaclid,caller,perm_namespace,perm_name))
return; // we have the right permission in the ACL
DynamoSecurityException dse = new DynamoSecurityException(GroupObject.class,"DatabaseMessages",
fail_message);
dse.setParameter(0,m_groupname);
throw dse;
} // end testPermission
private final void testAclOwner(DynamoUser caller) throws DatabaseException, DynamoSecurityException
{
if (m_gaclid==-1)
return;
if (caller==null)
throw new DynamoSecurityException(GroupObject.class,"DatabaseMessages","sec.needSec");
if (caller.equals(m_srm.getAdminUser()))
return; // Administrator can do anything
if (m_srm.isOwnerOfAcl(m_gaclid,caller))
return; // we own this ACL
DynamoSecurityException dse = new DynamoSecurityException(GroupObject.class,"DatabaseMessages",
"sec.setGroupAcl");
dse.setParameter(0,m_groupname);
throw dse;
} // end testAclOwner
private final boolean addUIDInternal(int uid) throws DatabaseException
{
Integer key = new Integer(uid);
synchronized (m_members_sync)
{ // look in the cache first
if (m_known_members.contains(key))
return false; // we're already a known member
// fiddle the database
boolean rc = m_ops.addMember(m_gid,uid);
m_known_members.add(key); // update the cache to reflect reality
if (m_known_nonmembers!=null)
m_known_nonmembers.remove(key);
return rc;
} // end synchronized block
} // end addUIDInternal
private final boolean removeUIDInternal(int uid) throws DatabaseException
{
Integer key = new Integer(uid);
synchronized (m_members_sync)
{ // look in the cache first
if (m_known_nonmembers!=null)
{ // are we a known nonmember?
if (m_known_nonmembers.contains(key))
return false; // already a nonmember
} // end if
else
{ // in this circumstance, everyone not in the members set is a nonmember
if (!(m_known_members.contains(key)))
return false; // already a nonmember
} // end else
// fiddle the database
boolean rc = m_ops.removeMember(m_gid,uid);
m_known_members.remove(key); // update the cache to reflect reality
if (m_known_nonmembers!=null)
m_known_nonmembers.add(key);
return rc;
} // end synchronized block
} // end removeUIDInternal
/*--------------------------------------------------------------------------------
* Implementations from interface Principal
*--------------------------------------------------------------------------------
*/
public boolean equals(Object another)
{
if (another==null)
return false;
if (another instanceof DynamoGroup)
return (m_gid==((DynamoGroup)another).getGID());
return false;
} // end equals
public String toString()
{
return "group " + m_groupname;
} // end toString
public int hashCode()
{
return m_gid;
} // end hashCode
public String getName()
{
return m_groupname;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface Group
*--------------------------------------------------------------------------------
*/
public boolean addMember(Principal user)
{
testOperationWithoutSecurity();
try
{ // break down the operations...
if (user instanceof DynamoUser)
return this.addUIDInternal(((DynamoUser)user).getUID());
else if (user instanceof DynamoGroup)
{ // add all UIDs contained in this group
int[] uids = ((DynamoGroup)user).getUIDs();
boolean rc = false;
for (int i=0; i<uids.length; i++)
rc = this.addUIDInternal(uids[i]) || rc;
return rc;
} // end else if
else
throw new IllegalArgumentException("expected DynamoUser or DynamoGroup");
} // end try
catch (DatabaseException e)
{ // wrap this exception and return it
throw new GroupRuntimeException(e);
} // end catch
} // end addMember
public boolean removeMember(Principal user)
{
testOperationWithoutSecurity();
try
{ // break down the operations...
if (user instanceof DynamoUser)
return this.removeUIDInternal(((DynamoUser)user).getUID());
else if (user instanceof DynamoGroup)
{ // remove all UIDs contained in this group
int[] uids = ((DynamoGroup)user).getUIDs();
boolean rc = false;
for (int i=0; i<uids.length; i++)
rc = this.removeUIDInternal(uids[i]) || rc;
return rc;
} // end else if
else
throw new IllegalArgumentException("expected DynamoUser or DynamoGroup");
} // end try
catch (DatabaseException e)
{ // wrap this exception and return it
throw new GroupRuntimeException(e);
} // end catch
} // end removeMember
public boolean isMember(Principal member)
{
try
{ // break down the operations...
if (member instanceof DynamoUser)
return this.testUID(((DynamoUser)member).getUID());
else if (member instanceof DynamoGroup)
{ // test all UIDs contained within this group
int[] uids = ((DynamoGroup)member).getUIDs();
if (uids.length==0)
return false;
boolean rc = true;
for (int i=0; rc && (i<uids.length); i++)
rc = this.testUID(uids[i]);
return rc;
} // end else if
else
throw new IllegalArgumentException("expected DynamoUser or DynamoGroup");
} // end try
catch (DatabaseException e)
{ // wrap this exception and return it
throw new GroupRuntimeException(e);
} // end catch
} // end isMember
public Enumeration members()
{
try
{ // call down, get the UIDs, and use them to get proxies
int[] uids = this.getUIDs();
ArrayList tmp = new ArrayList(uids.length);
for (int i=0; i<uids.length; i++)
tmp.add(m_upm.getUserProxy(uids[i]));
return Collections.enumeration(tmp);
} // end try
catch (DatabaseException e)
{ // wrap this exception and return it
throw new GroupRuntimeException(e);
} // end catch
} // end members
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectProvider
*--------------------------------------------------------------------------------
*/
/**
* Retrieves an object from this <CODE>ObjectProvider</CODE>.
*
* @param namespace The namespace to interpret the name relative to.
* @param name The name of the object to be retrieved.
* @return The object reference specified.
*/
public Object getObject(String namespace, String name)
{
try
{ // convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
Object rc = null;
synchronized (m_properties_sync)
{ // start by looking in the properties map
rc = m_properties.get(key);
if (rc==null)
{ // no use - need to try the database
rc = m_ops.getProperty(m_gid,key);
if (rc!=null)
m_properties.put(key,rc);
} // end if
} // end synchronized block
if (rc==null)
throw new NoSuchObjectException(this.toString(),namespace,name);
return rc;
} // end try
catch (DatabaseException e)
{ // translate into our NoSuchObjectException but retain the DatabaseException
throw new NoSuchObjectException(this.toString(),namespace,name,e);
} // end catch
} // end getObject
/*--------------------------------------------------------------------------------
* Implementations from interface SecureObjectStore
*--------------------------------------------------------------------------------
*/
public Object setObject(DynamoUser caller, String namespace, String name, Object value)
throws DatabaseException, DynamoSecurityException
{
testPermission(caller,namespace,"set.property","sec.setGroupProperty");
Object rc = null;
// convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
synchronized (m_properties_sync)
{ // start by setting the database value
rc = m_ops.setProperty(m_gid,key,value);
// and cache it, too
m_properties.put(key,value);
} // end synchronized block
return rc;
} // end setObject
public Object removeObject(DynamoUser caller, String namespace, String name)
throws DatabaseException, DynamoSecurityException
{
testPermission(caller,namespace,"remove.property","sec.removeGroupProperty");
Object rc = null;
// convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
synchronized (m_properties_sync)
{ // start by killing the database value
rc = m_ops.removeProperty(m_gid,key);
// and remove the cached value, too
m_properties.remove(key);
} // end synchronized block
return rc;
} // end removeObject
public Collection getNamespaces() throws DatabaseException
{
// call through to the database to get the list of namespace IDs
int[] ids = m_ops.getPropertyNamespaceIDs(m_gid);
ArrayList rc = new ArrayList(ids.length);
for (int i=0; i<ids.length; i++)
rc.add(m_ns_cache.namespaceIdToName(ids[i]));
return Collections.unmodifiableList(rc);
} // end getNamespaces
public Collection getNamesForNamespace(String namespace) throws DatabaseException
{
// call through to the database to get the data for this namespace
int nsid = m_ns_cache.namespaceNameToId(namespace);
Map data = m_ops.getAllProperties(m_gid,nsid);
// we both create the return value and cache the data values
ArrayList rc = new ArrayList(data.size());
synchronized (m_properties_sync)
{ // do the transfer...
Iterator it = data.entrySet().iterator();
while (it.hasNext())
{ // copy one entry at a time
Map.Entry ntry = (Map.Entry)(it.next());
rc.add(ntry.getKey().toString());
m_properties.put(new PropertyKey(nsid,ntry.getKey().toString()),ntry.getValue());
} // end while
} // end synchronized block
return Collections.unmodifiableList(rc);
} // end getNamesForNamespace
/*--------------------------------------------------------------------------------
* Implementations from interface DynamoGroup
*--------------------------------------------------------------------------------
*/
public int getGID()
{
return m_gid;
} // end getGID
public boolean addUID(DynamoUser caller, int uid) throws DatabaseException, DynamoSecurityException
{
testPermission(caller,uid,PERM_NAMESPACE,"add.member","join.group","sec.addGroupMember");
return addUIDInternal(uid);
} // end addUID
public boolean removeUID(DynamoUser caller, int uid) throws DatabaseException, DynamoSecurityException
{
testPermission(caller,uid,PERM_NAMESPACE,"remove.member","unjoin.group","sec.removeGroupMember");
return removeUIDInternal(uid);
} // end removeUID
public boolean testUID(int uid) throws DatabaseException
{
Integer key = new Integer(uid);
synchronized (m_members_sync)
{ // look in the cache first
if (m_known_members.contains(key))
return true;
if ((m_known_nonmembers==null) || m_known_nonmembers.contains(key))
return false;
// try the database
boolean rc = m_ops.testMember(m_gid,uid);
if (rc) // add cached information
m_known_members.add(key);
else if (m_known_nonmembers!=null)
m_known_nonmembers.add(key);
return rc;
} // end synchronized block
} // end testUID
public int[] getUIDs() throws DatabaseException
{
int[] rc = null;
synchronized (m_members_sync)
{ // try the cache first
if (m_known_nonmembers==null)
{ // we know we already contain the complete members list, so just get that
rc = new int[m_known_members.size()];
int i = 0;
Iterator it = m_known_members.iterator();
while (it.hasNext())
rc[i++] = ((Integer)(it.next())).intValue();
} // end if
else
{ // have to call down to the database to get the list
rc = m_ops.getMembers(m_gid);
// now we can cache the entire array and dump the nonmembers cache
for (int i=0; i<rc.length; i++)
m_known_members.add(new Integer(rc[i]));
m_known_nonmembers.clear();
m_known_nonmembers = null;
} // end else
} // end synchronized block
return rc;
} // end getUIDs
public boolean addMember(DynamoUser caller, Principal member)
throws DatabaseException, DynamoSecurityException
{
testPermission(caller,getPrincipalUID(member),PERM_NAMESPACE,"add.member","join.group",
"sec.addGroupMember");
if (member instanceof DynamoUser)
return this.addUIDInternal(((DynamoUser)member).getUID());
else if (member instanceof DynamoGroup)
{ // add all UIDs contained in this group
int[] uids = ((DynamoGroup)member).getUIDs();
boolean rc = false;
for (int i=0; i<uids.length; i++)
rc = this.addUIDInternal(uids[i]) || rc;
return rc;
} // end else if
else
throw new IllegalArgumentException("expected DynamoUser or DynamoGroup");
} // end addMember
public boolean removeMember(DynamoUser caller, Principal member)
throws DatabaseException, DynamoSecurityException
{
testPermission(caller,getPrincipalUID(member),PERM_NAMESPACE,"remove.member","unjoin.group",
"sec.removeGroupMember");
if (member instanceof DynamoUser)
return this.removeUIDInternal(((DynamoUser)member).getUID());
else if (member instanceof DynamoGroup)
{ // remove all UIDs contained in this group
int[] uids = ((DynamoGroup)member).getUIDs();
boolean rc = false;
for (int i=0; i<uids.length; i++)
rc = this.removeUIDInternal(uids[i]) || rc;
return rc;
} // end else if
else
throw new IllegalArgumentException("expected DynamoUser or DynamoGroup");
} // end removeMember
public DynamoAcl getAcl() throws DatabaseException, AclNotFoundException
{
if (m_gaclid==-1)
return null;
else
return m_srm.getAcl(m_gaclid);
} // end getAcl
public void setAcl(DynamoUser caller, DynamoAcl acl) throws DatabaseException, DynamoSecurityException
{
testAclOwner(caller);
int new_id = ((acl==null) ? -1 : acl.getAclID());
m_ops.setAclID(m_gid,new_id);
m_gaclid = new_id;
} // end setAcl
} // end class GroupObject

View File

@@ -0,0 +1,63 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.util.*;
abstract class GroupObjectOps extends OpsBase
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected GroupObjectOps(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
abstract Object getProperty(int gid, PropertyKey key) throws DatabaseException;
abstract Object setProperty(int gid, PropertyKey key, Object value) throws DatabaseException;
abstract Object removeProperty(int gid, PropertyKey key) throws DatabaseException;
abstract int[] getPropertyNamespaceIDs(int gid) throws DatabaseException;
abstract Map getAllProperties(int gid, int namespace) throws DatabaseException;
abstract boolean testMember(int gid, int uid) throws DatabaseException;
abstract boolean addMember(int gid, int uid) throws DatabaseException;
abstract boolean removeMember(int gid, int uid) throws DatabaseException;
abstract int[] getMembers(int gid) throws DatabaseException;
abstract void setAclID(int gid, int aclid) throws DatabaseException;
} // end class GroupObjectOps

View File

@@ -0,0 +1,556 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class GroupObjectOps_mysql extends GroupObjectOps
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DBUtilities m_utils;
private PropertySerializer m_psz;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
GroupObjectOps_mysql(DBConnectionPool pool, DBUtilities utils)
{
super(pool);
m_utils = utils;
m_psz = (PropertySerializer)(pool.queryService(PropertySerializer.class));
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class GroupObjectOps
*--------------------------------------------------------------------------------
*/
Object getProperty(int gid, PropertyKey key) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String rc_str = null;
try
{ // get a connection
conn = getConnection();
// look up the property
stmt = conn.prepareStatement("SELECT prop_value FROM groupprop WHERE gid = ? AND nsid = ? "
+ "AND prop_name = ?;");
stmt.setInt(1,gid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
rs = stmt.executeQuery();
if (!(rs.next()))
return null; // property not found
rc_str = rs.getString(1);
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(rc_str);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(GroupObjectOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end getProperty
Object setProperty(int gid, PropertyKey key, Object value) throws DatabaseException
{
String serialized_value = m_psz.serializeProperty(value);
if (serialized_value==null)
{ // serialization exception - throw it
DatabaseException de = new DatabaseException(GroupObjectOps_mysql.class,"DatabaseMessages",
"property.serialize");
de.setParameter(0,key.getName());
throw de;
} // end if
String old_value = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES groupprop WRITE;");
// look to see if the property value is already there
stmt = conn.prepareStatement("SELECT prop_value FROM groupprop WHERE gid = ? AND nsid = ? "
+ "AND prop_name = ?;");
stmt.setInt(1,gid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
rs = stmt.executeQuery();
if (rs.next())
old_value = rs.getString(1);
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
if (old_value!=null)
{ // prepare the statement to update the existing record
stmt = conn.prepareStatement("UPDATE groupprop SET prop_value = ? WHERE gid = ? "
+ "AND nsid = ? AND prop_name = ?;");
stmt.setString(1,serialized_value);
stmt.setInt(2,gid);
stmt.setInt(3,key.getNamespaceID());
stmt.setString(4,key.getName());
} // end if
else
{ // prepare the statement to insert a new record
stmt = conn.prepareStatement("INSERT INTO groupprop (gid, nsid, prop_name, prop_value) "
+ "VALUES (?, ?, ?, ?);");
stmt.setInt(1,gid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
stmt.setString(4,serialized_value);
} // end else
stmt.executeUpdate(); // execute it!
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
if (old_value==null)
return null; // no previous value
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(old_value);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(GroupObjectOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end setProperty
Object removeProperty(int gid, PropertyKey key) throws DatabaseException
{
String old_value = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES groupprop WRITE;");
// look to see if the property value is already there
stmt = conn.prepareStatement("SELECT prop_value FROM groupprop WHERE gid = ? AND nsid = ? "
+ "AND prop_name = ?;");
stmt.setInt(1,gid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
rs = stmt.executeQuery();
if (rs.next())
old_value = rs.getString(1);
else
return null; // no need to remove anything
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
// delete the database row
stmt = conn.prepareStatement("DELETE FROM groupprop WHERE gid = ? AND nsid = ? AND prop_name = ?;");
stmt.setInt(1,gid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(old_value);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(GroupObjectOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end removeProperty
int[] getPropertyNamespaceIDs(int gid) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the query!
stmt = conn.prepareStatement("SELECT DISTINCT nsid FROM groupprop WHERE gid = ?;");
stmt.setInt(1,gid);
rs = stmt.executeQuery();
// read out a list of the namespace IDs
ArrayList tmp = new ArrayList();
while (rs.next())
tmp.add(new Integer(rs.getInt(1)));
// create and return the array
int[] rc = new int[tmp.size()];
for (int i=0; i<tmp.size(); i++)
rc[i] = ((Integer)(tmp.get(i))).intValue();
tmp.clear();
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getPropertyNamespaceIDs
Map getAllProperties(int gid, int namespace) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the query!
stmt = conn.prepareStatement("SELECT prop_name, prop_value FROM groupprop WHERE gid = ? AND nsid = ?;");
stmt.setInt(1,gid);
stmt.setInt(2,namespace);
rs = stmt.executeQuery();
// prepare the return value
HashMap rc = new HashMap();
while (rs.next())
{ // copy data out, deserializing properties as we go
String key = rs.getString(1);
Object value = m_psz.deserializeProperty(rs.getString(2));
if (value==null)
{ // deserialization exception - throw it
DatabaseException de = new DatabaseException(GroupObjectOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key);
throw de;
} // end if
rc.put(key,value);
} // end while
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getAllProperties
boolean testMember(int gid, int uid) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute a query
stmt = conn.prepareStatement("SELECT uid FROM groupmembers WHERE gid = ? AND uid = ?;");
stmt.setInt(1,gid);
stmt.setInt(2,uid);
rs = stmt.executeQuery();
return rs.next();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end testMember
boolean addMember(int gid, int uid) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES groupmembers WRITE;");
// see if we're already in the members list
stmt = conn.prepareStatement("SELECT uid FROM groupmembers WHERE gid = ? AND uid = ?;");
stmt.setInt(1,gid);
stmt.setInt(2,uid);
rs = stmt.executeQuery();
if (rs.next())
return false;
// close statement in prep for next one
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
// insert the member ID!
stmt = conn.prepareStatement("INSERT INTO groupmembers (gid, uid) VALUES (?, ?);");
stmt.setInt(1,gid);
stmt.setInt(2,uid);
stmt.executeUpdate();
return true;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end addMember
boolean removeMember(int gid, int uid) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES groupmembers WRITE;");
// execute the deletion!
stmt = conn.prepareStatement("DELETE FROM groupmembers WHERE gid = ? AND uid = ?;");
stmt.setInt(1,gid);
stmt.setInt(2,uid);
return (stmt.executeUpdate()>0);
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end removeMember
int[] getMembers(int gid) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList tmp = null;
try
{ // get a connection
conn = getConnection();
// create a query to get all the UIDs
stmt = conn.prepareStatement("SELECT uid FROM groupmembers WHERE gid = ?;");
stmt.setInt(1,gid);
rs = stmt.executeQuery();
// fill the intermediate ArrayList
tmp = new ArrayList();
while (rs.next())
tmp.add(new Integer(rs.getInt(1)));
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
// now translate into an integer array
int[] rc = new int[tmp.size()];
for (int i=0; i<tmp.size(); i++)
rc[i] = ((Integer)(tmp.get(i))).intValue();
tmp.clear();
return rc;
} // end getMembers
void setAclID(int gid, int aclid) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES groups WRITE;");
// prepare and execute the statement
stmt = conn.prepareStatement("UPDATE groups SET gaclid = ? WHERE gid = ?;");
stmt.setInt(1,aclid);
stmt.setInt(2,gid);
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end setAclID
} // end class GroupObjectOps_mysql

View File

@@ -0,0 +1,249 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.security.Principal;
import java.security.acl.AclNotFoundException;
import java.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
abstract class GroupProxy implements DynamoGroup, DynamicWrapper
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
protected int m_gid;
protected String m_groupname;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
protected GroupProxy(int gid)
{
m_gid = gid;
m_groupname = null;
} // end constructor
protected GroupProxy(int gid, String groupname)
{
m_gid = gid;
m_groupname = groupname;
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
protected abstract DynamoGroup getRealGroup();
/*--------------------------------------------------------------------------------
* Implementations from interface Principal
*--------------------------------------------------------------------------------
*/
public boolean equals(Object another)
{
if (another==null)
return false;
if (another instanceof DynamoGroup)
return (m_gid==((DynamoGroup)another).getGID());
return false;
} // end equals
public String toString()
{
if (m_groupname!=null)
return "group " + m_groupname;
return getRealGroup().toString();
} // end toString
public int hashCode()
{
return m_gid;
} // end hashCode
public String getName()
{
if (m_groupname!=null)
return m_groupname;
return getRealGroup().getName();
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface Group
*--------------------------------------------------------------------------------
*/
public boolean addMember(Principal user)
{
return getRealGroup().addMember(user);
} // end addMember
public boolean removeMember(Principal user)
{
return getRealGroup().removeMember(user);
} // end removeMember
public boolean isMember(Principal member)
{
return getRealGroup().isMember(member);
} // end isMember
public Enumeration members()
{
return getRealGroup().members();
} // end members
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectProvider
*--------------------------------------------------------------------------------
*/
/**
* Retrieves an object from this <CODE>ObjectProvider</CODE>.
*
* @param namespace The namespace to interpret the name relative to.
* @param name The name of the object to be retrieved.
* @return The object reference specified.
*/
public Object getObject(String namespace, String name)
{
return getRealGroup().getObject(namespace,name);
} // end getObject
/*--------------------------------------------------------------------------------
* Implementations from interface SecureObjectStore
*--------------------------------------------------------------------------------
*/
public Object setObject(DynamoUser caller, String namespace, String name, Object value)
throws DatabaseException, DynamoSecurityException
{
return getRealGroup().setObject(caller,namespace,name,value);
} // end setObject
public Object removeObject(DynamoUser caller, String namespace, String name)
throws DatabaseException, DynamoSecurityException
{
return getRealGroup().removeObject(caller,namespace,name);
} // end removeObject
public Collection getNamespaces() throws DatabaseException
{
return getRealGroup().getNamespaces();
} // end getNamespaces
public Collection getNamesForNamespace(String namespace) throws DatabaseException
{
return getRealGroup().getNamesForNamespace(namespace);
} // end getNamesForNamespace
/*--------------------------------------------------------------------------------
* Implementations from interface DynamoGroup
*--------------------------------------------------------------------------------
*/
public int getGID()
{
return m_gid;
} // end getGID
public boolean addUID(DynamoUser caller, int uid) throws DatabaseException, DynamoSecurityException
{
return getRealGroup().addUID(caller,uid);
} // end addUID
public boolean removeUID(DynamoUser caller, int uid) throws DatabaseException, DynamoSecurityException
{
return getRealGroup().removeUID(caller,uid);
} // end removeUID
public boolean testUID(int uid) throws DatabaseException
{
return getRealGroup().testUID(uid);
} // end testUID
public int[] getUIDs() throws DatabaseException
{
return getRealGroup().getUIDs();
} // end getUIDs
public boolean addMember(DynamoUser caller, Principal member)
throws DatabaseException, DynamoSecurityException
{
return getRealGroup().addMember(caller,member);
} // end addMember
public boolean removeMember(DynamoUser caller, Principal member)
throws DatabaseException, DynamoSecurityException
{
return getRealGroup().removeMember(caller,member);
} // end removeMember
public DynamoAcl getAcl() throws DatabaseException, AclNotFoundException
{
return getRealGroup().getAcl();
} // end getAcl
public void setAcl(DynamoUser caller, DynamoAcl acl) throws DatabaseException, DynamoSecurityException
{
getRealGroup().setAcl(caller,acl);
} // end setAcl
/*--------------------------------------------------------------------------------
* Implementations from interface DynamicWrapper
*--------------------------------------------------------------------------------
*/
public Object unwrap()
{
return getRealGroup();
} // end unwrap
} // end class GroupProxy

View File

@@ -0,0 +1,42 @@
/*
* 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.security.Principal;
import com.silverwrist.dynamo.except.DatabaseException;
import com.silverwrist.dynamo.except.DynamoSecurityException;
import com.silverwrist.dynamo.iface.DataItem;
import com.silverwrist.dynamo.iface.DynamoUser;
public interface ImageStore
{
public DataItem getImage(int id) throws DatabaseException;
public int saveNewImage(String type_namespace, String type_name, Principal owner, DataItem image)
throws DatabaseException;
public void replaceImage(DynamoUser caller, int image_id, DataItem image)
throws DatabaseException, DynamoSecurityException;
public int findImageID(String type_namespace, String type_name, Principal owner) throws DatabaseException;
public void deleteImage(DynamoUser caller, int image_id) throws DatabaseException, DynamoSecurityException;
public DataItem normalizeImage(DataItem source, int width, int height, String new_type) throws Exception;
} // end interface ImageStore

View File

@@ -0,0 +1,249 @@
/*
* 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.security.Principal;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.image.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class ImageStoreObject implements NamedObject, ComponentInitialize, ComponentShutdown, ImageStore
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name; // object name
private NamespaceCache m_ns_cache; // namespace cache object
private ImageStoreOps m_ops; // image store operations
private Hashtable m_imagetype_tlb = new Hashtable(); // translates imagetypes
private Hashtable m_imagetype_rev_tlb = new Hashtable(); // translates imagetypes
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ImageStoreObject()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private final int imageTypeToIndex(PropertyKey pkey) throws DatabaseException
{
Integer foo = (Integer)(m_imagetype_tlb.get(pkey));
if (foo!=null)
return foo.intValue();
int rc = m_ops.imageTypeToIndex(pkey);
foo = new Integer(rc);
m_imagetype_tlb.put(pkey,foo);
m_imagetype_rev_tlb.put(foo,pkey);
return rc;
} // end imageTypeToIndex
private final int imageTypeToIndex(int nsid, String name) throws DatabaseException
{
return imageTypeToIndex(new PropertyKey(nsid,name));
} // end imageTypeToIndex
private final int imageTypeToIndex(String namespace, String name) throws DatabaseException
{
return imageTypeToIndex(new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name));
} // end imageTypeToIndex
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentInitialize
*--------------------------------------------------------------------------------
*/
public void initialize(Element config_root, ServiceProvider services) throws ConfigException
{
String conn_name = null;
String nscache_name = null;
XMLLoader loader = XMLLoader.get();
try
{ // verify the right node name
loader.verifyNodeName(config_root,"object");
// get the object's name
m_name = loader.getAttribute(config_root,"name");
// get the database configuration connection
DOMElementHelper config_root_h = new DOMElementHelper(config_root);
Element elt = loader.getSubElement(config_root_h,"database");
conn_name = loader.getAttribute(elt,"connection");
nscache_name = loader.getAttribute(elt,"namespaces");
} // end try
catch (XMLLoadException e)
{ // error loading XML config data
throw new ConfigException(e);
} // end catch
// Get the database connection pool and namespace cache.
DBConnectionPool pool = GetObjectUtils.getDatabaseConnection(services,conn_name);
m_ns_cache =
(NamespaceCache)(GetObjectUtils.getDynamoComponent(services,NamespaceCache.class,nscache_name));
// Get the operations object.
m_ops = ImageStoreOps.get(pool);
} // end initialize
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
public void shutdown()
{
m_ops.dispose();
m_ops = null;
m_ns_cache = null;
} // end shutdown
/*--------------------------------------------------------------------------------
* Implementations from interface ImageStore
*--------------------------------------------------------------------------------
*/
public DataItem getImage(int id) throws DatabaseException
{
return m_ops.getImage(id);
} // end getImage
public int saveNewImage(String type_namespace, String type_name, Principal owner, DataItem image)
throws DatabaseException
{
int image_type = imageTypeToIndex(type_namespace,type_name);
int owner_id = 0, owner_flag = 0;
if (owner instanceof DynamoUser)
owner_id = ((DynamoUser)owner).getUID();
else if (owner instanceof DynamoGroup)
{ // get the GID
owner_id = ((DynamoGroup)owner).getGID();
owner_flag = 1;
} // end else if
else
throw new DatabaseException(ImageStoreObject.class,"DatabaseMessages","img.badOwner");
// call down to the database to save it all off
return m_ops.saveNewImage(image_type,owner_id,owner_flag,image);
} // end saveNewImage
public void replaceImage(DynamoUser caller, int image_id, DataItem image)
throws DatabaseException, DynamoSecurityException
{
if (m_ops.canReplaceImage(caller.getUID(),image_id))
m_ops.replaceImage(image_id,image);
else
{ // throw a security exception here
DynamoSecurityException dse = new DynamoSecurityException(ImageStoreObject.class,"DatabaseMessages",
"img.notOwner");
dse.setParameter(0,String.valueOf(image_id));
throw dse;
} // end else
} // end replaceImage
public int findImageID(String type_namespace, String type_name, Principal owner) throws DatabaseException
{
int image_type = imageTypeToIndex(type_namespace,type_name);
int owner_id = 0, owner_flag = 0;
if (owner instanceof DynamoUser)
owner_id = ((DynamoUser)owner).getUID();
else if (owner instanceof DynamoGroup)
{ // get the GID
owner_id = ((DynamoGroup)owner).getGID();
owner_flag = 1;
} // end else if
else
throw new DatabaseException(ImageStoreObject.class,"DatabaseMessages","img.badOwner");
// call down to find it
return m_ops.findImageID(image_type,owner_id,owner_flag);
} // end findImageID
public void deleteImage(DynamoUser caller, int image_id) throws DatabaseException, DynamoSecurityException
{
if (m_ops.canReplaceImage(caller.getUID(),image_id))
m_ops.deleteImage(image_id);
else
{ // throw a security exception here
DynamoSecurityException dse = new DynamoSecurityException(ImageStoreObject.class,"DatabaseMessages",
"img.notOwner");
dse.setParameter(0,String.valueOf(image_id));
throw dse;
} // end else
} // end deleteImage
public DataItem normalizeImage(DataItem source, int width, int height, String new_type) throws Exception
{
try
{ // normalize the image and encapsulate it in a StaticDataItem
byte[] data = ImageNormalizer.normalizeImage(source.getDataStream(),width,height,new_type);
return new StaticDataItem(source.getName() + "-converted",new_type,data.length,data);
} // end try
catch (ImageNormalizerException e)
{ // morph the exception
ExternalException ee = new ExternalException(ImageStoreObject.class,"DatabaseMessages",
"img.normalize",e);
ee.setParameter(0,source.getName());
ee.setParameter(1,e.getMessage());
throw ee;
} // end catch
} // end normalizeImage
} // end class ImageStoreObject

View File

@@ -0,0 +1,80 @@
/*
* 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
abstract class ImageStoreOps extends OpsBase
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected ImageStoreOps(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class OpsBase
*--------------------------------------------------------------------------------
*/
public void dispose()
{
super.dispose();
} // end dispose
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
abstract int imageTypeToIndex(PropertyKey pkey) throws DatabaseException;
abstract DataItem getImage(int id) throws DatabaseException;
abstract int saveNewImage(int typecode, int owner_id, int owner_flag, DataItem image)
throws DatabaseException;
abstract boolean canReplaceImage(int uid, int image_id) throws DatabaseException;
abstract void replaceImage(int image_id, DataItem image) throws DatabaseException;
abstract int findImageID(int typecode, int owner_id, int owner_flag) throws DatabaseException;
abstract void deleteImage(int image_id) throws DatabaseException;
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
static ImageStoreOps get(DBConnectionPool pool) throws ConfigException
{
return (ImageStoreOps)get(pool,ImageStoreOps.class.getClassLoader(),
ImageStoreOps.class.getName() + "_","ImageStoreOps");
} // end get
} // end class ImageStoreOps

View File

@@ -0,0 +1,363 @@
/*
* 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.io.*;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class ImageStoreOps_mysql extends ImageStoreOps
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ImageStoreOps_mysql(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class ImageStoreOps
*--------------------------------------------------------------------------------
*/
int imageTypeToIndex(PropertyKey pkey) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table while we work
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES imagetype WRITE;");
// first try to look the index up
stmt = conn.prepareStatement("SELECT typecode FROM imagetype WHERE nsid = ? AND name = ?;");
stmt.setInt(1,pkey.getNamespaceID());
stmt.setString(2,pkey.getName());
rs = stmt.executeQuery();
if (rs.next())
return rs.getInt(1);
// then add it
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
stmt = conn.prepareStatement("INSERT INTO imagetype (nsid, name) VALUES (?, ?);");
stmt.setInt(1,pkey.getNamespaceID());
stmt.setString(2,pkey.getName());
stmt.executeUpdate();
return MySQLUtils.getLastInsertInt(conn);
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end imageTypeToIndex
DataItem getImage(int id) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// Start by getting the MIME type and image length.
stmt = conn.prepareStatement("SELECT mimetype, length FROM imagestore WHERE imageid = ?;");
stmt.setInt(1,id);
rs = stmt.executeQuery();
if (!(rs.next()))
return null;
String mime_type = rs.getString(1);
int length = rs.getInt(2);
// Now get the actual data blob.
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
stmt = conn.prepareStatement("SELECT data FROM imagestore WHERE imageid = ?;");
stmt.setInt(1,id);
rs = stmt.executeQuery();
if (!(rs.next()))
return null;
// We need to copy the data blob into a local buffer. We also mesh the whole thing into a DataItem.
return new StaticDataItem("image" + id,mime_type,length,IOUtils.load(rs.getBinaryStream(1)));
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
catch (IOException e)
{ // turn IOException into DatabaseException too
DatabaseException de = new DatabaseException(ImageStoreOps_mysql.class,"DatabaseMessages",
"img.loadFail",e);
de.setParameter(0,String.valueOf(id));
throw de;
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getImage
int saveNewImage(int typecode, int owner_id, int owner_flag, DataItem image) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
try
{ // get a connection
conn = getConnection();
// lock the table while we work
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES imagestore WRITE;");
// insert all the "base" information
stmt = conn.prepareStatement("INSERT INTO imagestore (typecode, ownerid, ownerflag, mimetype, length) "
+ "VALUES (?, ?, ?, ?, ?);");
stmt.setInt(1,typecode);
stmt.setInt(2,owner_id);
stmt.setInt(3,owner_flag);
stmt.setString(4,image.getMimeType());
stmt.setInt(5,image.getSize());
stmt.executeUpdate();
int rc = MySQLUtils.getLastInsertInt(conn);
// insert the file data itself
SQLUtils.shutdown(stmt);
stmt = conn.prepareStatement("UPDATE imagestore SET data = ? WHERE imageid = ?;");
stmt.setBlob(1,image.getBlob());
stmt.setInt(2,rc);
stmt.executeUpdate();
return rc; // all done!
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end saveNewImage
boolean canReplaceImage(int uid, int image_id) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// get the owner ID and flag from the image records
stmt = conn.prepareStatement("SELECT ownerid, ownerflag FROM imagestore WHERE imageid = ?;");
stmt.setInt(1,image_id);
rs = stmt.executeQuery();
if (!(rs.next()))
return false;
int owner_id = rs.getInt(1);
if (rs.getInt(2)==0) // a user owns it
return (uid==owner_id);
// Test group membership for ownership.
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
stmt = conn.prepareStatement("SELECT uid FROM groupmembers WHERE uid = ? AND gid = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,owner_id);
rs = stmt.executeQuery();
return rs.next();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end canReplaceImage
void replaceImage(int image_id, DataItem image) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
try
{ // get a connection
conn = getConnection();
// lock the table while we work
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES imagestore WRITE;");
// poke in the basic data items first
stmt = conn.prepareStatement("UPDATE imagestore SET mimetype = ?, length = ?, data = NULL "
+ "WHERE imageid = ?;");
stmt.setString(1,image.getMimeType());
stmt.setInt(2,image.getSize());
stmt.setInt(3,image_id);
stmt.executeUpdate();
// insert the new file data itself
SQLUtils.shutdown(stmt);
stmt = conn.prepareStatement("UPDATE imagestore SET data = ? WHERE imageid = ?;");
stmt.setBlob(1,image.getBlob());
stmt.setInt(2,image_id);
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end replaceImage
int findImageID(int typecode, int owner_id, int owner_flag) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// create statement and run it
stmt = conn.prepareStatement("SELECT imageid FROM imagestore WHERE typecode = ? AND ownerid = ? "
+ "AND ownerflag = ?;");
stmt.setInt(1,typecode);
stmt.setInt(2,owner_id);
stmt.setInt(3,owner_flag);
rs = stmt.executeQuery();
if (rs.next())
return rs.getInt(1);
else
return -1;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end findImageID
void deleteImage(int image_id) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
try
{ // get a connection
conn = getConnection();
// lock the table while we work
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES imagestore WRITE;");
// delete it!
stmt = conn.prepareStatement("DELETE FROM imagestore WHERE imageid = ?;");
stmt.setInt(1,image_id);
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end deleteImage
} // end class ImageStoreOps_mysql

View File

@@ -0,0 +1,28 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import com.silverwrist.dynamo.except.DatabaseException;
public interface NamespaceCache
{
public int namespaceNameToId(String name) throws DatabaseException;
public String namespaceIdToName(int id) throws DatabaseException;
} // end interface NamespaceCache

View File

@@ -0,0 +1,143 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.Namespaces;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class NamespaceCacheObject
implements NamedObject, ComponentInitialize, ComponentShutdown, NamespaceCache
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name; // object name
private NamespaceCacheOps m_ops; // low-level database operations
private HashMap m_cache = new HashMap(); // namespace cache object
private HashMap m_rev_cache = new HashMap(); // namespace reverse cache object
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public NamespaceCacheObject()
{
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentInitialize
*--------------------------------------------------------------------------------
*/
public void initialize(Element config_root, ServiceProvider services) throws ConfigException
{
String conn_name = null;
XMLLoader loader = XMLLoader.get();
try
{ // verify the right node name
loader.verifyNodeName(config_root,"object");
// get the object's name
m_name = loader.getAttribute(config_root,"name");
// get the database configuration connection
Element elt = loader.getSubElement(config_root,"database");
conn_name = loader.getAttribute(elt,"connection");
} // end try
catch (XMLLoadException e)
{ // error loading XML config data
throw new ConfigException(e);
} // end catch
// Get the database connection pool.
DBConnectionPool pool = GetObjectUtils.getDatabaseConnection(services,conn_name);
// Get the database operations class.
m_ops = NamespaceCacheOps.get(pool);
} // end initialize
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
public void shutdown()
{
m_ops.dispose();
m_ops = null;
} // end shutdown
/*--------------------------------------------------------------------------------
* Implementations from interface NamespaceCache
*--------------------------------------------------------------------------------
*/
public synchronized int namespaceNameToId(String name) throws DatabaseException
{
Integer rc = (Integer)(m_cache.get(name));
if (rc!=null)
return rc.intValue();
int real_id = m_ops.namespaceNameToId(name);
rc = new Integer(real_id);
name = name.intern();
m_cache.put(name,rc);
m_rev_cache.put(rc,name);
return real_id;
} // end namespaceNameToId
public synchronized String namespaceIdToName(int id) throws DatabaseException
{
Integer key = new Integer(id);
String rc = (String)(m_rev_cache.get(key));
if (rc!=null)
return rc;
rc = m_ops.namespaceIdToName(id);
if (rc==null)
throw new DatabaseException(NamespaceCacheObject.class,"DatabaseMessages","nsCache.notFound");
rc = rc.intern();
m_cache.put(rc,key);
m_rev_cache.put(key,rc);
return rc;
} // end namespaceIdToName
} // end class NamespaceCacheObject

View File

@@ -0,0 +1,69 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.lang.reflect.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
abstract class NamespaceCacheOps extends OpsBase
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected NamespaceCacheOps(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class OpsBase
*--------------------------------------------------------------------------------
*/
public void dispose()
{
super.dispose();
} // end dispose
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
abstract int namespaceNameToId(String name) throws DatabaseException;
abstract String namespaceIdToName(int id) throws DatabaseException;
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
static NamespaceCacheOps get(DBConnectionPool pool) throws ConfigException
{
return (NamespaceCacheOps)get(pool,NamespaceCacheOps.class.getClassLoader(),
NamespaceCacheOps.class.getName() + "_","NamespaceCacheOps");
} // end get
} // end class NamespaceCacheOps

View File

@@ -0,0 +1,132 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
public class NamespaceCacheOps_mysql extends NamespaceCacheOps
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public NamespaceCacheOps_mysql(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class NamespaceCacheOps
*--------------------------------------------------------------------------------
*/
int namespaceNameToId(String name) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table while we do this
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES namespaces WRITE;");
// try the initial SELECT to see if it works
stmt = conn.prepareStatement("SELECT nsid FROM namespaces WHERE namespace = ?;");
stmt.setString(1,name);
rs = stmt.executeQuery();
if (rs.next())
return rs.getInt(1);
// it wasn't present - try adding it
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
stmt = conn.prepareStatement("INSERT INTO namespaces (namespace) VALUES (?);");
stmt.setString(1,name);
stmt.executeUpdate();
return MySQLUtils.getLastInsertInt(conn);
} // end try
catch (SQLException e)
{ // translate this to a DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end namespaceNameToId
String namespaceIdToName(int id) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table while we do this
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES namespaces READ;");
// try the SELECT to see if it works
stmt = conn.prepareStatement("SELECT namespace FROM namespaces WHERE nsid = ?;");
stmt.setInt(1,id);
rs = stmt.executeQuery();
if (rs.next())
return rs.getString(1);
else
return null;
} // end try
catch (SQLException e)
{ // translate the exception and rethrow
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end namespaceIdToName
} // end class NamespaceCacheOps_mysql

View File

@@ -0,0 +1,118 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.lang.reflect.*;
import java.sql.Connection;
import java.sql.SQLException;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
public class OpsBase
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final Class[] ARGS_CLASS = { DBConnectionPool.class };
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DBConnectionPool m_pool;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected OpsBase(DBConnectionPool pool)
{
m_pool = pool;
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
protected final DBConnectionPool getPool()
{
return m_pool;
} // end getPool
protected final Connection getConnection() throws DatabaseException
{
return new WrappedConnection(m_pool,m_pool.getConnection());
} // end getConnection
protected final DatabaseException generalException(SQLException e)
{
DatabaseException dbe = new DatabaseException(OpsBase.class,"DatabaseMessages","general",e);
dbe.setParameter(0,e.getMessage());
return dbe;
} // end generalException
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public void dispose()
{
m_pool = null;
} // end dispose
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
protected static Object get(DBConnectionPool pool, ClassLoader loader, String stem_name, String type)
throws ConfigException
{
try
{ // load the specified ops class and return a new instance
String klassname = stem_name + pool.getDatabaseType().toLowerCase();
Constructor c = loader.loadClass(klassname).getConstructor(ARGS_CLASS);
Object[] args = new Object[1];
args[0] = pool;
return c.newInstance(args);
} // end try
catch (Exception e)
{ // error loading the ops class...
ConfigException ce = new ConfigException(OpsBase.class,"DatabaseMessages","load.opsClass",e);
ce.setParameter(0,e.getMessage());
ce.setParameter(1,pool.getDatabaseType());
ce.setParameter(2,type);
throw ce;
} // end catch
} // end get
} // end class OpsBase

View File

@@ -0,0 +1,42 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.Collection;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
public interface UserManagement
{
public DynamoUser getAnonymousUser() throws DatabaseException;
public DynamoUser getUser(int id) throws DatabaseException;
public DynamoUser getUser(String username) throws DatabaseException;
public DynamoUser createUser(String username, String email) throws DatabaseException;
public DynamoGroup getGroup(int id) throws DatabaseException;
public DynamoGroup getGroup(String groupname) throws DatabaseException;
public DynamoGroup createGroup(String groupname) throws DatabaseException;
public void loadUserDefaults(DynamoUser user, Collection namespaces) throws DatabaseException;
} // end interface UserManagement

View File

@@ -0,0 +1,987 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.lang.ref.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.UserInfoNamespace;
import com.silverwrist.dynamo.event.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;
public class UserManagerObject
implements NamedObject, ComponentInitialize, ComponentShutdown, UserManagement, UserProxyManagement,
AuthenticatorRegistration, UserInfoNamespace, UserPropertyTranslatorInstall
{
/*--------------------------------------------------------------------------------
* Internal class implementing user proxies
*--------------------------------------------------------------------------------
*/
private class MyUserProxy extends UserProxy
{
/*====================================================================
* Attributes
*====================================================================
*/
private DynamoUser m_real_user = null;
/*====================================================================
* Constructors
*====================================================================
*/
MyUserProxy(int uid)
{
super(uid);
} // end constructor
MyUserProxy(int uid, String username)
{
super(uid,username);
} // end constructor
/*====================================================================
* Abstract implementations from class UserProxy
*====================================================================
*/
protected synchronized DynamoUser getRealUser()
{
if (m_real_user==null)
{ // need to retrieve the real user...
try
{ // get the real user...
m_real_user = UserManagerObject.this.getUser(m_uid);
} // end try
catch (DatabaseException e)
{ // wrap it in a runtime exception type
throw new ProxyException(e);
} // end catch
} // end if
return m_real_user;
} // end getRealUser
} // end class MyUserProxy
/*--------------------------------------------------------------------------------
* Internal class implementing group proxies
*--------------------------------------------------------------------------------
*/
private class MyGroupProxy extends GroupProxy
{
/*====================================================================
* Attributes
*====================================================================
*/
private DynamoGroup m_real_group = null;
/*====================================================================
* Constructors
*====================================================================
*/
MyGroupProxy(int gid)
{
super(gid);
} // end constructor
MyGroupProxy(int gid, String groupname)
{
super(gid,groupname);
} // end constructor
/*====================================================================
* Abstract implementations from class UserProxy
*====================================================================
*/
protected synchronized DynamoGroup getRealGroup()
{
if (m_real_group==null)
{ // need to retrieve the real group...
try
{ // get the real group...
m_real_group = UserManagerObject.this.getGroup(m_gid);
} // end try
catch (DatabaseException e)
{ // wrap it in a runtime exception type
throw new ProxyException(e);
} // end catch
} // end if
return m_real_group;
} // end getRealGroup
} // end class MyGroupProxy
/*--------------------------------------------------------------------------------
* Internal event listener class
*--------------------------------------------------------------------------------
*/
private class UpdateListener implements DynamicUpdateListener
{
/*====================================================================
* Constructor
*====================================================================
*/
UpdateListener()
{ // do nothing
} // end constructor
/*====================================================================
* Implementations from interface DynamicUpdateListener
*====================================================================
*/
public void updateReceived(DynamicUpdateEvent evt)
{
if (evt instanceof UserUpdateEvent)
{ // try to pass the event on to the user
int uid = ((UserUpdateEvent)evt).getUID();
Integer key = new Integer(uid);
synchronized (m_users_sync)
{ // try looking in the cache for a UserObject
IDNameCacheObject cobj = (IDNameCacheObject)(m_id_to_user.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the user value
UserObject target = (UserObject)(cobj.get());
if (target==null)
{ // the UserObject got kicked out! kick it out of the HashMaps
m_id_to_user.remove(key);
m_name_to_user.remove(cobj.getNameKey());
cobj.clear();
cobj = null;
} // end if
else if (target!=evt.getSource())
target.updated((UserUpdateEvent)evt);
} // end if
} // end synchronized block
} // end if
} // end updateReceived
} // end class UpdateListener
/*--------------------------------------------------------------------------------
* Internal property serializer class
*--------------------------------------------------------------------------------
*/
private class UserGroupSerializer implements PropertySerializer
{
/*====================================================================
* Constructor
*====================================================================
*/
UserGroupSerializer()
{ // do nothing
} // end constructor
/*====================================================================
* Implementations from interface PropertySerializer
*====================================================================
*/
public String serializeProperty(Object value)
{
if (value instanceof DynamoUser)
return "User:" + String.valueOf(((DynamoUser)value).getUID());
if (value instanceof DynamoGroup)
return "Group:" + String.valueOf(((DynamoGroup)value).getGID());
return null;
} // end serializeProperty
public Object deserializeProperty(String value)
{
try
{ // look for our known prefixes
if (value.startsWith("User:"))
return getUserProxy(Integer.parseInt(value.substring(5)));
if (value.startsWith("Group:"))
return getGroupProxy(Integer.parseInt(value.substring(6)));
return null;
} // end try
catch (NumberFormatException e)
{ // number parse blew up...
return null;
} // end catch
} // end deserializeProperty
} // end UserGroupSerializer
/*--------------------------------------------------------------------------------
* Internal class implementing the adapter for UserPropertyTranslator
*--------------------------------------------------------------------------------
*/
class UserPropertyAdapter implements UserPropertyTranslator
{
/*====================================================================
* Attributes
*====================================================================
*/
private UserPropertyTranslator m_upt = null;
/*====================================================================
* Constructor
*====================================================================
*/
UserPropertyAdapter()
{ // do nothing
} // end constructor
/*====================================================================
* Implementations from interface UserPropertyTranslator
*====================================================================
*/
public String getUserFullName(DynamoUser user)
{
if (m_upt!=null)
return m_upt.getUserFullName(user);
else
return user.getName();
} // end getUserFullName
/*====================================================================
* External operations
*====================================================================
*/
void setTranslator(UserPropertyTranslator upt)
{
m_upt = upt;
} // end setTranslator
} // end class UserPropertyAdapter
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final int MAX_USERNAME = 64;
private static final int MAX_GROUPNAME = 64;
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private UserPropertyAdapter m_adapter; // user property adapter
private String m_name; // object name
private NamespaceCache m_ns_cache; // namespace cache object
private SecurityReferenceMonitor m_srm; // security reference monitor
private PostDynamicUpdate m_post; // dynamic update poster
private UserManagerOps m_ops; // database operations object
private UserObject m_anon_user = null; // permanent reference to anonymous user
private Object m_anon_user_sync = new Object(); // synchronization on the above field
private HashMap m_id_to_user = new HashMap(); // map from IDs (Integer) to objects
private HashMap m_name_to_user = new HashMap(); // map from names (DynamoIDKey) to objects
private ReferenceQueue m_rq = new ReferenceQueue(); // reference queue for old objects
private Object m_users_sync = new Object(); // synchronization for user HashMaps
private HashMap m_id_to_group = new HashMap(); // map from IDs (Integer) to groups
private HashMap m_name_to_group = new HashMap(); // map from names (DynamoIDKey) to groups
private ReferenceQueue m_group_rq = new ReferenceQueue(); // reference queue for group objects
private Object m_groups_sync = new Object(); // synchronization for group HashMaps
private Hashtable m_authenticators = new Hashtable(); // authenticators list
private ComponentShutdown m_hook_init; // hook for init service provider
private ComponentShutdown m_pszreg; // property serializer registration
private ComponentShutdown m_evt_user; // event registration
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public UserManagerObject()
{
m_adapter = new UserPropertyAdapter(); // create the adapter
// Add some default authenticators.
m_authenticators.put(new QualifiedNameKey(NAMESPACE,AUTH_DEFAULT),new DefaultHashAuthenticator());
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentInitialize
*--------------------------------------------------------------------------------
*/
public void initialize(Element config_root, ServiceProvider services) throws ConfigException
{
String conn_name = null;
String nscache_name = null;
String srm_name = null;
String connect_name = null;
XMLLoader loader = XMLLoader.get();
try
{ // verify the right node name
loader.verifyNodeName(config_root,"object");
// get the object's name
m_name = loader.getAttribute(config_root,"name");
// get the database configuration connection
DOMElementHelper config_root_h = new DOMElementHelper(config_root);
Element elt = loader.getSubElement(config_root_h,"database");
conn_name = loader.getAttribute(elt,"connection");
nscache_name = loader.getAttribute(elt,"namespaces");
// get the security reference monitor reference
elt = loader.getSubElement(config_root_h,"security");
srm_name = loader.getAttribute(elt,"object");
// get the name of the connection point to connect ourselves to
elt = config_root_h.getSubElement("connect-proxy-services");
if (elt!=null)
connect_name = loader.getAttribute(elt,"cpoint");
} // end try
catch (XMLLoadException e)
{ // error loading XML config data
throw new ConfigException(e);
} // end catch
// Get the database connection pool, namespace cache, and security reference monitor.
DBConnectionPool pool = GetObjectUtils.getDatabaseConnection(services,conn_name);
m_ns_cache =
(NamespaceCache)(GetObjectUtils.getDynamoComponent(services,NamespaceCache.class,nscache_name));
m_srm =
(SecurityReferenceMonitor)(GetObjectUtils.getDynamoComponent(services,SecurityReferenceMonitor.class,
srm_name));
m_post = (PostDynamicUpdate)(services.queryService(PostDynamicUpdate.class));
// Get the operations object.
m_ops = UserManagerOps.get(pool);
// Connect our proxy services to the connection point.
if (connect_name!=null)
{ // get the ConnectionBackend service and use it to jack in
ConnectionBackEnd backend = (ConnectionBackEnd)(services.queryService(ConnectionBackEnd.class));
backend.connectObject(connect_name,this);
} // end if
// Register event listeners that forward events to the right location.
EventListenerRegistration reg =
(EventListenerRegistration)(services.queryService(EventListenerRegistration.class));
UpdateListener ul = new UpdateListener();
m_evt_user = reg.registerDynamicUpdateListener(UserUpdateEvent.class,ul);
// Register our property serializer to let User and Group objects be serialized.
PropertySerializerRegistration psreg =
(PropertySerializerRegistration)(services.queryService(PropertySerializerRegistration.class));
m_pszreg = psreg.registerPropertySerializer(new UserGroupSerializer());
// Add us to the initialization services.
HookServiceProviders hooker = (HookServiceProviders)(services.queryService(HookServiceProviders.class));
SingletonServiceProvider ssp = new SingletonServiceProvider("UserManagerObject",
AuthenticatorRegistration.class,
(AuthenticatorRegistration)this);
m_hook_init = hooker.hookInitServiceProvider(ssp);
} // end initialize
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
public void shutdown()
{
m_evt_user.shutdown();
m_evt_user = null;
m_pszreg.shutdown();
m_pszreg = null;
m_hook_init.shutdown();
m_hook_init = null;
m_authenticators.clear();
m_id_to_user.clear();
m_name_to_user.clear();
m_anon_user = null;
m_ops.dispose();
m_ops = null;
m_post = null;
m_srm = null;
m_ns_cache = null;
} // end shutdown
/*--------------------------------------------------------------------------------
* Implementations from interface UserManagement
*--------------------------------------------------------------------------------
*/
public DynamoUser getAnonymousUser() throws DatabaseException
{
synchronized (m_anon_user_sync)
{ // get the anonymous user, if it doesn't already exist
if (m_anon_user==null)
{ // get the data for the anonymous user
Map data = m_ops.getAnonymousUserData();
if (data==null)
throw new DatabaseException(UserManagerObject.class,"UserMessages","anon.notFound");
m_anon_user = new UserObject(data,true,m_ops.getObjectOps(),m_ns_cache,m_srm,this,m_post,m_adapter);
} // end if
return m_anon_user;
} // end synchronized block
} // end getAnonymousUser
public DynamoUser getUser(int id) throws DatabaseException
{
DynamoUser rc = getAnonymousUser();
if (rc.getUID()==id)
return rc;
rc = null;
Integer key = new Integer(id);
synchronized (m_users_sync)
{ // try to retrieve the user
IDNameCacheObject cobj = (IDNameCacheObject)(m_id_to_user.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the user value
rc = (DynamoUser)(cobj.get());
if (rc==null)
{ // the UserObject got kicked out! kick it out of the HashMaps
m_id_to_user.remove(key);
m_name_to_user.remove(cobj.getNameKey());
cobj.clear();
cobj = null;
} // end if
} // end if
if (rc==null)
{ // OK, we have to go to the database to find the user
Map data = m_ops.getUserData(id);
if (data!=null)
{ // create UserObject and add it to our cache maps
UserObject uobj = new UserObject(data,false,m_ops.getObjectOps(),m_ns_cache,m_srm,this,m_post,
m_adapter);
rc = uobj;
cobj = new IDNameCacheObject(key,uobj.getName(),uobj,m_rq);
m_id_to_user.put(cobj.getIDKey(),cobj);
m_name_to_user.put(cobj.getNameKey(),cobj);
} // end if
// else user does not exist - return null
} // end if
} // end synchronized block
return rc;
} // end getUser
public DynamoUser getUser(String username) throws DatabaseException
{
DynamoUser rc = getAnonymousUser();
if (rc.getName().equalsIgnoreCase(username))
return rc;
rc = null;
DynamoIDKey key = new DynamoIDKey(username);
synchronized (m_users_sync)
{ // try to retrieve the user
IDNameCacheObject cobj = (IDNameCacheObject)(m_name_to_user.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the user value
rc = (DynamoUser)(cobj.get());
if (rc==null)
{ // the UserObject got kicked out! kick it out of the HashMaps
m_id_to_user.remove(cobj.getIDKey());
m_name_to_user.remove(key);
cobj.clear();
cobj = null;
} // end if
} // end if
if (rc==null)
{ // OK, we have to go to the database to find the user
Map data = m_ops.getUserData(username);
if (data!=null)
{ // create user object and add it to our cache maps
UserObject uobj = new UserObject(data,false,m_ops.getObjectOps(),m_ns_cache,m_srm,this,m_post,
m_adapter);
rc = uobj;
cobj = new IDNameCacheObject(uobj.getUID(),key,uobj,m_rq);
m_id_to_user.put(cobj.getIDKey(),cobj);
m_name_to_user.put(cobj.getNameKey(),cobj);
} // end if
// else user does not exist - return null
} // end if
} // end synchronized block
return rc;
} // end getUser
public DynamoUser createUser(String username, String email) throws DatabaseException
{
DynamoUser rc = getAnonymousUser();
if (rc.getName().equalsIgnoreCase(username))
{ // this user already exists
DatabaseException de = new DatabaseException(UserManagerObject.class,"UserMessages","user.exists");
de.setParameter(0,username);
throw de;
} // end if
DynamoIDKey key = new DynamoIDKey(username);
if (!(key.isValid(MAX_USERNAME)))
{ // the user ID is invalid...
DatabaseException de = new DatabaseException(UserManagerObject.class,"UserMessages","user.badID");
de.setParameter(0,username);
throw de;
} // end if
rc = null;
synchronized (m_users_sync)
{ // see if the user is in our cache already
IDNameCacheObject cobj = (IDNameCacheObject)(m_name_to_user.get(key));
if (cobj!=null)
{ // it's in the cache - we're going to fail this operation. But while we're here, if the
// actual user object has been kicked out, expunge the reference.
if (cobj.get()==null)
{ // the UserObject got kicked out! kick it out of the HashMaps
m_id_to_user.remove(cobj.getIDKey());
m_name_to_user.remove(key);
cobj.clear();
cobj = null;
} // end if
// throw the exception saying that we exist
DatabaseException de = new DatabaseException(UserManagerObject.class,"UserMessages","user.exists");
de.setParameter(0,username);
throw de;
} // end if
// OK, at this point, we can't be any surer the user doesn't already exist without
// hitting the database. So create it. (createNewUser will throw a DatabaseException if the
// user already exists.)
Map data = m_ops.createNewUser(username,email);
UserObject uobj = new UserObject(data,false,m_ops.getObjectOps(),m_ns_cache,m_srm,this,m_post,m_adapter);
rc = uobj;
cobj = new IDNameCacheObject(uobj.getUID(),key,uobj,m_rq);
m_id_to_user.put(cobj.getIDKey(),cobj);
m_name_to_user.put(cobj.getNameKey(),cobj);
} // end synchronized block
return rc; // new user created!
} // end createUser
public DynamoGroup getGroup(int id) throws DatabaseException
{
DynamoGroup rc = null;
Integer key = new Integer(id);
synchronized (m_groups_sync)
{ // try to retrieve the group
IDNameCacheObject cobj = (IDNameCacheObject)(m_id_to_group.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the group value
rc = (DynamoGroup)(cobj.get());
if (rc==null)
{ // the GroupObject got kicked out! kick it out of the HashMaps
m_id_to_group.remove(key);
m_name_to_group.remove(cobj.getNameKey());
cobj.clear();
cobj = null;
} // end if
} // end if
if (rc==null)
{ // OK, we have to go to the database to find the group
Map data = m_ops.getGroupData(id);
if (data!=null)
{ // create GroupObject and add it to our cache maps
GroupObject gobj = new GroupObject(data,m_ops.getGroupOps(),m_ns_cache,m_srm,this);
rc = gobj;
cobj = new IDNameCacheObject(key,gobj.getName(),gobj,m_group_rq);
m_id_to_group.put(cobj.getIDKey(),cobj);
m_name_to_group.put(cobj.getNameKey(),cobj);
} // end if
// else group does not exist - return null
} // end if
} // end synchronized block
return rc;
} // end getGroup
public DynamoGroup getGroup(String groupname) throws DatabaseException
{
DynamoGroup rc = null;
DynamoIDKey key = new DynamoIDKey(groupname);
synchronized (m_groups_sync)
{ // try to retrieve the group
IDNameCacheObject cobj = (IDNameCacheObject)(m_name_to_group.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the group value
rc = (DynamoGroup)(cobj.get());
if (rc==null)
{ // the GroupObject got kicked out! kick it out of the HashMaps
m_id_to_group.remove(cobj.getIDKey());
m_name_to_group.remove(key);
cobj.clear();
cobj = null;
} // end if
} // end if
if (rc==null)
{ // OK, we have to go to the database to find the group
Map data = m_ops.getGroupData(groupname);
if (data!=null)
{ // create group object and add it to our cache maps
GroupObject gobj = new GroupObject(data,m_ops.getGroupOps(),m_ns_cache,m_srm,this);
rc = gobj;
cobj = new IDNameCacheObject(gobj.getGID(),key,gobj,m_group_rq);
m_id_to_group.put(cobj.getIDKey(),cobj);
m_name_to_group.put(cobj.getNameKey(),cobj);
} // end if
// else group does not exist - return null
} // end if
} // end synchronized block
return rc;
} // end getGroup
public DynamoGroup createGroup(String groupname) throws DatabaseException
{
DynamoIDKey key = new DynamoIDKey(groupname);
if (!(key.isValid(MAX_GROUPNAME)))
{ // the group ID is invalid...
DatabaseException de = new DatabaseException(UserManagerObject.class,"UserMessages","group.badID");
de.setParameter(0,groupname);
throw de;
} // end if
DynamoGroup rc = null;
synchronized (m_groups_sync)
{ // see if the group is in our cache already
IDNameCacheObject cobj = (IDNameCacheObject)(m_name_to_group.get(key));
if (cobj!=null)
{ // it's in the cache - we're going to fail this operation. But while we're here, if the
// actual group object has been kicked out, expunge the reference.
if (cobj.get()==null)
{ // the GroupObject got kicked out! kick it out of the HashMaps
m_id_to_group.remove(cobj.getIDKey());
m_name_to_group.remove(key);
cobj.clear();
cobj = null;
} // end if
// throw the exception saying that we exist
DatabaseException de = new DatabaseException(UserManagerObject.class,"UserMessages","group.exists");
de.setParameter(0,groupname);
throw de;
} // end if
// OK, at this point, we can't be any surer the group doesn't already exist without
// hitting the database. So create it. (createNewGroup will throw a DatabaseException if the
// group already exists.)
Map data = m_ops.createNewGroup(groupname);
GroupObject gobj = new GroupObject(data,m_ops.getGroupOps(),m_ns_cache,m_srm,this);
rc = gobj;
cobj = new IDNameCacheObject(gobj.getGID(),key,gobj,m_group_rq);
m_id_to_group.put(cobj.getIDKey(),cobj);
m_name_to_group.put(cobj.getNameKey(),cobj);
} // end synchronized block
return rc; // new group created!
} // end createNewGroup
public void loadUserDefaults(DynamoUser user, Collection namespaces) throws DatabaseException
{
// Start by translating all the namespaces to namespace IDs.
int[] nsids = new int[namespaces.size()];
int i = 0;
Iterator it = namespaces.iterator();
while (it.hasNext())
nsids[i++] = m_ns_cache.namespaceNameToId(it.next().toString());
// Now feed it into the database operations.
m_ops.loadUserDefaults(user.getUID(),nsids);
} // end loadUserDefaults
/*--------------------------------------------------------------------------------
* Implementations from interface UserProxyManagement
*--------------------------------------------------------------------------------
*/
public DynamoUser getUserProxy(int uid)
{
synchronized (m_anon_user_sync)
{ // get the anonymous user, if it's there and matches
if ((m_anon_user!=null) && (m_anon_user.getUID()==uid))
return m_anon_user;
} // end synchronized block
Integer key = new Integer(uid);
synchronized (m_users_sync)
{ // try to retrieve the user
IDNameCacheObject cobj = (IDNameCacheObject)(m_id_to_user.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the user value
DynamoUser rc = (DynamoUser)(cobj.get());
if (rc==null)
{ // the UserObject got kicked out! kick it out of the HashMaps
m_id_to_user.remove(key);
m_name_to_user.remove(cobj.getNameKey());
rc = new MyUserProxy(uid,cobj.getNameKey().toString());
cobj.clear();
cobj = null;
} // end if
return rc;
} // end if
return new MyUserProxy(uid); // just return a proxy object
} // end synchronized block
} // end getUserProxy
public DynamoUser getUserProxy(int uid, String username)
{
synchronized (m_anon_user_sync)
{ // get the anonymous user, if it's there and matches
if ((m_anon_user!=null) && (m_anon_user.getUID()==uid))
return m_anon_user;
} // end synchronized block
Integer key = new Integer(uid);
synchronized (m_users_sync)
{ // try to retrieve the user
IDNameCacheObject cobj = (IDNameCacheObject)(m_id_to_user.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the user value
DynamoUser rc = (DynamoUser)(cobj.get());
if (rc==null)
{ // the UserObject got kicked out! kick it out of the HashMaps
m_id_to_user.remove(key);
m_name_to_user.remove(cobj.getNameKey());
rc = new MyUserProxy(uid,cobj.getNameKey().toString());
cobj.clear();
cobj = null;
} // end if
return rc;
} // end if
return new MyUserProxy(uid,username); // just return a proxy object
} // end synchronized block
} // end getUserProxy
public DynamoGroup getGroupProxy(int gid)
{
Integer key = new Integer(gid);
synchronized (m_groups_sync)
{ // try to retrieve the group
IDNameCacheObject cobj = (IDNameCacheObject)(m_id_to_group.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the group value
DynamoGroup rc = (DynamoGroup)(cobj.get());
if (rc==null)
{ // the GroupObject got kicked out! kick it out of the HashMaps
m_id_to_group.remove(key);
m_name_to_group.remove(cobj.getNameKey());
rc = new MyGroupProxy(gid,cobj.getNameKey().toString());
cobj.clear();
cobj = null;
} // end if
return rc;
} // end if
return new MyGroupProxy(gid); // just return a proxy object
} // end synchronized block
} // end getGroupProxy
public DynamoGroup getGroupProxy(int gid, String groupname)
{
Integer key = new Integer(gid);
synchronized (m_groups_sync)
{ // try to retrieve the group
IDNameCacheObject cobj = (IDNameCacheObject)(m_id_to_group.get(key));
if (cobj!=null)
{ // got a cache object - retrieve the group value
DynamoGroup rc = (DynamoGroup)(cobj.get());
if (rc==null)
{ // the GroupObject got kicked out! kick it out of the HashMaps
m_id_to_group.remove(key);
m_name_to_group.remove(cobj.getNameKey());
rc = new MyGroupProxy(gid,cobj.getNameKey().toString());
cobj.clear();
cobj = null;
} // end if
return rc;
} // end if
return new MyGroupProxy(gid,groupname); // just return a proxy object
} // end synchronized block
} // end getGroupProxy
/*--------------------------------------------------------------------------------
* Implementations from interface AuthenticatorLookup
*--------------------------------------------------------------------------------
*/
public Authenticator findAuthenticator(String method_namespace, String method)
{
return (Authenticator)(m_authenticators.get(new QualifiedNameKey(method_namespace,method)));
} // end findAuthenticator
/*--------------------------------------------------------------------------------
* Implementations from interface AuthenticatorRegistration
*--------------------------------------------------------------------------------
*/
public ComponentShutdown registerAuthenticator(String method_namespace, String method, Authenticator auth)
throws ConfigException
{
QualifiedNameKey key = new QualifiedNameKey(method_namespace,method);
if (m_authenticators.containsKey(key))
{ // dump out here
ConfigException ce = new ConfigException(UserManagerObject.class,"DatabaseMessages","auth.register");
ce.setParameter(0,method_namespace);
ce.setParameter(1,method);
throw ce;
} // end if
m_authenticators.put(key,auth);
return new ShutdownHashtableRemove(m_authenticators,key);
} // end registerAuthenticator
/*--------------------------------------------------------------------------------
* Implementations from interface UserPropertyTranslatorInstall
*--------------------------------------------------------------------------------
*/
public void installUserPropertyTranslator(UserPropertyTranslator upt)
{
m_adapter.setTranslator(upt);
} // end installUserPropertyTranslator
} // end class UserManagerObject

View File

@@ -0,0 +1,102 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
abstract class UserManagerOps extends OpsBase
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
static final String HMKEY_UID = "uid";
static final String HMKEY_USERNAME = "username";
static final String HMKEY_EMAIL = "email";
static final String HMKEY_LOCKED = "locked";
static final String HMKEY_NOSPAM = "nospam";
static final String HMKEY_CREATED = "created";
static final String HMKEY_LAST_ACCESS = "last_accessed";
static final String HMKEY_GID = "gid";
static final String HMKEY_GROUPNAME = "groupname";
static final String HMKEY_GACLID = "gaclid";
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected UserManagerOps(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class OpsBase
*--------------------------------------------------------------------------------
*/
public void dispose()
{
super.dispose();
} // end dispose
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
abstract UserObjectOps getObjectOps();
abstract GroupObjectOps getGroupOps();
abstract Map getAnonymousUserData() throws DatabaseException;
abstract Map getUserData(int id) throws DatabaseException;
abstract Map getUserData(String username) throws DatabaseException;
abstract Map createNewUser(String username, String email) throws DatabaseException;
abstract Map getGroupData(int id) throws DatabaseException;
abstract Map getGroupData(String groupname) throws DatabaseException;
abstract Map createNewGroup(String groupname) throws DatabaseException;
abstract void loadUserDefaults(int uid, int[] nsids) throws DatabaseException;
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
static UserManagerOps get(DBConnectionPool pool) throws ConfigException
{
return (UserManagerOps)get(pool,UserManagerOps.class.getClassLoader(),
UserManagerOps.class.getName() + "_","UserManagerOps");
} // end get
} // end class UserManagerOps

View File

@@ -0,0 +1,463 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
public class UserManagerOps_mysql extends UserManagerOps
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final Integer GACLID_NONE = new Integer(-1);
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DBUtilities m_utils; // reference to utilities object
private UserObjectOps m_obj_ops = null; // object operations object
private GroupObjectOps m_group_ops = null; // group operations object
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public UserManagerOps_mysql(DBConnectionPool pool)
{
super(pool);
m_utils = (DBUtilities)(pool.queryService(DBUtilities.class));
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class UserManagerOps
*--------------------------------------------------------------------------------
*/
synchronized UserObjectOps getObjectOps()
{
if (m_obj_ops==null)
m_obj_ops = new UserObjectOps_mysql(getPool(),m_utils);
return m_obj_ops;
} // end getObjectOps
synchronized GroupObjectOps getGroupOps()
{
if (m_group_ops==null)
m_group_ops = new GroupObjectOps_mysql(getPool(),m_utils);
return m_group_ops;
} // end getGroupOps
Map getAnonymousUserData() throws DatabaseException
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{ // get a connection and statement
conn = getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT uid, username, email, created, last_accessed FROM users "
+ "WHERE is_anon = 1;");
if (!(rs.next()))
return null; // no anonymous user info (will throw exception later)
// Create and return the Map containing the user data.
HashMap rc = new HashMap();
rc.put(HMKEY_UID,new Integer(rs.getInt(1)));
rc.put(HMKEY_USERNAME,rs.getString(2));
rc.put(HMKEY_EMAIL,rs.getString(3));
rc.put(HMKEY_LOCKED,Boolean.FALSE);
rc.put(HMKEY_NOSPAM,Boolean.TRUE);
rc.put(HMKEY_CREATED,m_utils.getDateTime(rs,4));
java.util.Date lacc = m_utils.getDateTime(rs,5);
if (lacc!=null)
rc.put(HMKEY_LAST_ACCESS,lacc);
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getAnonymousUserData
Map getUserData(int id) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the statement to get the user data
stmt = conn.prepareStatement("SELECT username, email, locked, nospam, created, last_accessed FROM users "
+ "WHERE uid = ? AND is_anon = 0;");
stmt.setInt(1,id);
rs = stmt.executeQuery();
if (!(rs.next()))
return null; // no user info
// Create and return the Map containing the user data.
HashMap rc = new HashMap();
rc.put(HMKEY_UID,new Integer(id));
rc.put(HMKEY_USERNAME,rs.getString(1));
rc.put(HMKEY_EMAIL,rs.getString(2));
rc.put(HMKEY_LOCKED,Boolean.valueOf(rs.getBoolean(3)));
rc.put(HMKEY_NOSPAM,Boolean.valueOf(rs.getBoolean(4)));
rc.put(HMKEY_CREATED,m_utils.getDateTime(rs,5));
java.util.Date lacc = m_utils.getDateTime(rs,6);
if (lacc!=null)
rc.put(HMKEY_LAST_ACCESS,lacc);
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getUserData
Map getUserData(String username) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the statement to get the user data
stmt = conn.prepareStatement("SELECT uid, email, locked, nospam, created, last_accessed FROM users "
+ "WHERE username = ? AND is_anon = 0;");
stmt.setString(1,username);
rs = stmt.executeQuery();
if (!(rs.next()))
return null; // no user info
// Create and return the Map containing the user data.
HashMap rc = new HashMap();
rc.put(HMKEY_UID,new Integer(rs.getInt(1)));
rc.put(HMKEY_USERNAME,username);
rc.put(HMKEY_EMAIL,rs.getString(2));
rc.put(HMKEY_LOCKED,Boolean.valueOf(rs.getBoolean(3)));
rc.put(HMKEY_NOSPAM,Boolean.valueOf(rs.getBoolean(4)));
rc.put(HMKEY_CREATED,m_utils.getDateTime(rs,5));
java.util.Date lacc = m_utils.getDateTime(rs,6);
if (lacc!=null)
rc.put(HMKEY_LAST_ACCESS,lacc);
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getUserData
Map createNewUser(String username, String email) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the users table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES users WRITE;");
// see if the user already exists
stmt = conn.prepareStatement("SELECT uid FROM users WHERE username = ?;");
stmt.setString(1,username);
rs = stmt.executeQuery();
if (rs.next())
{ // user exists - our operation is blown
DatabaseException de = new DatabaseException(UserManagerOps_mysql.class,"UserMessages","user.exists");
de.setParameter(0,username);
throw de;
} // end if
// close down previous statement in prep for next one
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
// insert the new user record!
stmt = conn.prepareStatement("INSERT INTO users (username, email, created) VALUES (?, ?, ?);");
stmt.setString(1,username);
stmt.setString(2,email);
java.util.Date created = new java.util.Date();
m_utils.setDateTime(stmt,3,created);
stmt.executeUpdate();
// Generate the return Map, suitable for creating a new object.
HashMap rc = new HashMap();
rc.put(HMKEY_UID,new Integer(MySQLUtils.getLastInsertInt(conn)));
rc.put(HMKEY_USERNAME,username);
rc.put(HMKEY_EMAIL,email);
rc.put(HMKEY_LOCKED,Boolean.FALSE);
rc.put(HMKEY_NOSPAM,Boolean.FALSE);
rc.put(HMKEY_CREATED,created);
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end createNewUser
Map getGroupData(int id) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the statement to get the group data
stmt = conn.prepareStatement("SELECT groupname, gaclid FROM groups WHERE gid = ?;");
stmt.setInt(1,id);
rs = stmt.executeQuery();
if (!(rs.next()))
return null; // no group info
// Create and return the Map containing the group data.
HashMap rc = new HashMap();
rc.put(HMKEY_GID,new Integer(id));
rc.put(HMKEY_GROUPNAME,rs.getString(1));
rc.put(HMKEY_GACLID,new Integer(rs.getInt(2)));
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getGroupData
Map getGroupData(String groupname) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the statement to get the group data
stmt = conn.prepareStatement("SELECT gid, gaclid FROM groups WHERE groupname = ?;");
stmt.setString(1,groupname);
rs = stmt.executeQuery();
if (!(rs.next()))
return null; // no group info
// Create and return the Map containing the group data.
HashMap rc = new HashMap();
rc.put(HMKEY_GID,new Integer(rs.getInt(1)));
rc.put(HMKEY_GROUPNAME,groupname);
rc.put(HMKEY_GACLID,new Integer(rs.getInt(2)));
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getGroupData
Map createNewGroup(String groupname) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the groups table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES groups WRITE;");
// see if the group already exists
stmt = conn.prepareStatement("SELECT gid FROM groups WHERE groupname = ?;");
stmt.setString(1,groupname);
rs = stmt.executeQuery();
if (rs.next())
{ // group exists - our operation is blown
DatabaseException de = new DatabaseException(UserManagerOps_mysql.class,"UserMessages","group.exists");
de.setParameter(0,groupname);
throw de;
} // end if
// close down previous statement in prep for next one
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
// insert the new group record!
stmt = conn.prepareStatement("INSERT INTO groups (groupname) VALUES (?);");
stmt.setString(1,groupname);
stmt.executeUpdate();
// Generate the return Map, suitable for creating a new object.
HashMap rc = new HashMap();
rc.put(HMKEY_GID,new Integer(MySQLUtils.getLastInsertInt(conn)));
rc.put(HMKEY_GROUPNAME,groupname);
rc.put(HMKEY_GACLID,GACLID_NONE);
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end createNewGroup
void loadUserDefaults(int uid, int[] nsids) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt_insert = null;
Statement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the global and user properties tables
stmt = conn.createStatement();
stmt.executeUpdate("LOCK TABLES userprop WRITE, globalprop READ;");
// prepare the fancy insert statement
stmt_insert = conn.prepareStatement("INSERT INTO userprop (uid, nsid, prop_name, prop_value) "
+ "SELECT ?, globalprop.nsid, globalprop.prop_name, "
+ "globalprop.prop_value FROM globalprop "
+ "WHERE globalprop.nsid = ?;");
for (int i=0; i<nsids.length; i++)
{ // execute each statement in turn to insert each namespace's default values
stmt_insert.setInt(1,uid);
stmt_insert.setInt(2,nsids[i]);
stmt_insert.executeUpdate();
} // end for
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt_insert);
SQLUtils.shutdown(conn);
} // end finally
} // end loadUserDefaults
} // end class UserManagerOps_mysql

View File

@@ -0,0 +1,22 @@
# 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# ---------------------------------------------------------------------------------
# This file has been localized for the en_US locale
anon.notFound=Internal Error: Unable to load information for the anonymous user.
user.exists=User "{0}" already exists in the database.
user.badID=The user name "{0}" is not valid.
group.exists=Group "{0}" already exists in the database.
group.badID=The group name "{0}" is not valid.

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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import org.apache.commons.collections.*;
import com.silverwrist.dynamo.UserInfoNamespace;
import com.silverwrist.dynamo.event.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.security.SecurityReferenceMonitor;
import com.silverwrist.dynamo.util.*;
class UserObject implements DynamoUser, UserInfoNamespace
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private UserObjectOps m_ops; // operations object
private NamespaceCache m_ns_cache; // namespace cache object
private SecurityReferenceMonitor m_srm; // security reference monitor
private AuthenticatorLookup m_auth_lookup; // authenticator lookup
private PostDynamicUpdate m_post; // where we post dynamic events
private UserPropertyTranslator m_upt;
private int m_uid; // user ID
private String m_username; // user name
private String m_email; // E-mail address
private java.util.Date m_created; // created date
private java.util.Date m_last_accessed; // last access date
private boolean m_anonymous; // is this the anonymous user?
private boolean m_locked; // is user locked?
private boolean m_nospam; // user "no-spam" flag
private ReferenceMap m_properties; // cached property values
private Object m_properties_sync = new Object(); // synchronization for above
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
UserObject(Map data, boolean anonymous, UserObjectOps ops, NamespaceCache ns_cache,
SecurityReferenceMonitor srm, AuthenticatorLookup auth_lookup, PostDynamicUpdate post,
UserPropertyTranslator upt)
{
m_ops = ops;
m_ns_cache = ns_cache;
m_srm = srm;
m_auth_lookup = auth_lookup;
m_post = post;
m_upt = upt;
m_uid = ((Integer)(data.get(UserManagerOps.HMKEY_UID))).intValue();
m_username = (String)(data.get(UserManagerOps.HMKEY_USERNAME));
m_email = (String)(data.get(UserManagerOps.HMKEY_EMAIL));
m_created = (java.util.Date)(data.get(UserManagerOps.HMKEY_CREATED));
m_last_accessed = (java.util.Date)(data.get(UserManagerOps.HMKEY_LAST_ACCESS));
m_anonymous = anonymous;
m_locked = ((Boolean)(data.get(UserManagerOps.HMKEY_LOCKED))).booleanValue();
m_nospam = ((Boolean)(data.get(UserManagerOps.HMKEY_NOSPAM))).booleanValue();
m_properties = new ReferenceMap(ReferenceMap.HARD,ReferenceMap.SOFT);
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private final void testChangeOK(DynamoUser caller) throws DatabaseException, DynamoSecurityException
{
if (equals(caller))
return; // a user can always change their OWN information
if (caller.equals(m_srm.getAdminUser()))
return; // Administrator can do anything
if (m_srm.getGlobalAcl().testPermission(caller,NAMESPACE,PERM_EDIT_ALL))
return; // and so can anyone else with "edit all" permission on the global ACL
// Presume the change is forbidden - throw the exception
DynamoSecurityException dse = new DynamoSecurityException(UserObject.class,"DatabaseMessages",
"sec.changeUser");
dse.setParameter(0,m_username);
throw dse;
} // end testChangeOK
/*--------------------------------------------------------------------------------
* Implementations from interface Principal
*--------------------------------------------------------------------------------
*/
public boolean equals(Object another)
{
if (another==null)
return false;
if (another instanceof DynamoUser)
return (m_uid==((DynamoUser)another).getUID());
return false;
} // end equals
public String toString()
{
return "user " + m_username;
} // end toString
public int hashCode()
{
return m_uid;
} // end hashCode
public String getName()
{
return m_username;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectProvider
*--------------------------------------------------------------------------------
*/
/**
* Retrieves an object from this <CODE>ObjectProvider</CODE>.
*
* @param namespace The namespace to interpret the name relative to.
* @param name The name of the object to be retrieved.
* @return The object reference specified.
*/
public Object getObject(String namespace, String name)
{
if (NAMESPACE.equals(namespace))
{ // handle user info namespace specially
if (ATTR_FULLNAME.equals(name))
return m_upt.getUserFullName(this);
else if (ATTR_EMAIL_ADDRESS.equals(name))
return m_email;
else if (ATTR_ID.equals(name))
return new Integer(m_uid);
else if (ATTR_USERNAME.equals(name))
return m_username;
else
throw new NoSuchObjectException(this.toString(),namespace,name);
} // end if
try
{ // convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
Object rc = null;
synchronized (m_properties_sync)
{ // start by looking in the properties map
rc = m_properties.get(key);
if (rc==null)
{ // no use - need to try the database
rc = m_ops.getProperty(m_uid,key);
if (rc!=null)
m_properties.put(key,rc);
} // end if
} // end synchronized block
if (rc==null)
throw new NoSuchObjectException(this.toString(),namespace,name);
return rc;
} // end try
catch (DatabaseException e)
{ // translate into our NoSuchObjectException but retain the DatabaseException
throw new NoSuchObjectException(this.toString(),namespace,name,e);
} // end catch
} // end getObject
/*--------------------------------------------------------------------------------
* Implementations from interface SecureObjectStore
*--------------------------------------------------------------------------------
*/
public Object setObject(DynamoUser caller, String namespace, String name, Object value)
throws DatabaseException, DynamoSecurityException
{
if (NAMESPACE.equals(namespace))
{ // can't set more data in restricted namespace
ObjectStoreException ose = new ObjectStoreException(UserObject.class,"DatabaseMessages",
"ose.setProperty");
ose.setParameter(0,namespace);
ose.setParameter(1,name);
throw ose;
} // end if
testChangeOK(caller);
Object rc = null;
// convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
synchronized (m_properties_sync)
{ // start by setting the database value
rc = m_ops.setProperty(m_uid,key,value);
// and cache it, too
m_properties.put(key,value);
} // end synchronized block
m_post.postUpdate(new UserPropertyUpdateEvent(this,m_uid,namespace,name));
return rc;
} // end setObject
public Object removeObject(DynamoUser caller, String namespace, String name)
throws DatabaseException, DynamoSecurityException
{
if (NAMESPACE.equals(namespace))
{ // can't set more data in restricted namespace
ObjectStoreException ose = new ObjectStoreException(UserObject.class,"DatabaseMessages",
"ose.removeProperty");
ose.setParameter(0,namespace);
ose.setParameter(1,name);
throw ose;
} // end if
testChangeOK(caller);
Object rc = null;
// convert the namespace name to an ID here
PropertyKey key = new PropertyKey(m_ns_cache.namespaceNameToId(namespace),name);
synchronized (m_properties_sync)
{ // start by killing the database value
rc = m_ops.removeProperty(m_uid,key);
// and remove the cached value, too
m_properties.remove(key);
} // end synchronized block
m_post.postUpdate(new UserPropertyUpdateEvent(this,m_uid,namespace,name));
return rc;
} // end removeObject
public Collection getNamespaces() throws DatabaseException
{
// call through to the database to get the list of namespace IDs
int[] ids = m_ops.getPropertyNamespaceIDs(m_uid);
ArrayList rc = new ArrayList(ids.length);
for (int i=0; i<ids.length; i++)
rc.add(m_ns_cache.namespaceIdToName(ids[i]));
rc.add(NAMESPACE);
return Collections.unmodifiableList(rc);
} // end getNamespaces
public Collection getNamesForNamespace(String namespace) throws DatabaseException
{
if (NAMESPACE.equals(namespace))
{ // return the "static" attribute names
ArrayList rc = new ArrayList();
rc.add(ATTR_FULLNAME);
rc.add(ATTR_EMAIL_ADDRESS);
rc.add(ATTR_ID);
rc.add(ATTR_USERNAME);
return Collections.unmodifiableList(rc);
} // end if
// call through to the database to get the data for this namespace
int nsid = m_ns_cache.namespaceNameToId(namespace);
Map data = m_ops.getAllProperties(m_uid,nsid);
// we both create the return value and cache the data values
ArrayList rc = new ArrayList(data.size());
synchronized (m_properties_sync)
{ // do the transfer...
Iterator it = data.entrySet().iterator();
while (it.hasNext())
{ // copy one entry at a time
Map.Entry ntry = (Map.Entry)(it.next());
rc.add(ntry.getKey().toString());
m_properties.put(new PropertyKey(nsid,ntry.getKey().toString()),ntry.getValue());
} // end while
} // end synchronized block
return Collections.unmodifiableList(rc);
} // end getNamesForNamespace
/*--------------------------------------------------------------------------------
* Implementations from interface DynamoUser
*--------------------------------------------------------------------------------
*/
public int getUID()
{
return m_uid;
} // end getUID
public boolean isAnonymous()
{
return m_anonymous;
} // end isAnonymous
public boolean isLocked()
{
return m_locked;
} // end isLocked
public void setLocked(DynamoUser caller, boolean locked) throws DatabaseException, DynamoSecurityException
{
testChangeOK(caller);
if (m_anonymous)
return; // cannot change lock status for anonymous user
if (m_locked!=locked)
{ // call through to set the flag
m_ops.setLocked(m_uid,locked);
m_locked = locked;
} // end if
} // end setLocked
public boolean isNoSpam()
{
return m_nospam;
} // end isNoSpam
public void setNoSpam(DynamoUser caller, boolean nospam) throws DatabaseException, DynamoSecurityException
{
testChangeOK(caller);
if (m_anonymous)
return; // cannot change nospam status for anonymous user
if (m_nospam!=nospam)
{ // call through to set the flag
m_ops.setNoSpam(m_uid,nospam);
m_nospam = nospam;
} // end if
} // end setNoSpam
public String getEMailAddress()
{
return m_email;
} // end getEMailAddress
public boolean setEMailAddress(DynamoUser caller, String addr)
throws DatabaseException, DynamoSecurityException
{
testChangeOK(caller);
if (m_anonymous)
return false; // cannot change E-mail address for anonymous user
if (m_email.equals(addr))
return false; // no change necessary
m_ops.setEMailAddress(m_uid,addr);
m_email = addr;
return true;
} // end setEMailAddress
public boolean authenticate(String method_namespace, String method, String source_data, String auth_data)
throws DatabaseException, AuthenticationException
{
if (m_anonymous)
return false; // anonymous user cannot authenticate
// Get the authenticator that handles these requests.
Authenticator auth = m_auth_lookup.findAuthenticator(method_namespace,method);
if (auth==null)
{ // the authenticator could not be found - bail out
AuthenticationException ae = new AuthenticationException(UserObject.class,"DatabaseMessages",
"auth.notFound");
ae.setParameter(0,method_namespace);
ae.setParameter(1,method);
throw ae;
} // end if
// Retrieve the authentication data from the database.
String[] stored_data = m_ops.getAuthenticationData(m_uid,m_ns_cache.namespaceNameToId(method_namespace),
method,source_data);
if (stored_data==null)
{ // user has no data for this authentication method
AuthenticationException ae = new AuthenticationException(UserObject.class,"DatabaseMessages",
"auth.noUserData");
ae.setParameter(0,method_namespace);
ae.setParameter(1,method);
throw ae;
} // end if
// Now try the authentication.
AuthenticationException ae = null;
boolean rc = false;
for (int i=0; !rc && (i<stored_data.length); i++)
{ // try the various authentication stored data
try
{ // call authentication data...
rc = auth.authenticate(stored_data[i],auth_data);
} // end try
catch (AuthenticationException e)
{ // save the exception
ae = e;
} // end catch
} // end for
if (rc)
return true;
if (ae!=null)
throw ae;
return false;
} // end authenticate
public void setAuthenticationData(DynamoUser caller, String method_namespace, String method,
String source_data, String auth_data)
throws DatabaseException, AuthenticationException, DynamoSecurityException
{
testChangeOK(caller);
if (m_anonymous)
return; // cannot change authentication data for anonymous user
// Get the authenticator that handles these requests.
Authenticator auth = m_auth_lookup.findAuthenticator(method_namespace,method);
if (auth==null)
{ // the authenticator could not be found - bail out
AuthenticationException ae = new AuthenticationException(UserObject.class,"DatabaseMessages",
"auth.notFound");
ae.setParameter(0,method_namespace);
ae.setParameter(1,method);
throw ae;
} // end if
// Call down to set the authentication data.
m_ops.putAuthenticationData(m_uid,m_ns_cache.namespaceNameToId(method_namespace),method,source_data,
auth.processInputData(auth_data));
} // end setAuthenticationData
public void clearAuthenticationData(DynamoUser caller, String method_namespace, String method,
String source_data) throws DatabaseException, DynamoSecurityException
{
testChangeOK(caller);
if (m_anonymous)
return; // cannot change authentication data for anonymous user
// Call down to clear the authentication data.
m_ops.clearAuthenticationData(m_uid,m_ns_cache.namespaceNameToId(method_namespace),method,source_data);
} // end clearAuthenticationData
public void clearAuthenticationData(DynamoUser caller, String method_namespace, String method)
throws DatabaseException, DynamoSecurityException
{
testChangeOK(caller);
if (m_anonymous)
return; // cannot change authentication data for anonymous user
// Call down to clear the authentication data.
m_ops.clearAuthenticationData(m_uid,m_ns_cache.namespaceNameToId(method_namespace),method,null);
} // end clearAuthenticationData
public java.util.Date getCreationDate()
{
return m_created;
} // end getCreationDate
public java.util.Date getLastAccessDate()
{
return m_last_accessed;
} // end getLastAccessDate
public synchronized void setLastAccessDate(DynamoUser caller, java.util.Date date)
throws DatabaseException, DynamoSecurityException
{
testChangeOK(caller);
m_ops.setLastAccessed(m_uid,date);
m_last_accessed = date;
} // end setLastAccessDate
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
void updated(UserUpdateEvent evt)
{
} // end updated
} // end class UserObject

View File

@@ -0,0 +1,70 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.util.*;
abstract class UserObjectOps extends OpsBase
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
protected UserObjectOps(DBConnectionPool pool)
{
super(pool);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
abstract Object getProperty(int uid, PropertyKey key) throws DatabaseException;
abstract Object setProperty(int uid, PropertyKey key, Object value) throws DatabaseException;
abstract Object removeProperty(int uid, PropertyKey key) throws DatabaseException;
abstract int[] getPropertyNamespaceIDs(int uid) throws DatabaseException;
abstract Map getAllProperties(int uid, int namespace) throws DatabaseException;
abstract void setLocked(int uid, boolean locked) throws DatabaseException;
abstract void setNoSpam(int uid, boolean locked) throws DatabaseException;
abstract void setEMailAddress(int uid, String addr) throws DatabaseException;
abstract void setLastAccessed(int uid, java.util.Date date) throws DatabaseException;
abstract String[] getAuthenticationData(int uid, int nsid, String method, String source_data)
throws DatabaseException;
abstract void putAuthenticationData(int uid, int nsid, String method, String source_data, String auth_data)
throws DatabaseException;
abstract void clearAuthenticationData(int uid, int nsid, String method, String source_data)
throws DatabaseException;
} // end class UserObjectOps

View File

@@ -0,0 +1,635 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class UserObjectOps_mysql extends UserObjectOps
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String[] STRING_TEMPLATE = new String[0];
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DBUtilities m_utils;
private PropertySerializer m_psz;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
UserObjectOps_mysql(DBConnectionPool pool, DBUtilities utils)
{
super(pool);
m_utils = utils;
m_psz = (PropertySerializer)(pool.queryService(PropertySerializer.class));
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class UserObjectOps
*--------------------------------------------------------------------------------
*/
Object getProperty(int uid, PropertyKey key) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String rc_str = null;
try
{ // get a connection
conn = getConnection();
// look up the property
stmt = conn.prepareStatement("SELECT prop_value FROM userprop WHERE uid = ? AND nsid = ? "
+ "AND prop_name = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
rs = stmt.executeQuery();
if (!(rs.next()))
return null; // property not found
rc_str = rs.getString(1);
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(rc_str);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end getProperty
Object setProperty(int uid, PropertyKey key, Object value) throws DatabaseException
{
String serialized_value = m_psz.serializeProperty(value);
if (serialized_value==null)
{ // serialization exception - throw it
DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
"property.serialize");
de.setParameter(0,key.getName());
throw de;
} // end if
String old_value = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES userprop WRITE;");
// look to see if the property value is already there
stmt = conn.prepareStatement("SELECT prop_value FROM userprop WHERE uid = ? AND nsid = ? "
+ "AND prop_name = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
rs = stmt.executeQuery();
if (rs.next())
old_value = rs.getString(1);
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
if (old_value!=null)
{ // prepare the statement to update the existing record
stmt = conn.prepareStatement("UPDATE userprop SET prop_value = ? WHERE uid = ? "
+ "AND nsid = ? AND prop_name = ?;");
stmt.setString(1,serialized_value);
stmt.setInt(2,uid);
stmt.setInt(3,key.getNamespaceID());
stmt.setString(4,key.getName());
} // end if
else
{ // prepare the statement to insert a new record
stmt = conn.prepareStatement("INSERT INTO userprop (uid, nsid, prop_name, prop_value) "
+ "VALUES (?, ?, ?, ?);");
stmt.setInt(1,uid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
stmt.setString(4,serialized_value);
} // end else
stmt.executeUpdate(); // execute it!
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
if (old_value==null)
return null; // no previous value
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(old_value);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end setProperty
Object removeProperty(int uid, PropertyKey key) throws DatabaseException
{
String old_value = null;
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES userprop WRITE;");
// look to see if the property value is already there
stmt = conn.prepareStatement("SELECT prop_value FROM userprop WHERE uid = ? AND nsid = ? "
+ "AND prop_name = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
rs = stmt.executeQuery();
if (rs.next())
old_value = rs.getString(1);
else
return null; // no need to remove anything
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
// delete the database row
stmt = conn.prepareStatement("DELETE FROM userprop WHERE uid = ? AND nsid = ? AND prop_name = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,key.getNamespaceID());
stmt.setString(3,key.getName());
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
// Deserialize the property value.
Object rc = m_psz.deserializeProperty(old_value);
if (rc!=null)
return rc;
// deserialization exception - throw it
DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key.getName());
throw de;
} // end removeProperty
int[] getPropertyNamespaceIDs(int uid) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the query!
stmt = conn.prepareStatement("SELECT DISTINCT nsid FROM userprop WHERE uid = ?;");
stmt.setInt(1,uid);
rs = stmt.executeQuery();
// read out a list of the namespace IDs
ArrayList tmp = new ArrayList();
while (rs.next())
tmp.add(new Integer(rs.getInt(1)));
// create and return the array
int[] rc = new int[tmp.size()];
for (int i=0; i<tmp.size(); i++)
rc[i] = ((Integer)(tmp.get(i))).intValue();
tmp.clear();
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getPropertyNamespaceIDs
Map getAllProperties(int uid, int namespace) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the query!
stmt = conn.prepareStatement("SELECT prop_name, prop_value FROM userprop WHERE uid = ? AND nsid = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,namespace);
rs = stmt.executeQuery();
// prepare the return value
HashMap rc = new HashMap();
while (rs.next())
{ // copy data out, deserializing properties as we go
String key = rs.getString(1);
Object value = m_psz.deserializeProperty(rs.getString(2));
if (value==null)
{ // deserialization exception - throw it
DatabaseException de = new DatabaseException(UserObjectOps_mysql.class,"DatabaseMessages",
"property.deserialize");
de.setParameter(0,key);
throw de;
} // end if
rc.put(key,value);
} // end while
return rc;
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getAllProperties
void setLocked(int uid, boolean locked) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
try
{ // get a connection
conn = getConnection();
// run the appropriate SQL update
stmt = conn.prepareStatement("UPDATE users SET locked = ? WHERE uid = ?;");
stmt.setInt(1,(locked ? 1 : 0));
stmt.setInt(2,uid);
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end setLocked
void setNoSpam(int uid, boolean nospam) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
try
{ // get a connection
conn = getConnection();
// run the appropriate SQL update
stmt = conn.prepareStatement("UPDATE users SET nospam = ? WHERE uid = ?;");
stmt.setInt(1,(nospam ? 1 : 0));
stmt.setInt(2,uid);
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end setNoSpam
void setEMailAddress(int uid, String addr) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
try
{ // get a connection
conn = getConnection();
// run the appropriate SQL update
stmt = conn.prepareStatement("UPDATE users SET email = ? WHERE uid = ?;");
stmt.setString(1,addr);
stmt.setInt(2,uid);
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end setEMailAddress
void setLastAccessed(int uid, java.util.Date date) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
try
{ // get a connection
conn = getConnection();
// run the appropriate SQL update
stmt = conn.prepareStatement("UPDATE users SET last_accessed = ? WHERE uid = ?;");
m_utils.setDateTime(stmt,1,date);
stmt.setInt(2,uid);
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end setLastAccessed
String[] getAuthenticationData(int uid, int nsid, String method, String source_data) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// execute the statement!
stmt = conn.prepareStatement("SELECT auth_data FROM userauth WHERE uid = ? AND nsid = ? "
+ "AND method = ? AND source_data = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,nsid);
stmt.setString(3,method);
stmt.setString(4,source_data);
rs = stmt.executeQuery();
if (!(rs.next()))
return null;
// Construct the return value.
ArrayList rc = new ArrayList();
do
{ // append return value
rc.add(rs.getString(1));
} while (rs.next()); // end do
return (String[])(rc.toArray(STRING_TEMPLATE));
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end getAuthenticationData
void putAuthenticationData(int uid, int nsid, String method, String source_data, String auth_data)
throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
Statement stmt2 = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// lock the userauth table
stmt2 = conn.createStatement();
stmt2.executeUpdate("LOCK TABLES userauth WRITE;");
// look for an existing record
stmt = conn.prepareStatement("SELECT uid FROM userauth WHERE uid = ? AND nsid = ? AND method = ? "
+ "AND source_data = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,nsid);
stmt.setString(3,method);
stmt.setString(4,source_data);
rs = stmt.executeQuery();
boolean present = rs.next();
SQLUtils.shutdown(rs);
rs = null;
SQLUtils.shutdown(stmt);
if (present)
{ // execute an update statement
stmt = conn.prepareStatement("UPDATE userauth SET auth_data = ? WHERE uid = ? AND nsid = ? "
+ "AND method = ? AND source_data = ?;");
stmt.setString(1,auth_data);
stmt.setInt(2,uid);
stmt.setInt(3,nsid);
stmt.setString(4,method);
stmt.setString(5,source_data);
} // end if
else
{ // execute an insert statement
stmt = conn.prepareStatement("INSERT INTO userauth (uid, nsid, method, source_data, auth_data) "
+ "VALUES (?, ?, ?, ?, ?);");
stmt.setInt(1,uid);
stmt.setInt(2,nsid);
stmt.setString(3,method);
stmt.setString(4,source_data);
stmt.setString(5,auth_data);
} // end else
stmt.executeUpdate(); // run it!
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
MySQLUtils.unlockTables(conn);
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(stmt2);
SQLUtils.shutdown(conn);
} // end finally
} // end putAuthenticationData
void clearAuthenticationData(int uid, int nsid, String method, String source_data) throws DatabaseException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{ // get a connection
conn = getConnection();
// prepare and run the statement
if (source_data==null)
stmt = conn.prepareStatement("DELETE FROM userauth WHERE uid = ? AND nsid = ? AND method = ?;");
else
stmt = conn.prepareStatement("DELETE FROM userauth WHERE uid = ? AND nsid = ? AND method = ? "
+ "AND source_data = ?;");
stmt.setInt(1,uid);
stmt.setInt(2,nsid);
stmt.setString(3,method);
if (source_data!=null)
stmt.setString(4,source_data);
stmt.executeUpdate();
} // end try
catch (SQLException e)
{ // translate to a general DatabaseException
throw generalException(e);
} // end catch
finally
{ // shut everything down
SQLUtils.shutdown(rs);
SQLUtils.shutdown(stmt);
SQLUtils.shutdown(conn);
} // end finally
} // end clearAuthenticationData
} // end class UserObjectOps_mysql

View File

@@ -0,0 +1,26 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import com.silverwrist.dynamo.iface.DynamoUser;
public interface UserPropertyTranslator
{
public String getUserFullName(DynamoUser user);
} // end interface UserPropertyTranslator

View File

@@ -0,0 +1,24 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
public interface UserPropertyTranslatorInstall
{
public void installUserPropertyTranslator(UserPropertyTranslator upt);
} // end interface UserPropertyTranslatorInstall

View File

@@ -0,0 +1,260 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.util.*;
import com.silverwrist.dynamo.UserInfoNamespace;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
abstract class UserProxy implements DynamoUser, UserInfoNamespace, DynamicWrapper
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
protected int m_uid;
protected String m_username;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
protected UserProxy(int uid)
{
m_uid = uid;
m_username = null;
} // end constructor
protected UserProxy(int uid, String username)
{
m_uid = uid;
m_username = username;
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
protected abstract DynamoUser getRealUser();
/*--------------------------------------------------------------------------------
* Implementations from interface Principal
*--------------------------------------------------------------------------------
*/
public boolean equals(Object another)
{
if (another==null)
return false;
if (another instanceof DynamoUser)
return (m_uid==((DynamoUser)another).getUID());
return false;
} // end equals
public String toString()
{
if (m_username!=null)
return "user " + m_username;
return getRealUser().toString();
} // end toString
public int hashCode()
{
return m_uid;
} // end hashCode
public String getName()
{
if (m_username!=null)
return m_username;
return getRealUser().getName();
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectProvider
*--------------------------------------------------------------------------------
*/
/**
* Retrieves an object from this <CODE>ObjectProvider</CODE>.
*
* @param namespace The namespace to interpret the name relative to.
* @param name The name of the object to be retrieved.
* @return The object reference specified.
*/
public Object getObject(String namespace, String name)
{
return getRealUser().getObject(namespace,name);
} // end getObject
/*--------------------------------------------------------------------------------
* Implementations from interface SecureObjectStore
*--------------------------------------------------------------------------------
*/
public Object setObject(DynamoUser caller, String namespace, String name, Object value)
throws DatabaseException, DynamoSecurityException
{
return getRealUser().setObject(caller,namespace,name,value);
} // end setObject
public Object removeObject(DynamoUser caller, String namespace, String name)
throws DatabaseException, DynamoSecurityException
{
return getRealUser().removeObject(caller,namespace,name);
} // end removeObject
public Collection getNamespaces() throws DatabaseException
{
return getRealUser().getNamespaces();
} // end getNamespaces
public Collection getNamesForNamespace(String namespace) throws DatabaseException
{
return getRealUser().getNamesForNamespace(namespace);
} // end getNamesForNamespace
/*--------------------------------------------------------------------------------
* Implementations from interface DynamoUser
*--------------------------------------------------------------------------------
*/
public int getUID()
{
return m_uid;
} // end getUID
public boolean isAnonymous()
{
return getRealUser().isAnonymous();
} // end isAnonymous
public boolean isLocked()
{
return getRealUser().isLocked();
} // end isLocked
public void setLocked(DynamoUser caller, boolean locked) throws DatabaseException, DynamoSecurityException
{
getRealUser().setLocked(caller,locked);
} // end setLocked
public boolean isNoSpam()
{
return getRealUser().isNoSpam();
} // end isNoSpam
public void setNoSpam(DynamoUser caller, boolean nospam) throws DatabaseException, DynamoSecurityException
{
getRealUser().setNoSpam(caller,nospam);
} // end setNoSpam
public String getEMailAddress()
{
return getRealUser().getEMailAddress();
} // end getEMailAddress
public boolean setEMailAddress(DynamoUser caller, String addr)
throws DatabaseException, DynamoSecurityException
{
return getRealUser().setEMailAddress(caller,addr);
} // end setEMailAddress
public boolean authenticate(String method_namespace, String method, String source_data, String auth_data)
throws DatabaseException, AuthenticationException
{
return getRealUser().authenticate(method_namespace,method,source_data,auth_data);
} // end authenticate
public void setAuthenticationData(DynamoUser caller, String method_namespace, String method,
String source_data, String auth_data)
throws DatabaseException, AuthenticationException, DynamoSecurityException
{
getRealUser().setAuthenticationData(caller,method_namespace,method,source_data,auth_data);
} // end setAuthenticationData
public void clearAuthenticationData(DynamoUser caller, String method_namespace, String method,
String source_data) throws DatabaseException, DynamoSecurityException
{
getRealUser().clearAuthenticationData(caller,method_namespace,method,source_data);
} // end clearAuthenticationData
public void clearAuthenticationData(DynamoUser caller, String method_namespace, String method)
throws DatabaseException, DynamoSecurityException
{
getRealUser().clearAuthenticationData(caller,method_namespace,method);
} // end clearAuthenticationData
public java.util.Date getCreationDate()
{
return getRealUser().getCreationDate();
} // end getCreationDate
public java.util.Date getLastAccessDate()
{
return getRealUser().getLastAccessDate();
} // end getLastAccessDate
public synchronized void setLastAccessDate(DynamoUser caller, java.util.Date date)
throws DatabaseException, DynamoSecurityException
{
getRealUser().setLastAccessDate(caller,date);
} // end setLastAccessDate
/*--------------------------------------------------------------------------------
* Implementations from interface DynamicWrapper
*--------------------------------------------------------------------------------
*/
public Object unwrap()
{
return getRealUser();
} // end unwrap
} // end class UserProxy

View File

@@ -0,0 +1,32 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import com.silverwrist.dynamo.iface.*;
public interface UserProxyManagement
{
public DynamoUser getUserProxy(int uid);
public DynamoUser getUserProxy(int uid, String username);
public DynamoGroup getGroupProxy(int gid);
public DynamoGroup getGroupProxy(int gid, String groupname);
} // end interface UserProxyManagement

View File

@@ -0,0 +1,498 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.db;
import java.sql.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
class WrappedConnection implements Connection
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DBConnectionPool m_datapool;
private Connection m_conn;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
WrappedConnection(DBConnectionPool datapool, Connection conn)
{
m_datapool = datapool;
m_conn = conn;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class Object
*--------------------------------------------------------------------------------
*/
protected void finalize() throws Throwable
{
if (m_conn!=null)
this.close();
super.finalize();
} // end finalize
/*--------------------------------------------------------------------------------
* Implementations from interface Connection
*--------------------------------------------------------------------------------
*/
/**
* Creates a <code>Statement</code> object for sending
* SQL statements to the database.
*
* @return a new Statement object
* @exception SQLException if a database access error occurs
*/
public Statement createStatement() throws SQLException
{
return m_conn.createStatement();
} // end createStatement
/**
* Creates a <code>PreparedStatement</code> object for sending
* parameterized SQL statements to the database.
*
* @param sql a SQL statement that may contain one or more '?' IN parameter placeholders
* @return a new PreparedStatement object containing the pre-compiled statement
* @exception SQLException if a database access error occurs
*/
public PreparedStatement prepareStatement(String sql) throws SQLException
{
return m_conn.prepareStatement(sql);
} // end prepareStatement
/**
* Creates a <code>CallableStatement</code> object for calling
* database stored procedures.
*
* @param sql a SQL statement that may contain one or more '?' parameter placeholders.
* Typically this statement is a JDBC function call escape string.
* @return a new CallableStatement object containing the pre-compiled SQL statement
* @exception SQLException if a database access error occurs
*/
public CallableStatement prepareCall(String sql) throws SQLException
{
return m_conn.prepareCall(sql);
} // end prepareCall
/**
* Converts the given SQL statement into the system's native SQL grammar.
*
* @param sql a SQL statement that may contain one or more '?' parameter placeholders
* @return the native form of this statement
* @exception SQLException if a database access error occurs
*/
public String nativeSQL(String sql) throws SQLException
{
return m_conn.nativeSQL(sql);
} // end nativeSQL
/**
* Sets this connection's auto-commit mode.
*
* @param autoCommit true enables auto-commit; false disables auto-commit.
* @exception SQLException if a database access error occurs
*/
public void setAutoCommit(boolean autoCommit) throws SQLException
{
m_conn.setAutoCommit(autoCommit);
} // end setAutoCommit
/**
* Gets the current auto-commit state.
*
* @return the current state of auto-commit mode
* @exception SQLException if a database access error occurs
* @see #setAutoCommit
*/
public boolean getAutoCommit() throws SQLException
{
return m_conn.getAutoCommit();
} // end getAutoCommit
/**
* Makes all changes made since the previous
* commit/rollback permanent and releases any database locks
* currently held by the Connection. This method should be
* used only when auto-commit mode has been disabled.
*
* @exception SQLException if a database access error occurs
* @see #setAutoCommit
*/
public void commit() throws SQLException
{
m_conn.commit();
} // end commit
/**
* Drops all changes made since the previous
* commit/rollback and releases any database locks currently held
* by this Connection. This method should be used only when auto-
* commit has been disabled.
*
* @exception SQLException if a database access error occurs
* @see #setAutoCommit
*/
public void rollback() throws SQLException
{
m_conn.rollback();
} // end rollback
/**
* Releases a Connection's database and JDBC resources
* immediately instead of waiting for them to be automatically released.
*
* @exception SQLException if a database access error occurs
*/
public synchronized void close() throws SQLException
{
try
{ // blow away the connection
if (!(m_conn.getAutoCommit()))
m_conn.rollback();
m_datapool.releaseConnection(m_conn);
m_conn = null;
} // end try
catch (DatabaseException e)
{ // database exception becomes SQLException
SQLException sqle = new SQLException(e.getMessage());
sqle.initCause(e);
throw sqle;
} // end catch
} // end close
/**
* Tests to see if a Connection is closed.
*
* @return true if the connection is closed; false if it's still open
* @exception SQLException if a database access error occurs
*/
public boolean isClosed() throws SQLException
{
return (m_conn==null) ? true : m_conn.isClosed();
} // end isClosed
/**
* Gets the metadata regarding this connection's database.
*
* @return a DatabaseMetaData object for this Connection
* @exception SQLException if a database access error occurs
*/
public DatabaseMetaData getMetaData() throws SQLException
{
return m_conn.getMetaData();
} // end getMetaData
/**
* Puts this connection in read-only mode as a hint to enable
* database optimizations.
*
* @param readOnly true enables read-only mode; false disables read-only mode.
* @exception SQLException if a database access error occurs
*/
public void setReadOnly(boolean readOnly)
{ // do nothing
} // end setReadOnly
/**
* Tests to see if the connection is in read-only mode.
*
* @return true if connection is read-only and false otherwise
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly()
{
return false;
} // end isReadOnly
/**
* Sets a catalog name in order to select
* a subspace of this Connection's database in which to work.
* If the driver does not support catalogs, it will
* silently ignore this request.
*
* @exception SQLException if a database access error occurs
*/
public void setCatalog(String catalog)
{ // do nothing
} // end setCatalog
/**
* Returns the Connection's current catalog name.
*
* @return the current catalog name or null
* @exception SQLException if a database access error occurs
*/
public String getCatalog() throws SQLException
{
return m_conn.getCatalog();
} // end getCatalog
/**
* Attempts to change the transaction
* isolation level to the one given.
* The constants defined in the interface <code>Connection</code>
* are the possible transaction isolation levels.
*
* @param level one of the TRANSACTION_* isolation values with the exception of TRANSACTION_NONE;
* some databases may not support other values
* @exception SQLException if a database access error occurs
* @see DatabaseMetaData#supportsTransactionIsolationLevel
*/
public void setTransactionIsolation(int level)
{ // do nothing
} // end setTransactionIsolation
/**
* Gets this Connection's current transaction isolation level.
*
* @return the current TRANSACTION_* mode value
* @exception SQLException if a database access error occurs
*/
public int getTransactionIsolation() throws SQLException
{
return m_conn.getTransactionIsolation();
} // end getTransactionIsolation
/**
* Returns the first warning reported by calls on this Connection.
*
* @return the first SQLWarning or null
* @exception SQLException if a database access error occurs
*/
public SQLWarning getWarnings() throws SQLException
{
return m_conn.getWarnings();
} // end getWarnings
/**
* Clears all warnings reported for this <code>Connection</code> object.
* After a call to this method, the method <code>getWarnings</code>
* returns null until a new warning is reported for this Connection.
*
* @exception SQLException if a database access error occurs
*/
public void clearWarnings() throws SQLException
{
m_conn.clearWarnings();
} // end clearWarnings
/**
* Creates a <code>Statement</code> object that will generate
* <code>ResultSet</code> objects with the given type and concurrency.
*
* @param resultSetType a result set type; see ResultSet.TYPE_XXX
* @param resultSetConcurrency a concurrency type; see ResultSet.CONCUR_XXX
* @return a new Statement object
* @exception SQLException if a database access error occurs
* @since 1.2
* @see <a href="package-summary.html#2.0 API">What Is in the JDBC 2.0 API</a>
*/
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{
return m_conn.createStatement(resultSetType,resultSetConcurrency);
} // end createStatement
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException
{
return m_conn.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
} // end createStatement
/**
* Creates a <code>PreparedStatement</code> object that will generate
* <code>ResultSet</code> objects with the given type and concurrency.
* This method is the same as the <code>prepareStatement</code> method
* above, but it allows the default result set
* type and result set concurrency type to be overridden.
*
* @param resultSetType a result set type; see ResultSet.TYPE_XXX
* @param resultSetConcurrency a concurrency type; see ResultSet.CONCUR_XXX
* @return a new PreparedStatement object containing the pre-compiled SQL statement
* @exception SQLException if a database access error occurs
* @since 1.2
* @see <a href="package-summary.html#2.0 API">What Is in the JDBC 2.0 API</a>
*/
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException
{
return m_conn.prepareStatement(sql,resultSetType,resultSetConcurrency);
} // end prepareStatement
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
return m_conn.prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
} // end prepareStatement
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
{
return m_conn.prepareStatement(sql,autoGeneratedKeys);
} // end prepareStatement
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
{
return m_conn.prepareStatement(sql,columnIndexes);
} // end prepareStatement
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{
return m_conn.prepareStatement(sql,columnNames);
} // end prepareStatement
/**
* Creates a <code>CallableStatement</code> object that will generate
* <code>ResultSet</code> objects with the given type and concurrency.
* This method is the same as the <code>prepareCall</code> method
* above, but it allows the default result set
* type and result set concurrency type to be overridden.
*
* @param resultSetType a result set type; see ResultSet.TYPE_XXX
* @param resultSetConcurrency a concurrency type; see ResultSet.CONCUR_XXX
* @return a new CallableStatement object containing the pre-compiled SQL statement
* @exception SQLException if a database access error occurs
* @since 1.2
* @see <a href="package-summary.html#2.0 API">What Is in the JDBC 2.0 API</a>
*/
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException
{
return m_conn.prepareCall(sql,resultSetType,resultSetConcurrency);
} // end prepareCall
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
return m_conn.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
} // end prepareCall
/**
* Gets the type map object associated with this connection.
* Unless the application has added an entry to the type map,
* the map returned will be empty.
*
* @return the <code>java.util.Map</code> object associated with this <code>Connection</code> object
* @since 1.2
* @see <a href="package-summary.html#2.0 API">What Is in the JDBC 2.0 API</a>
*/
public java.util.Map getTypeMap() throws SQLException
{
return m_conn.getTypeMap();
} // end getTypeMap
/**
* Installs the given type map as the type map for
* this connection. The type map will be used for the
* custom mapping of SQL structured types and distinct types.
*
* @param the <code>java.util.Map</code> object to install
* as the replacement for this <code>Connection</code>
* object's default type map
* @since 1.2
* @see <a href="package-summary.html#2.0 API">What Is in the JDBC 2.0 API</a>
*/
public void setTypeMap(java.util.Map map) throws SQLException
{
m_conn.setTypeMap(map);
} // end setTypeMap
public int getHoldability() throws SQLException
{
return m_conn.getHoldability();
} // end getHoldability
public void setHoldability(int holdability) throws SQLException
{ // do nothing
} // end setHoldability
public Savepoint setSavepoint() throws SQLException
{
return m_conn.setSavepoint();
} // end setSavepont
public Savepoint setSavepoint(String name) throws SQLException
{
return m_conn.setSavepoint(name);
} // end setSavepoint
public void rollback(Savepoint savepoint) throws SQLException
{
m_conn.rollback(savepoint);
} // end rollback
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
m_conn.releaseSavepoint(savepoint);
} // end releaseSavepoint
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
Connection getRealConnection()
{
return m_conn;
} // end getRealConnection
} // end class WrappedConnection

View File

@@ -0,0 +1,229 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
public abstract class BaseDialogField implements DialogField
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private boolean m_reverse; // if true, field is on left, false = right
private String m_name; // field name (parameter name)
private String m_caption; // primary caption
private String m_caption2; // secondary caption
private boolean m_required; // is this field required?
private boolean m_default_enabled; // are we enabled by default?
private boolean m_enabled; // are we currently enabled?
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
protected BaseDialogField(boolean reverse, Element element) throws DialogException
{
m_reverse = reverse;
XMLLoader loader = XMLLoader.get();
try
{ // get the base class stuff
m_name = loader.getAttribute(element,"name");
m_caption = loader.getAttribute(element,"caption");
m_caption2 = element.getAttribute("caption2");
m_required = loader.getAttributeBoolean(element,"required",false);
m_default_enabled = loader.getAttributeBoolean(element,"enabled",true);
} // end try
catch (XMLLoadException e)
{ // translate the exception and return it
throw new DialogException(e);
} // end catch
m_enabled = m_default_enabled;
} // end constructor
protected BaseDialogField(BaseDialogField other)
{
m_reverse = other.m_reverse;
m_name = other.m_name;
m_caption = other.m_caption;
m_caption2 = other.m_caption2;
m_required = other.m_required;
m_default_enabled = other.m_default_enabled;
m_enabled = m_default_enabled;
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private final void renderCaption(TextRenderControl control, Map render_params)
throws IOException, RenderingException
{
PrintWriter wr = control.getWriter();
if (!m_enabled)
wr.write("<span style=\"color: silver;\">");
wr.write(StringUtils.encodeHTML(StringUtils.replaceAllVariables(m_caption,render_params)));
if (StringUtils.isNotEmpty(m_caption2))
wr.write(" " + StringUtils.encodeHTML(StringUtils.replaceAllVariables(m_caption2,render_params)));
if (!m_reverse)
wr.write(":");
if (!m_enabled)
wr.write("</span>");
if (m_required)
wr.write("<span style=\"color: red;\"><b>*</b></span>");
} // end renderCaption
protected final String getCaption()
{
return m_caption;
} // end getCaption
protected final void setCaption2(String s)
{
m_caption2 = s;
} // end setCaption2
protected boolean isNull(Object value)
{
return (value==null);
} // end isNull
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
protected abstract void renderField(TextRenderControl control, Map render_params)
throws IOException, RenderingException;
protected abstract void validateContents(Request r, Object data) throws ValidationException;
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Abstract methods from interface DialogItem
*--------------------------------------------------------------------------------
*/
public abstract Object clone();
/*--------------------------------------------------------------------------------
* Implementations from interface DialogItem
*--------------------------------------------------------------------------------
*/
public void render(TextRenderControl control, Map render_params) throws IOException, RenderingException
{
PrintWriter wr = control.getWriter();
wr.write("<tr valign=\"middle\">\n<td align=\"right\" class=\"content\">");
if (m_reverse)
renderField(control,render_params);
else
renderCaption(control,render_params);
wr.write("</td>\n<td align=\"left\" class=\"content\">");
if (m_reverse)
renderCaption(control,render_params);
else
renderField(control,render_params);
wr.write("</td>\n</tr>\n");
} // end render
public boolean isEnabled()
{
return m_enabled;
} // end isEnabled
public void setEnabled(boolean flag)
{
m_enabled = flag;
} // end setEnabled
/*--------------------------------------------------------------------------------
* Abstract methods from interface DialogField
*--------------------------------------------------------------------------------
*/
public abstract Object getValue();
public abstract boolean containsValue();
public abstract void setValue(Object obj);
public abstract void setValueFrom(Request r);
public abstract void reset();
/*--------------------------------------------------------------------------------
* Implementations from interface DialogField
*--------------------------------------------------------------------------------
*/
public void validate(Request r) throws ValidationException
{
Object val = getValue();
if (m_required && m_enabled && isNull(val))
{ // null field value - we need to bail out
ValidationException ve = new ValidationException(BaseDialogField.class,"DialogMessages",
"required.field");
ve.setParameter(0,m_caption);
throw ve;
} // end if
if (m_enabled)
validateContents(r,val);
} // end validate
public int getFlags()
{
return (m_required ? FLAG_REQUIRED : 0);
} // end getFlags
} // end class BaseDialogField

View File

@@ -0,0 +1,21 @@
# 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# ---------------------------------------------------------------------------------
# This file has been localized for the en_US locale
cancel=Cancel
login=Log In
ok=OK
reminder=Reminder

View File

@@ -0,0 +1,187 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class CheckBoxField extends BaseDialogField
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String YES = "Y";
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_value;
private boolean m_default_checked;
private boolean m_checked;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
CheckBoxField(Element elt) throws DialogException
{
super(true,elt);
XMLLoader loader = XMLLoader.get();
try
{ // get the checkbox value
m_value = loader.getAttribute(elt,"value",YES);
m_default_checked = loader.getAttributeBoolean(elt,"checked",false);
} // end try
catch (XMLLoadException e)
{ // translate into DialogException
throw new DialogException(e);
} // end catch
m_checked = m_default_checked;
} // end constructor
protected CheckBoxField(CheckBoxField other)
{
super(other);
m_value = other.m_value;
m_default_checked = other.m_default_checked;
m_checked = m_default_checked;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class BaseDialogField
*--------------------------------------------------------------------------------
*/
protected boolean isNull(Object value)
{
return false;
} // end isNull
public int getFlags()
{
return 0;
} // end getFlags
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
protected void renderField(TextRenderControl control, Map render_params)
throws IOException, RenderingException
{
PrintWriter wr = control.getWriter();
wr.write("<input type=\"checkbox\" name=\"" + getName() + "\" value=\"" + m_value + "\"");
if (!isEnabled())
wr.write(" disabled=\"disabled\"");
if (m_checked)
wr.write(" checked=\"checked\"");
wr.write(" />");
} // end renderField
protected void validateContents(Request r, Object data) throws ValidationException
{ // do nothing
} // end validateContents
public Object clone()
{
return new CheckBoxField(this);
} // end clone
public Object getValue()
{
return Boolean.valueOf(m_checked);
} // end getValue
public boolean containsValue()
{
return true;
} // end containsValue
public void setValue(Object obj)
{
if (obj==null)
m_checked = m_default_checked;
else if (obj instanceof Boolean)
m_checked = ((Boolean)obj).booleanValue();
else if (obj instanceof Number)
m_checked = (((Number)obj).intValue()!=0);
else
{ // look at the string equivalent
String s = obj.toString();
if (StringUtils.isBooleanTrue(s))
m_checked = true;
else if (StringUtils.isBooleanFalse(s))
m_checked = false;
} // end else
} // end setValue
public void setValueFrom(Request r)
{
RequestHelper rh = new RequestHelper(r);
String[] vals = rh.getStringParameterValues(getName());
if (vals!=null)
{ // if no values are set, we're definitely NOT checked
for (int i=0; i<vals.length; i++)
{ // look and see if our value is among the values for this item
if (m_value.equals(vals[i]))
{ // found our value! bail out!
m_checked = true;
return;
} // end if
} // end for
} // end if
m_checked = false;
} // end setValueFrom
public void reset()
{
m_checked = m_default_checked;
} // end reset
} // end class CheckBoxField

View File

@@ -0,0 +1,187 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
abstract class CommonTextField extends BaseDialogField
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final int MINSIZE = 2;
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_tagname;
private String m_value = null;
private int m_size;
private int m_maxlength;
private int m_real_maxlength;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
protected CommonTextField(String tagname, Element elt) throws DialogException
{
super(false,elt);
m_tagname = tagname;
XMLLoader loader = XMLLoader.get();
try
{ // load the "size" attributes for the text field
int my_size = loader.getAttributeInt(elt,"size");
DOMElementHelper h = new DOMElementHelper(elt);
if (h.hasAttribute("maxlength"))
{ // get the maxlength and figure it in...
m_real_maxlength = loader.getAttributeInt(elt,"maxlength");
m_maxlength = Math.max(m_real_maxlength,MINSIZE);
m_size = Math.max(my_size,MINSIZE);
} // end if
else
{ // "size" is all we got - maxlength is equal to it
m_real_maxlength = my_size;
m_maxlength = m_size = Math.max(my_size,MINSIZE);
} // end else
} // end try
catch (XMLLoadException e)
{ // translate exception here
throw new DialogException(e);
} // end catch
} // end constructor
protected CommonTextField(String tagname, int width, Element elt) throws DialogException
{
super(false,elt);
m_tagname = tagname;
m_real_maxlength = width;
m_maxlength = m_size = Math.max(width,MINSIZE);
} // end constructor
protected CommonTextField(CommonTextField other)
{
super(other);
m_tagname = other.m_tagname;
m_size = other.m_size;
m_maxlength = other.m_maxlength;
m_real_maxlength = other.m_real_maxlength;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class BaseDialogField
*--------------------------------------------------------------------------------
*/
protected boolean isNull(Object value)
{
return StringUtils.isEmpty((String)value);
} // end isNull
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
protected void renderField(TextRenderControl control, Map render_params)
throws IOException, RenderingException
{
PrintWriter wr = control.getWriter();
wr.write("<input type=\"" + m_tagname + "\" class=\"content\" name=\"" + getName() + "\" size=\"" + m_size
+ "\" maxlength=\"" + m_maxlength + "\"");
if (!isEnabled())
wr.write(" disabled=\"disabled\"");
wr.write(" value=\"");
if (m_value!=null)
wr.write(m_value);
wr.write("\" />");
} // end renderField
protected void validateContents(Request r, Object data) throws ValidationException
{
if ((data!=null) && (data.toString().length()>m_real_maxlength))
{ // this value is too long
ValidationException ve = new ValidationException(CommonTextField.class,"DialogMessages","text.tooLong");
ve.setParameter(0,getCaption());
ve.setParameter(1,String.valueOf(m_real_maxlength));
throw ve;
} // end if
} // end validateContents
public Object getValue()
{
return m_value;
} // end getValue
public boolean containsValue()
{
return StringUtils.isNotEmpty(m_value);
} // end containsValue
public void setValue(Object obj)
{
if (obj==null)
m_value = null;
else
m_value = obj.toString();
if ((m_value!=null) && StringUtils.isEmpty(m_value))
m_value = null;
} // end setValue
public void setValueFrom(Request r)
{
RequestHelper rh = new RequestHelper(r);
m_value = rh.getParameterString(getName());
if ((m_value!=null) && StringUtils.isEmpty(m_value))
m_value = null;
} // end setValueFrom
public void reset()
{
m_value = null;
} // end reset
} // end class CommonTextField

View File

@@ -0,0 +1,123 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.util.*;
import org.w3c.dom.Element;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.DialogException;
class CountryListField extends PickListField
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Country UNKNOWN_COUNTRY = International.get().getCountryForCode("XX");
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
CountryListField(Element elt) throws DialogException
{
super(elt);
} // end constructor
protected CountryListField(CountryListField other)
{
super(other);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new CountryListField(this);
} // end clone
/*--------------------------------------------------------------------------------
* Overrides from class BaseDialogField
*--------------------------------------------------------------------------------
*/
protected boolean isNull(Object value)
{
return ((value==null) || UNKNOWN_COUNTRY.equals(value));
} // end isNull
/*--------------------------------------------------------------------------------
* Abstract implementations from class PickListField
*--------------------------------------------------------------------------------
*/
protected Iterator getChoices()
{
return International.get().getCountryList().iterator();
} // end getChoices
protected String getChoiceName(Object choice)
{
return ((Country)choice).getCode();
} // end getChoiceName
protected String getChoiceDisplay(Object choice)
{
return ((Country)choice).getName();
} // end getChoiceDisplay
protected Object getChoiceForName(String name)
{
return International.get().getCountryForCode(name);
} // end getChoiceForName
protected boolean isValidChoice(Object choice)
{
if (!(choice instanceof Country))
return false;
Country x = International.get().getCountryForCode(((Country)choice).getCode());
return x.equals(choice);
} // end isValidChoice
/*--------------------------------------------------------------------------------
* Overrides from class PickListField
*--------------------------------------------------------------------------------
*/
public boolean containsValue()
{
Object v = getValue();
return ((v!=null) && !UNKNOWN_COUNTRY.equals(v));
} // end containsValue
} // end class CountryListField

View File

@@ -0,0 +1,85 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.util.*;
import com.silverwrist.dynamo.iface.*;
class DefaultDialogLAF implements DialogPLAF
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private ResourceBundle m_captions;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
DefaultDialogLAF()
{
m_captions = ResourceBundle.getBundle("com.silverwrist.dynamo.dialog.ButtonCaptions",Locale.getDefault());
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface DialogPLAF
*--------------------------------------------------------------------------------
*/
public Object getButtonRendering(String button_name)
{
String caption;
try
{ // get the default caption
caption = m_captions.getString(button_name);
} // end try
catch (MissingResourceException e)
{ // default to just using the button name
caption = button_name;
} // end catch
StringBuffer buf = new StringBuffer("<input type=\"submit\" name=\"");
buf.append(button_name).append("\" value=\"").append(caption).append("\" />");
return buf.toString();
} // end getButtonRendering
public boolean isButtonClicked(Request r, String button_name)
{
return r.getParameters().containsKey(button_name);
} // end isButtonClicked
public Object getContentHeader(String title, String subtitle)
{
StringBuffer buf = new StringBuffer("<span class=\"chdrtitle\">");
buf.append(title).append("</span>\n");
if (subtitle!=null)
buf.append("&nbsp;&nbsp;<span class=\"chdrsubtitle\">").append(subtitle).append("</span>\n");
buf.append("<hr align=\"left\" size=\"2\" width=\"90%\" noshade=\"noshade\" />\n");
return buf.toString();
} // end getContentHeader
} // end class DefaultDialogLAF

View File

@@ -0,0 +1,643 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.except.*;
class DialogImpl implements Dialog
{
/*--------------------------------------------------------------------------------
* Internal class to "peel off" certain dialog items that are tags
*--------------------------------------------------------------------------------
*/
private class InternalFilter implements DialogItemFactory
{
/*====================================================================
* Attributes
*====================================================================
*/
private DialogItemFactory m_inner;
private HashMap m_rp = new HashMap();
/*====================================================================
* Constructor
*====================================================================
*/
InternalFilter(DialogItemFactory inner)
{
m_inner = inner;
} // end constructor
/*====================================================================
* Implementations from interface DialogItemFactory
*====================================================================
*/
public DialogItem createDialogItem(Element elt, DialogPLAF plaf) throws DialogException
{
try
{ // strip out certain items we need from the element stream
XMLLoader loader = XMLLoader.get();
String tagname = elt.getTagName();
if (tagname.equals("title"))
{ // get title
m_default_title = loader.getText(elt);
if (m_default_title!=null)
m_default_title = m_default_title.trim();
} // end if
else if (tagname.equals("subtitle"))
{ // get subtitle (not required)
DOMElementHelper h = new DOMElementHelper(elt);
m_default_subtitle = h.getElementText();
if (m_default_subtitle!=null)
m_default_subtitle = m_default_subtitle.trim();
} // end else if
else if (tagname.equals("action"))
{ // get action and action type
m_action = loader.getText(elt);
if (m_action!=null)
m_action = m_action.trim();
m_action_type = loader.getAttribute(elt,"type","SERVLET");
} // end else if
else if (tagname.equals("render-param"))
{ // get a rendering parameter
String name = loader.getAttribute(elt,"name");
DOMElementHelper h = new DOMElementHelper(elt);
String value = h.getElementText();
if (value!=null)
value = value.trim();
else
value = "";
m_rp.put(name,value);
} // end else if
else if (tagname.equals("instructions"))
{ // get instructions (not required)
DOMElementHelper h = new DOMElementHelper(elt);
m_default_instructions = h.getElementText();
if (m_default_instructions!=null)
m_default_instructions = m_default_instructions.trim();
} // end else if
else // go create a dialog item
return m_inner.createDialogItem(elt,plaf);
} // end try
catch (XMLLoadException e)
{ // translate XML Load exception to dialog exception
throw new DialogException(e);
} // end catch
return null;
} // end createDialogItem
/*====================================================================
* External operations
*====================================================================
*/
Map renderParams()
{
if (m_rp.isEmpty())
return Collections.EMPTY_MAP;
else
return Collections.unmodifiableMap(m_rp);
} // end renderParams
} // end class InternalFilter
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DialogPLAF m_plaf;
private String m_name;
private String m_default_button = null;
private String m_default_title = null;
private String m_default_subtitle = null;
private String m_action = null;
private String m_action_type = null;
private String m_default_instructions = null;
private boolean m_any_required;
private boolean m_need_multipart;
private List m_field_order;
private Map m_field_map;
private List m_button_order;
private Map m_button_map;
private List m_hidden_order;
private Map m_hidden_map;
private String m_title = null;
private String m_subtitle = null;
private String m_instructions = null;
private String m_error_message = null;
private Map m_default_render_params;
private HashMap m_render_params;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
DialogImpl(Element dialog_element, DialogItemFactory item_factory, DialogPLAF plaf) throws DialogException
{
// Copy the look-and-feel object reference.
m_plaf = plaf;
// Get the basic stuff from the root tag itself.
XMLLoader loader = XMLLoader.get();
try
{ // get the dialog name
m_name = loader.getAttribute(dialog_element,"name");
m_default_button = dialog_element.getAttribute("defaultbutton");
} // end try
catch (XMLLoadException e)
{ // translate to DialogException
throw new DialogException(e);
} // end catch
// Load the fields.
ArrayList field_order = new ArrayList();
HashMap field_map = new HashMap();
ArrayList button_order = new ArrayList();
HashMap button_map = new HashMap();
ArrayList hidden_order = new ArrayList();
HashMap hidden_map = new HashMap();
int global_flags = 0;
InternalFilter factory = new InternalFilter(item_factory);
NodeList nl = dialog_element.getChildNodes();
for (int i=0; i<nl.getLength(); i++)
{ // get each item to be implemented here
Node n = nl.item(i);
if (n.getNodeType()==Node.ELEMENT_NODE)
{ // create the dialog items
DialogItem item = factory.createDialogItem((Element)n,plaf);
if (item==null)
continue;
if (item instanceof DialogField)
{ // add the field to the field data structures
global_flags |= ((DialogField)item).getFlags();
field_order.add(item);
field_map.put(item.getName(),item);
} // end if
else if (item instanceof DialogButton)
{ // add the button to the button data structures
button_order.add(item);
button_map.put(item.getName(),item);
} // end else if
else if (item instanceof DialogHiddenItem)
{ // add the hidden item to the hidden data structures
hidden_order.add(item);
hidden_map.put(item.getName(),item);
} // end else if
} // end if
} // end for
// If anything hasn't been specified that should have been, error out now.
if (m_default_title==null)
{ // no default title specified
DialogException de = new DialogException(DialogImpl.class,"DialogMessages","dlg.noTitle");
de.setParameter(0,m_name);
throw de;
} // end if
if (m_action==null)
{ // no action URL specified
DialogException de = new DialogException(DialogImpl.class,"DialogMessages","dlg.noAction");
de.setParameter(0,m_name);
throw de;
} // end if
// "Freeze" the data structures.
field_order.trimToSize();
m_field_order = Collections.unmodifiableList(field_order);
m_field_map = Collections.unmodifiableMap(field_map);
button_order.trimToSize();
m_button_order = Collections.unmodifiableList(button_order);
m_button_map = Collections.unmodifiableMap(button_map);
hidden_order.trimToSize();
m_hidden_order = Collections.unmodifiableList(hidden_order);
m_hidden_map = Collections.unmodifiableMap(hidden_map);
m_default_render_params = factory.renderParams();
// Set the global flags.
m_any_required = ((global_flags & DialogField.FLAG_REQUIRED)!=0);
m_need_multipart = ((global_flags & DialogField.FLAG_ISFILE)!=0);
// Copy defaults to working values.
m_title = m_default_title;
m_subtitle = m_default_subtitle;
m_instructions = m_default_instructions;
m_error_message = null;
m_render_params = new HashMap(m_default_render_params);
} // end constructor
protected DialogImpl(DialogImpl other)
{
// Copy the base data.
m_plaf = other.m_plaf;
m_name = other.m_name;
m_default_title = other.m_default_title;
m_default_subtitle = other.m_default_subtitle;
m_action = other.m_action;
m_action_type = other.m_action_type;
m_default_instructions = other.m_default_instructions;
m_any_required = other.m_any_required;
m_need_multipart = other.m_need_multipart;
m_default_render_params = other.m_default_render_params;
// Clone off the fields.
ArrayList order = new ArrayList();
HashMap map = new HashMap();
Iterator it = other.m_field_order.iterator();
while (it.hasNext())
{ // clone all the fields
DialogField fld = (DialogField)(it.next());
DialogField new_fld = (DialogField)(fld.clone());
order.add(new_fld);
map.put(new_fld.getName(),new_fld);
} // end while
// "Freeze" the field data structures.
order.trimToSize();
m_field_order = Collections.unmodifiableList(order);
m_field_map = Collections.unmodifiableMap(map);
// Since the buttons aren't modified, we can get away with sharing
// the button order and button map.
m_button_order = other.m_button_order;
m_button_map = other.m_button_map;
// Clone off the hidden fields.
order = new ArrayList();
map = new HashMap();
it = other.m_hidden_order.iterator();
while (it.hasNext())
{ // clone all the fields
DialogHiddenItem fld = (DialogHiddenItem)(it.next());
DialogHiddenItem new_fld = (DialogHiddenItem)(fld.clone());
order.add(new_fld);
map.put(new_fld.getName(),new_fld);
} // end while
// "Freeze" the field data structures.
order.trimToSize();
m_hidden_order = Collections.unmodifiableList(order);
m_hidden_map = Collections.unmodifiableMap(map);
// Copy defaults to working values.
m_title = m_default_title;
m_subtitle = m_default_subtitle;
m_instructions = m_default_instructions;
m_error_message = null;
m_render_params = new HashMap(m_default_render_params);
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
protected final DialogField getField(String name)
{
return (DialogField)(m_field_map.get(name));
} // end getField
protected final DialogHiddenItem getHiddenItem(String name)
{
return (DialogHiddenItem)(m_hidden_map.get(name));
} // end getHiddenItem
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface Dialog
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new DialogImpl(this);
} // end clone
public void render(TextRenderControl control) throws IOException, RenderingException
{
PrintWriter wr = control.getWriter();
URLRewriter rewriter = (URLRewriter)(control.queryService(URLRewriter.class));
// Get the content header and render it.
control.renderSubObject(m_plaf.getContentHeader(m_title,m_subtitle));
// Write the error message.
if (m_error_message!=null)
wr.write("<p align=\"center\" class=\"content\" style=\"color: red; font-weight: bold;\">\n"
+ StringUtils.encodeHTML(m_error_message) + "\n</p>\n");
// Write the start of the form.
wr.write("<form name=\"" + m_name + "\"");
if (m_need_multipart)
wr.write(" enctype=\"multipart/form-data\"");
wr.write(" method=\"POST\" action=\"" + rewriter.rewriteURL(m_action_type,m_action)
+ "\"><div class=\"content\">\n");
// Create the render params parameter.
Map rparam = Collections.unmodifiableMap(m_render_params);
// Render the hidden fields.
Iterator it = m_hidden_order.iterator();
while (it.hasNext())
{ // render each hidden field in turn
DialogHiddenItem hfld = (DialogHiddenItem)(it.next());
hfld.render(control,rparam);
} // end while
// Render the instructions and such.
if (m_instructions!=null)
wr.write("<p>" + m_instructions + "</p>\n");
if (m_any_required)
{ // write out the "required" instructions
ResourceBundle b = ResourceBundle.getBundle("com.silverwrist.dynamo.dialog.DialogMessages",
Locale.getDefault());
wr.write("<p>" + b.getString("required.msg") + "</p>");
} // end if
// Write the form fields out inside a table.
wr.write("<table border=\"0\" align=\"center\" cellpadding=\"6\" cellspacing=\"0\">\n");
it = m_field_order.iterator();
while (it.hasNext())
{ // render each field in turn
DialogField fld = (DialogField)(it.next());
fld.render(control,rparam);
} // end while
wr.write("</table>\n");
if (!(m_button_order.isEmpty()))
{ // render the command buttons at the button
boolean is_first = true;
wr.write("<p align=\"center\" class=\"content\">");
it = m_button_order.iterator();
while (it.hasNext())
{ // render each button in turn, spacing them out
DialogButton bn = (DialogButton)(it.next());
if (is_first)
is_first = false;
else
wr.write("&nbsp;&nbsp;");
bn.render(control,rparam);
} // end while
wr.write("</p>\n");
} // end if
wr.write("</div></form>\n");
} // end render
public void reset()
{
m_title = m_default_title;
m_subtitle = m_default_subtitle;
m_instructions = m_default_instructions;
Iterator it = m_field_order.iterator();
while (it.hasNext())
{ // call reset on each field
DialogField fld = (DialogField)(it.next());
fld.reset();
} // end while
it = m_hidden_order.iterator();
while (it.hasNext())
{ // call reset on each hidden field
DialogHiddenItem hfld = (DialogHiddenItem)(it.next());
hfld.reset();
} // end while
} // end reset
public void load(Request r)
{
Iterator it = m_field_order.iterator();
while (it.hasNext())
{ // call setValueFrom on each field
DialogField fld = (DialogField)(it.next());
fld.setValueFrom(r);
} // end while
it = m_hidden_order.iterator();
while (it.hasNext())
{ // call setValueFrom on each hidden field
DialogHiddenItem hfld = (DialogHiddenItem)(it.next());
hfld.setValueFrom(r);
} // end while
} // end load
public Object getValue(String fieldname)
{
DialogField fld = getField(fieldname);
if (fld==null)
{ // try looking for a hidden field
DialogHiddenItem hfld = getHiddenItem(fieldname);
if (hfld==null)
return null;
else
return hfld.getValue();
} // end if
else
return fld.getValue();
} // end getValue
public boolean containsValue(String fieldname)
{
DialogField fld = getField(fieldname);
if (fld!=null)
return fld.containsValue();
DialogHiddenItem hfld = getHiddenItem(fieldname);
if (hfld!=null)
return hfld.containsValue();
return false;
} // end containsValue
public void setValue(String fieldname, Object value)
{
DialogField fld = getField(fieldname);
if (fld!=null)
fld.setValue(value);
else
{ // try setting a hidden value
DialogHiddenItem hfld = getHiddenItem(fieldname);
if (hfld!=null)
hfld.setValue(value);
} // end else
} // end setValue
public boolean isEnabled(String fieldname)
{
DialogField fld = getField(fieldname);
if (fld==null)
return false;
else
return fld.isEnabled();
} // end isEnabled
public void setEnabled(String fieldname, boolean flag)
{
DialogField fld = getField(fieldname);
if (fld!=null)
fld.setEnabled(flag);
} // end setEnabled
public void validate(Request r) throws ValidationException
{
// validate all the fields individually
Iterator it = m_field_order.iterator();
while (it.hasNext())
{ // call reset on each field
DialogField fld = (DialogField)(it.next());
fld.validate(r);
} // end while
} // end validate
public String getTitle()
{
return m_title;
} // end getTitle
public void setTitle(String s)
{
m_title = s;
} // end setTitle
public String getSubtitle()
{
return m_subtitle;
} // end getSubtitle
public void setSubtitle(String s)
{
m_subtitle = s;
} // end setSubtitle
public String getInstructions()
{
return m_instructions;
} // end getInstructions
public void setInstructions(String s)
{
m_instructions = s;
} // end setInstructions
public void setErrorMessage(String s)
{
m_error_message = s;
} // end setErrorMessage
public String getClickedButton(Request r)
{
Iterator it = m_button_order.iterator();
while (it.hasNext())
{ // look for a clicked button
DialogButton bn = (DialogButton)(it.next());
if (bn.isClicked(r))
return bn.getName();
} // end while
return m_default_button;
} // end getClickedButton
public synchronized void setRenderParam(String name, String value)
{
if (m_render_params.containsKey(name))
m_render_params.put(name,value);
} // end setRenderParam
} // end class DialogImpl

View File

@@ -0,0 +1,300 @@
/*
* 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class DialogManager
implements NamedObject, ComponentInitialize, ComponentShutdown, DialogFactoryConfig, DialogLoader
{
/*--------------------------------------------------------------------------------
* Internal class implementing the dialog item factory
*--------------------------------------------------------------------------------
*/
private class Factory implements DialogItemFactory
{
/*====================================================================
* Constructor
*====================================================================
*/
Factory()
{ // do nothing
} // end constructor
/*====================================================================
* Implementations from interface DialogItemFactory
*====================================================================
*/
public DialogItem createDialogItem(Element elt, DialogPLAF plaf) throws DialogException
{
DialogItemFactory fact = (DialogItemFactory)(m_factory_data.get(elt.getTagName()));
if (fact!=null)
return fact.createDialogItem(elt,plaf);
throw new UnknownDialogFieldException(elt.getTagName(),elt);
} // end createDialogItem
} // end class Factory
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final int DEFAULT_HARD_LIMIT = 5;
private static final int DEFAULT_SOFT_LIMIT = 20;
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name;
private String m_resource_prefix;
private ResourceProvider m_prov;
private DialogPLAF m_plaf;
private HardSoftCache m_resource_cache;
private Hashtable m_factory_data = new Hashtable();
private ComponentShutdown m_shut_init;
private ComponentShutdown m_shut_runtime;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public DialogManager()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentInitialize
*--------------------------------------------------------------------------------
*/
public void initialize(Element config_root, ServiceProvider services) throws ConfigException
{
XMLLoader loader = XMLLoader.get();
int hard_limit = DEFAULT_HARD_LIMIT;
int soft_limit = DEFAULT_SOFT_LIMIT;
try
{ // verify the right node name
loader.verifyNodeName(config_root,"object");
// get the object's name
m_name = loader.getAttribute(config_root,"name");
// get the resource prefix
DOMElementHelper config_h = new DOMElementHelper(config_root);
m_resource_prefix = config_h.getSubElementText("resource-prefix");
if (m_resource_prefix==null)
{ // set up default prefix
m_resource_prefix = "/";
} // end if
else
{ // make sure the prefix is properly set
if (!(m_resource_prefix.startsWith("/")))
m_resource_prefix = "/" + m_resource_prefix;
if (!(m_resource_prefix.endsWith("/")))
m_resource_prefix += "/";
} // end else
// get the resource dialog cache information
Element elt = config_h.getSubElement("resource-dialog-cache");
if (elt!=null)
{ // get the cache limits
hard_limit = loader.getAttributeInt(elt,"hardlimit",DEFAULT_HARD_LIMIT);
soft_limit = loader.getAttributeInt(elt,"softlimit",DEFAULT_SOFT_LIMIT);
} // end if
} // end try
catch (XMLLoadException e)
{ // error loading XML config data
throw new ConfigException(e);
} // end catch
// Get the standard resource provider.
m_prov = (ResourceProvider)(services.queryService(ResourceProvider.class));
// Set up the default look-and-feel provider.
m_plaf = new DefaultDialogLAF();
// Create the resource cache.
m_resource_cache = new HardSoftCache(hard_limit,soft_limit);
// Set up the standard factory elements.
DialogItemFactory fact = new StdItemFactory();
m_factory_data.put("button",fact);
m_factory_data.put("checkbox",fact);
m_factory_data.put("countrylist",fact);
m_factory_data.put("dynamo-id",fact);
m_factory_data.put("email",fact);
m_factory_data.put("header",fact);
m_factory_data.put("hidden",fact);
m_factory_data.put("int",fact);
m_factory_data.put("localelist",fact);
m_factory_data.put("password",fact);
m_factory_data.put("text",fact);
m_factory_data.put("tzlist",fact);
// Get the service provider hooks interface.
HookServiceProviders hooker = (HookServiceProviders)(services.queryService(HookServiceProviders.class));
// Hook the initialization services with our initialization interface.
SingletonServiceProvider ssp = new SingletonServiceProvider("DialogManager",DialogFactoryConfig.class,
(DialogFactoryConfig)this);
m_shut_init = hooker.hookInitServiceProvider(ssp);
// Hook the runtime services with the DialogLoader interface.
ssp = new SingletonServiceProvider("DialogManager",DialogLoader.class,(DialogLoader)this);
m_shut_runtime = hooker.hookRuntimeServiceProvider(ssp);
} // end initialize
/*--------------------------------------------------------------------------------
* Implementations from interface ComponentShutdown
*--------------------------------------------------------------------------------
*/
public void shutdown()
{
m_shut_runtime.shutdown();
m_shut_runtime = null;
m_shut_init.shutdown();
m_shut_init = null;
m_resource_cache.clear();
m_factory_data.clear();
m_plaf = null;
m_prov = null;
} // end shutdown
/*--------------------------------------------------------------------------------
* Implementations from interface DialogFactoryConfig
*--------------------------------------------------------------------------------
*/
public synchronized void setDialogPLAF(DialogPLAF plaf)
{
m_plaf = ((plaf==null) ? new DefaultDialogLAF() : plaf);
} // end setDialogPLAF
public ComponentShutdown registerDialogItem(String item_name, DialogItemFactory factory)
throws ConfigException
{
if (m_factory_data.containsKey(item_name))
{ // already registered - can't register again
ConfigException ce = new ConfigException(DialogManager.class,"DialogMessages","control.registered");
ce.setParameter(0,item_name);
throw ce;
} // end if
m_factory_data.put(item_name,factory);
return new ShutdownHashtableRemove(m_factory_data,item_name);
} // end registerDialogItem
/*--------------------------------------------------------------------------------
* Implementations from interface DialogLoader
*--------------------------------------------------------------------------------
*/
public Dialog loadDialogResource(String resource_name) throws DialogException
{
Dialog dlg = (Dialog)(m_resource_cache.get(resource_name));
if (dlg==null)
{ // OK, try loading the resource for the dialog...
InputStream stm = null;
try
{ // get the resource as a stream
stm = m_prov.getResource(m_resource_prefix + resource_name);
// parse it into an XML document
XMLLoader loader = XMLLoader.get();
Document doc = loader.load(stm,false);
// get the root element, which should be <dialog/>
Element elt = loader.getRootElement(doc,"dialog");
// now create the dialog! (and cache it)
dlg = new DialogImpl(elt,new Factory(),m_plaf);
m_resource_cache.put(resource_name,dlg);
} // end try
catch (IOException e)
{ // translate the exception and throw it
DialogException de = new DialogException(DialogManager.class,"DialogMessages","dlg.loadErr",e);
de.setParameter(0,resource_name);
de.setParameter(1,e.getMessage());
throw de;
} // end catch
catch (NoSuchResourceException e)
{ // translate this exception and throw it as well
DialogException de = new DialogException(DialogManager.class,"DialogMessages","dlg.notFound",e);
de.setParameter(0,resource_name);
throw de;
} // end catch
catch (XMLLoadException e)
{ // this translates straight into a DialogException
throw new DialogException(e);
} // end catch
finally
{ // make sure and close the stream before we go
IOUtils.shutdown(stm);
} // end finally
} // end if
// Clone the dialog before we return it, so as not to mess up the one in the cache.
return (Dialog)(dlg.clone());
} // end loadDialogResource
} // end class DialogManager

View File

@@ -0,0 +1,31 @@
# 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# ---------------------------------------------------------------------------------
# This file has been localized for the en_US locale
required.field=A value must be entered for the "{0}" field.
text.tooLong=The value of the "{0}" field must be no longer than {1} characters.
bad.itemType=No implementation exists for dialog item type "{0}".
bad.dynamoID=There is an invalid character in the "{0}" field. Valid characters are letters, digits, -, _, !, ~, *, ', and $.
dlg.noTitle=No default title specified for dialog "{0}".
dlg.noAction=No action URL specified for dialog "{0}".
required.msg=Required fields are marked with a <span style="color: red; font-weight: bold;">*</span>.
control.registered=A control has already been registered with the name "{0}".
dlg.loadErr=Unable to load the data for dialog resource "{0}": {1}
dlg.notFound=Unable to locate dialog resource "{0}".
bad.email=The value in the "{0}" field is not a valid E-mail address.
text.notInteger=Invalid non-numeric character in the "{0}" field.
int.tooSmall=The value of the "{0}" field must be greater than or equal to {1}.
int.tooLarge=The value of the "{0}" field must be less than or equal to {1}.

View File

@@ -0,0 +1,73 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import org.w3c.dom.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class DynamoIDField extends TextField
{
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
DynamoIDField(Element elt) throws DialogException
{
super(elt);
} // end constructor
protected DynamoIDField(DynamoIDField other)
{
super(other);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class CommonTextField
*--------------------------------------------------------------------------------
*/
protected void validateContents(Request r, Object data) throws ValidationException
{
super.validateContents(r,data);
if ((data!=null) && !(IDUtils.isValidDynamoID(data.toString())))
{ // not a valid Dynamo ID - throw exception
ValidationException ve = new ValidationException(DynamoIDField.class,"DialogMessages","bad.dynamoID");
ve.setParameter(0,getCaption());
throw ve;
} // end if
} // end validateContents
/*--------------------------------------------------------------------------------
* Overrides from class TextField
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new DynamoIDField(this);
} // end clone
} // end class DynamoIDField

View File

@@ -0,0 +1,73 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import org.w3c.dom.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class EmailAddressField extends TextField
{
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
EmailAddressField(Element elt) throws DialogException
{
super(elt);
} // end constructor
protected EmailAddressField(EmailAddressField other)
{
super(other);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class CommonTextField
*--------------------------------------------------------------------------------
*/
protected void validateContents(Request r, Object data) throws ValidationException
{
super.validateContents(r,data);
if ((data!=null) && !(IDUtils.isValidEmailAddress(data.toString())))
{ // not a valid E-mail address - throw exception
ValidationException ve = new ValidationException(EmailAddressField.class,"DialogMessages","bad.email");
ve.setParameter(0,getCaption());
throw ve;
} // end if
} // end validateContents
/*--------------------------------------------------------------------------------
* Overrides from class TextField
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new EmailAddressField(this);
} // end clone
} // end class EmailAddressField

View File

@@ -0,0 +1,177 @@
/*
* 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
class HeaderItem implements DialogField
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name; // name of header
private String m_caption; // caption to display
private String m_text; // text to display on right
private boolean m_default_enabled; // enabled or not?
private boolean m_enabled; // enabled or not?
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
HeaderItem(Element elt) throws DialogException
{
XMLLoader loader = XMLLoader.get();
try
{ // get the elements
m_name = loader.getAttribute(elt,"name");
m_caption = loader.getAttribute(elt,"caption");
DOMElementHelper h = new DOMElementHelper(elt);
m_text = h.getElementText();
if (m_text!=null)
m_text = m_text.trim();
m_default_enabled = loader.getAttributeBoolean(elt,"enabled",true);
} // end try
catch (XMLLoadException e)
{ // translate XML loader exception
throw new DialogException(e);
} // end catch
m_enabled = m_default_enabled;
} // end constructor
protected HeaderItem(HeaderItem other)
{
m_name = other.m_name;
m_caption = other.m_caption;
m_text = other.m_text;
m_default_enabled = other.m_default_enabled;
m_enabled = m_default_enabled;
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface DialogItem
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new HeaderItem(this);
} // end clone
public void render(TextRenderControl control, Map render_params) throws IOException, RenderingException
{
PrintWriter wr = control.getWriter();
wr.write("<tr valign=\"middle\">\n<td align=\"right\" class=\"content\"><span style=\"font-weight: bold;");
if (!m_enabled)
wr.write(" color: silver;");
wr.write("\">" + StringUtils.encodeHTML(StringUtils.replaceAllVariables(m_caption,render_params))
+ ":</span></td>\n<td align=\"left\" class=\"content\">");
if (m_text==null)
wr.write("&nbsp;");
else
{ // write out the text on the right hand side
if (!m_enabled)
wr.write("<span style=\"color: silver;\">");
wr.write(StringUtils.encodeHTML(StringUtils.replaceAllVariables(m_text,render_params)));
if (!m_enabled)
wr.write("</span>");
} // end else
wr.write("</td>\n</tr>\n");
} // end render
public boolean isEnabled()
{
return m_enabled;
} // end isEnabled
public void setEnabled(boolean flag)
{
m_enabled = flag;
} // end setEnabled
/*--------------------------------------------------------------------------------
* Implementations from interface DialogField
*--------------------------------------------------------------------------------
*/
public Object getValue()
{
return null;
} // end getValue
public boolean containsValue()
{
return false;
} // end containsValue
public void setValue(Object obj)
{ // do nothing
} // end setValue
public void setValueFrom(Request r)
{ // do nothing
} // end setValueFrom
public void validate(Request r)
{ // do nothing
} // end validate
public void reset()
{ // do nothing
} // end reset
public int getFlags()
{
return 0;
} // end getFlags
} // end class HeaderItem

View File

@@ -0,0 +1,148 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class HiddenField implements DialogHiddenItem
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_name;
private String m_default_value;
private String m_value;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
HiddenField(Element elt) throws DialogException
{
XMLLoader loader = XMLLoader.get();
try
{ // get field parameters from XML
m_name = loader.getAttribute(elt,"name");
m_default_value = loader.getAttribute(elt,"value","");
} // end try
catch (XMLLoadException e)
{ // translate this exception
throw new DialogException(e);
} // end catch
m_value = m_default_value;
} // end class HiddenField
protected HiddenField(HiddenField other)
{
m_name = other.m_name;
m_default_value = other.m_default_value;
m_value = m_default_value;
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface DialogItem
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new HiddenField(this);
} // end clone
public void render(TextRenderControl control, Map render_params) throws IOException, RenderingException
{
PrintWriter wr = control.getWriter();
wr.write("<input type=\"hidden\" name=\"" + m_name + "\" value=\""
+ StringUtils.replaceAllVariables(m_value,render_params) + "\" />\n");
} // end render
public boolean isEnabled()
{
return true;
} // end isEnabled
public void setEnabled(boolean flag)
{ // do nothing
} // end setEnabled
/*--------------------------------------------------------------------------------
* Implementations from interface DialogHiddenItem
*--------------------------------------------------------------------------------
*/
public Object getValue()
{
return m_value;
} // end getValue
public boolean containsValue()
{
return StringUtils.isNotEmpty(m_value);
} // end containsValue
public void setValue(Object obj)
{
m_value = ((obj==null) ? m_default_value : obj.toString());
} // end setValue
public void setValueFrom(Request r)
{
RequestHelper rh = new RequestHelper(r);
m_value = rh.getParameterString(m_name);
} // end setValueFrom
public void reset()
{
m_value = m_default_value;
} // end reset
} // end class HiddenField

View File

@@ -0,0 +1,271 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
class IntegerField extends CommonTextField
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final double LN10 = Math.log(10.0);
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private int m_min_value;
private int m_max_value;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
IntegerField(Element elt) throws DialogException
{
super("text",numDigits(elt),elt);
XMLLoader loader = XMLLoader.get();
DOMElementHelper h = new DOMElementHelper(elt);
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
try
{ // get the min and max values from the config item
if (h.hasAttribute("min"))
min = loader.getAttributeInt(elt,"min");
if (h.hasAttribute("max"))
max = loader.getAttributeInt(elt,"max");
} // end try
catch (XMLLoadException e)
{ // translate the exception
throw new DialogException(e);
} // end catch
if (max<min)
{ // assign the values the "wrong" way round
m_min_value = max;
m_max_value = min;
} // end if
else
{ // assign the values normally
m_min_value = min;
m_max_value = max;
} // end else
} // end elt
protected IntegerField(IntegerField other)
{
super(other);
m_min_value = other.m_min_value;
m_max_value = other.m_max_value;
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
private static final int numDigits(int v)
{
if (v==0)
return 1;
else if (v>0)
return 1 + (int)(Math.floor(Math.log((double)v) / LN10));
else
return 2 + (int)(Math.floor(Math.log((double)(-v)) / LN10));
} // end numDigits
private static final int numDigits(int min, int max)
{
return Math.max(numDigits(min),numDigits(max));
} // end numDigits
private static final int numDigits(Element elt) throws DialogException
{
XMLLoader loader = XMLLoader.get();
DOMElementHelper h = new DOMElementHelper(elt);
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
try
{ // get the min and max values from the config item
if (h.hasAttribute("min"))
min = loader.getAttributeInt(elt,"min");
if (h.hasAttribute("max"))
max = loader.getAttributeInt(elt,"max");
} // end try
catch (XMLLoadException e)
{ // translate the exception
throw new DialogException(e);
} // end catch
return numDigits(min,max);
} // end numDigits
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new IntegerField(this);
} // end clone
/*--------------------------------------------------------------------------------
* Overrides from class CommonDialogField
*--------------------------------------------------------------------------------
*/
protected void renderField(TextRenderControl control, Map render_params)
throws IOException, RenderingException
{
super.renderField(control,render_params);
PrintWriter wr = control.getWriter();
wr.write("&nbsp;(" + m_min_value + " - " + m_max_value + ")");
} // end renderField
protected void validateContents(Request r, Object data) throws ValidationException
{
if (data==null)
return;
try
{ // convert to an integer and chack against range
int x = Integer.parseInt(data.toString());
if ((m_min_value>Integer.MIN_VALUE) && (x<m_min_value))
{ // value is too small
ValidationException ve = new ValidationException(IntegerField.class,"DialogMessages","int.tooSmall");
ve.setParameter(0,getCaption());
ve.setParameter(1,String.valueOf(m_min_value));
throw ve;
} // end if
if ((m_max_value<Integer.MAX_VALUE) && (x>m_max_value))
{ // value is too large
ValidationException ve = new ValidationException(IntegerField.class,"DialogMessages","int.tooLarge");
ve.setParameter(0,getCaption());
ve.setParameter(1,String.valueOf(m_max_value));
throw ve;
} // end if
} // end try
catch (NumberFormatException e)
{ // integer conversion failed - throw an error
ValidationException ve = new ValidationException(IntegerField.class,"DialogMessages","text.notInteger");
ve.setParameter(0,getCaption());
throw ve;
} // end catch
} // end validateContents
public Object getValue()
{
String s = (String)(super.getValue());
if (s==null)
return null;
try
{ // map the return value to an Integer
return new Integer(s);
} // end try
catch (NumberFormatException e)
{ // this is not supposed to happen
throw new IllegalStateException("IntegerField.getValue(): value is not an integer!");
} // end catch
} // end getValue
public boolean containsValue()
{
return (super.getValue()!=null);
} // end containsValue
public void setValue(Object obj)
{
if (obj==null)
{ // deal with null values early
super.setValue(null);
return;
} // end if
int real_val;
if (obj instanceof Number)
real_val = ((Number)obj).intValue();
else
{ // convert the value to a string, then to integer
try
{ // perform the conversion
real_val = Integer.parseInt(obj.toString());
} // end try
catch (NumberFormatException e)
{ // just use a sensible default
real_val = m_min_value;
} // end catch
} // end else
// Constrain the value.
if (real_val<m_min_value)
real_val = m_min_value;
else if (real_val>m_max_value)
real_val = m_max_value;
// Now actually set it.
super.setValue(String.valueOf(real_val));
} // end setValue
public void setValueFrom(Request r)
{
RequestHelper rh = new RequestHelper(r);
this.setValue(rh.getParameterString(getName()));
} // end setValueFrom
} // end class IntegerField

View File

@@ -0,0 +1,90 @@
/*
* 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.util.*;
import org.w3c.dom.Element;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.DialogException;
class LocaleListField extends PickListField
{
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
LocaleListField(Element elt) throws DialogException
{
super(elt);
} // end constructor
protected LocaleListField(LocaleListField other)
{
super(other);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new LocaleListField(this);
} // end clone
/*--------------------------------------------------------------------------------
* Abstract implementations from class PickListField
*--------------------------------------------------------------------------------
*/
protected Iterator getChoices()
{
return Arrays.asList(Locale.getAvailableLocales()).iterator();
} // end getChoices
protected String getChoiceName(Object choice)
{
return choice.toString();
} // end getChoiceName
protected String getChoiceDisplay(Object choice)
{
return ((Locale)choice).getDisplayName();
} // end getChoiceDisplay
protected Object getChoiceForName(String name)
{
return International.get().createLocale(name);
} // end getChoiceForName
protected boolean isValidChoice(Object choice)
{
return (choice instanceof Locale);
} // end isValidChoice
} // end class LocaleListField

View File

@@ -0,0 +1,58 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class PasswordField extends CommonTextField
{
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
public PasswordField(Element elt) throws DialogException
{
super("password",elt);
} // end constructor
protected PasswordField(PasswordField other)
{
super(other);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new PasswordField(this);
} // end clone
} // end class PasswordField

View File

@@ -0,0 +1,137 @@
/*
* 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public abstract class PickListField extends BaseDialogField
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Object m_value;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
protected PickListField(Element elt) throws DialogException
{
super(false,elt);
m_value = null;
} // end constructor
protected PickListField(PickListField other)
{
super(other);
m_value = null;
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract operations
*--------------------------------------------------------------------------------
*/
protected abstract Iterator getChoices();
protected abstract String getChoiceName(Object choice);
protected abstract String getChoiceDisplay(Object choice);
protected abstract Object getChoiceForName(String name);
protected abstract boolean isValidChoice(Object choice);
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
protected void renderField(TextRenderControl control, Map render_params)
throws IOException, RenderingException
{
PrintWriter wr = control.getWriter();
wr.write("<select name=\"" + getName() + "\" size=\"1\"");
if (!isEnabled())
wr.write(" disabled=\"disabled\"");
wr.write(">\n");
Iterator it = getChoices();
while (it.hasNext())
{ // render each choice name and display value in turn
Object ch = it.next();
wr.write("<option value=\"" + getChoiceName(ch) + "\"");
if (ch.equals(m_value))
wr.write(" selected=\"selected\"");
wr.write(">"
+ StringUtils.encodeHTML(StringUtils.replaceAllVariables(getChoiceDisplay(ch),render_params))
+ "</option>\n");
} // end while
wr.write("</select>");
} // end renderField
protected void validateContents(Request r, Object data) throws ValidationException
{ // don't need to validate the contents on a pick list
} // end validateContents
public Object getValue()
{
return m_value;
} // end getValue
public boolean containsValue()
{
return (m_value!=null);
} // end containsValue
public void setValue(Object obj)
{
if ((obj==null) || isValidChoice(obj))
m_value = obj;
} // end setValue
public void setValueFrom(Request r)
{
RequestHelper rh = new RequestHelper(r);
m_value = getChoiceForName(rh.getParameterString(getName()));
} // end setValueFrom
public void reset()
{
m_value = null;
} // return reset
} // end class PickListField

View File

@@ -0,0 +1,118 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
class StdButton implements DialogButton
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DialogPLAF m_plaf;
private String m_name;
private Object m_rendering;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
StdButton(Element elt, DialogPLAF plaf) throws DialogException
{
m_plaf = plaf;
XMLLoader loader = XMLLoader.get();
try
{ // get the name
m_name = loader.getAttribute(elt,"name");
m_rendering = plaf.getButtonRendering(m_name);
} // end try
catch (XMLLoadException e)
{ // failed to load dialog - throw exception
throw new DialogException(e);
} // end catch
} // end constructor
protected StdButton(StdButton other)
{
m_plaf = other.m_plaf;
m_name = other.m_name;
m_rendering = other.m_rendering;
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface NamedObject
*--------------------------------------------------------------------------------
*/
public String getName()
{
return m_name;
} // end getName
/*--------------------------------------------------------------------------------
* Implementations from interface DialogItem
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new StdButton(this);
} // end clone
public void render(TextRenderControl control, Map render_params) throws IOException, RenderingException
{
control.renderSubObject(m_rendering);
} // end render
public boolean isEnabled()
{
return true;
} // end isEnabled
public void setEnabled(boolean flag)
{ // do nothing
} // end setEnabled
/*--------------------------------------------------------------------------------
* Implementations from interface DialogButton
*--------------------------------------------------------------------------------
*/
public boolean isClicked(Request r)
{
return m_plaf.isButtonClicked(r,m_name);
} // end isClicked
} // end class StdButton

View File

@@ -0,0 +1,80 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
class StdItemFactory implements DialogItemFactory
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Logger logger = Logger.getLogger(StdItemFactory.class);
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
StdItemFactory()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface DialogItemFactory
*--------------------------------------------------------------------------------
*/
public DialogItem createDialogItem(Element elt, DialogPLAF plaf) throws DialogException
{
String tagname = elt.getTagName();
if (tagname.equals("button"))
return new StdButton(elt,plaf);
if (tagname.equals("checkbox"))
return new CheckBoxField(elt);
if (tagname.equals("countrylist"))
return new CountryListField(elt);
if (tagname.equals("dynamo-id"))
return new DynamoIDField(elt);
if (tagname.equals("email"))
return new EmailAddressField(elt);
if (tagname.equals("header"))
return new HeaderItem(elt);
if (tagname.equals("hidden"))
return new HiddenField(elt);
if (tagname.equals("int"))
return new IntegerField(elt);
if (tagname.equals("localelist"))
return new LocaleListField(elt);
if (tagname.equals("password"))
return new PasswordField(elt);
if (tagname.equals("text"))
return new TextField(elt);
if (tagname.equals("tzlist"))
return new TimeZoneListField(elt);
throw new UnknownDialogFieldException(tagname,elt);
} // end createDialogItem
} // end class StdItemFactory

View File

@@ -0,0 +1,58 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.io.*;
import org.w3c.dom.*;
import com.silverwrist.util.*;
import com.silverwrist.util.xml.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class TextField extends CommonTextField
{
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
public TextField(Element elt) throws DialogException
{
super("text",elt);
} // end constructor
protected TextField(TextField other)
{
super(other);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new TextField(this);
} // end clone
} // end class TextField

View File

@@ -0,0 +1,116 @@
/*
* 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) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.dialog;
import java.util.*;
import org.w3c.dom.Element;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.DialogException;
class TimeZoneListField extends PickListField
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final List TZ_LIST;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
TimeZoneListField(Element elt) throws DialogException
{
super(elt);
} // end constructor
protected TimeZoneListField(TimeZoneListField other)
{
super(other);
} // end constructor
/*--------------------------------------------------------------------------------
* Abstract implementations from class BaseDialogField
*--------------------------------------------------------------------------------
*/
public Object clone()
{
return new TimeZoneListField(this);
} // end clone
/*--------------------------------------------------------------------------------
* Abstract implementations from class PickListField
*--------------------------------------------------------------------------------
*/
protected Iterator getChoices()
{
return TZ_LIST.iterator();
} // end getChoices
protected String getChoiceName(Object choice)
{
return ((TimeZone)choice).getID();
} // end getChoiceName
protected String getChoiceDisplay(Object choice)
{
TimeZone tz = (TimeZone)choice;
return tz.getID() + " (" + tz.getDisplayName() + ")";
} // end getChoiceDisplay
protected Object getChoiceForName(String name)
{
return TimeZone.getTimeZone(name);
} // end getChoiceForName
protected boolean isValidChoice(Object choice)
{
return (choice instanceof TimeZone);
} // end isValidChoice
/*--------------------------------------------------------------------------------
* Static initializer
*--------------------------------------------------------------------------------
*/
static
{ // get the list of IDs and sort them
String ids[] = TimeZone.getAvailableIDs();
Arrays.sort(ids);
// now create the list of TimeZone objects
ArrayList tmp = new ArrayList(ids.length);
for (int i=0; i<ids.length; i++)
tmp.add(TimeZone.getTimeZone(ids[i]));
TZ_LIST = Collections.unmodifiableList(tmp);
} // end static initializer
} // end class TimeZoneListField

View File

@@ -0,0 +1,44 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public class ApplicationAdapter implements ApplicationListener
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ApplicationAdapter()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface ApplicationListener
*--------------------------------------------------------------------------------
*/
public void applicationInitialized(ApplicationEvent event)
{ // do nothing
} // end applicationInitialized
public void applicationExiting(ApplicationEvent event)
{ // do nothing
} // end applicationExiting
} // end class ApplicationAdapter

View File

@@ -0,0 +1,71 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
import com.silverwrist.dynamo.iface.*;
public class ApplicationEvent extends DynamoEventObject
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private transient Application m_app;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ApplicationEvent(Request request, Application app)
{
super(request);
m_app = app;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class DynamoEventObject
*--------------------------------------------------------------------------------
*/
public String toString()
{
return "ApplicationEvent: request = " + source + ", application = " + m_app;
} // end toString
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public Request getRequest()
{
return (Request)getSource();
} // end getRequest
public Application getApplication()
{
return m_app;
} // end getApplication
} // end class ApplicationEvent

View File

@@ -0,0 +1,189 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
import java.util.*;
import com.silverwrist.dynamo.RequestType;
import com.silverwrist.dynamo.Verb;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class ApplicationEventRequest extends BaseDelegatingServiceProvider implements Request
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String EMPTY_STRING = "";
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Verb m_verb;
private Locale[] m_locales;
private MemoryObjectStore m_attrs;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ApplicationEventRequest(ServiceProvider services, boolean start)
{
super("ApplicationEventRequest",services);
m_verb = (start ? Verb.PUT : Verb.DELETE);
m_locales = new Locale[1];
m_locales[0] = Locale.getDefault();
m_attrs = new MemoryObjectStore(ApplicationEventRequest.class.getName());
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectProvider
*--------------------------------------------------------------------------------
*/
/**
* Retrieves an object from this <CODE>ObjectProvider</CODE>.
*
* @param namespace The namespace to interpret the name relative to.
* @param name The name of the object to be retrieved.
* @return The object reference specified.
*/
public Object getObject(String namespace, String name)
{
return m_attrs.getObject(namespace,name);
} // end getObject
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectStore
*--------------------------------------------------------------------------------
*/
public Object setObject(String namespace, String name, Object value)
{
return m_attrs.setObject(namespace,name,value);
} // end setObject
public Object removeObject(String namespace, String name)
{
return m_attrs.removeObject(namespace,name);
} // end removeObject
public Collection getNamespaces()
{
return m_attrs.getNamespaces();
} // end getNamespaces
public Collection getNamesForNamespace(String namespace)
{
return m_attrs.getNamesForNamespace(namespace);
} // end getNamesForNamespace
/*--------------------------------------------------------------------------------
* Implementations from interface Request
*--------------------------------------------------------------------------------
*/
public RequestType getType()
{
return RequestType._APPLICATION;
} // end getType
public String getServerName()
{
return EMPTY_STRING;
} // end getEmptyString
public int getServerPort()
{
return -1;
} // end getServerPort
public String getContextPath()
{
return EMPTY_STRING;
} // end getContextPath
public String getRequestPath()
{
return EMPTY_STRING;
} // end getRequestPath
public String getExtraPath()
{
return EMPTY_STRING;
} // end getExtraPath
public String getQueryString()
{
return EMPTY_STRING;
} // end getQueryString
public Verb getVerb()
{
return m_verb;
} // end getVerb
public String getSourceAddress()
{
return "127.0.0.1";
} // end getSourceAddress
public Map getParameters()
{
return Collections.EMPTY_MAP;
} // end getParameters
public Class getParametersEntryClass()
{
return Object.class;
} // end getParametersEntryClass
public Map getDataItems()
{
return Collections.EMPTY_MAP;
} // end getDataItems
public Locale[] getLocales()
{
return m_locales;
} // end getLocales
} // end class ApplicationEventRequest

View File

@@ -0,0 +1,26 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public interface ApplicationListener extends DynamoEventListener
{
public void applicationInitialized(ApplicationEvent event);
public void applicationExiting(ApplicationEvent event);
} // end interface ApplicationListener

View File

@@ -0,0 +1,44 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public class DynamicUpdateEvent extends DynamoEventObject
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public DynamicUpdateEvent(Object src)
{
super(src);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class DynamoEventObject
*--------------------------------------------------------------------------------
*/
public String toString()
{
return "DynamicUpdateEvent: source = " + source;
} // end toString
} // end class DynamicUpdateEvent

View File

@@ -0,0 +1,24 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public interface DynamicUpdateListener extends DynamoEventListener
{
public void updateReceived(DynamicUpdateEvent evt);
} // end class DynamicUpdateListener

View File

@@ -0,0 +1,32 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
import java.util.EventListener;
/**
* The base interface for all Dynamo framework event listeners.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public interface DynamoEventListener extends EventListener
{
// no methods
} // end interface DynamoEventListener

View File

@@ -0,0 +1,65 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
import java.util.EventObject;
/**
* The root class from which all Dynamo event state objects are derived.
* <p> All events are constructed with a reference to the object, the "source", that is logically deemed
* to be the object upon which the event in question initially occurred upon.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class DynamoEventObject extends EventObject
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new <CODE>DynamoEventObject</CODE>.
*
* @param src The object on which the event initially occurred.
*/
public DynamoEventObject(Object src)
{
super(src);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class EventObject
*--------------------------------------------------------------------------------
*/
/**
* Returns a string representation of the object. In general, the <CODE>toString</CODE> method returns a string
* that "textually represents" this object.
*
* @return A string representation of the object.
*/
public String toString()
{
return "DynamoEventObject: source = " + source;
} // end toString
} // end class DynamoEventObject

View File

@@ -0,0 +1,72 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public class GlobalBlockUpdateEvent extends GlobalUpdateEvent
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private transient String m_namespace;
private transient String m_name;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public GlobalBlockUpdateEvent(Object src, String namespace, String name)
{
super(src);
m_namespace = namespace;
m_name = name;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class GlobalUpdateEvent
*--------------------------------------------------------------------------------
*/
public String toString()
{
return "GlobalBlockUpdateEvent: source = " + source + ", namespace = " + m_namespace
+ ", name = " + m_name;
} // end toString
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String getBlockNamespace()
{
return m_namespace;
} // end getPropertyNamespace
public String getBlockName()
{
return m_name;
} // end getPropertyName
} // end class GlobalBlockUpdateEvent

View File

@@ -0,0 +1,72 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public class GlobalPropertyUpdateEvent extends GlobalUpdateEvent
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private transient String m_namespace;
private transient String m_name;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public GlobalPropertyUpdateEvent(Object src, String namespace, String name)
{
super(src);
m_namespace = namespace;
m_name = name;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class GlobalUpdateEvent
*--------------------------------------------------------------------------------
*/
public String toString()
{
return "GlobalPropertyUpdateEvent: source = " + source + ", namespace = " + m_namespace
+ ", name = " + m_name;
} // end toString
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public String getPropertyNamespace()
{
return m_namespace;
} // end getPropertyNamespace
public String getPropertyName()
{
return m_name;
} // end getPropertyName
} // end class GlobalPropertyUpdateEvent

View File

@@ -0,0 +1,44 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public class GlobalUpdateEvent extends DynamicUpdateEvent
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public GlobalUpdateEvent(Object src)
{
super(src);
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class DynamicUpdateEvent
*--------------------------------------------------------------------------------
*/
public String toString()
{
return "GlobalUpdateEvent: source = " + source;
} // end toString
} // end class GlobalUpdateEvent

View File

@@ -0,0 +1,72 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
import com.silverwrist.dynamo.iface.Request;
import com.silverwrist.dynamo.iface.ScriptEngineRegisterObject;
public class ScriptEngineStartEvent extends DynamoEventObject
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private transient ScriptEngineRegisterObject m_registrar;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public ScriptEngineStartEvent(Request request, ScriptEngineRegisterObject registrar)
{
super(request);
m_registrar = registrar;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class DynamoEventObject
*--------------------------------------------------------------------------------
*/
public String toString()
{
return "ScriptEngineStartEvent: request = " + source + ", registrar = " + m_registrar;
} // end toString
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public Request getRequest()
{
return (Request)getSource();
} // end getRequest
public ScriptEngineRegisterObject getRegistrar()
{
return m_registrar;
} // end getRegistrar
} // end class ScriptEngineStartEvent

View File

@@ -0,0 +1,24 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public interface ScriptEngineStartListener extends DynamoEventListener
{
public void scriptEngineStarting(ScriptEngineStartEvent event);
} // end interface ScriptEngineStartListener

View File

@@ -0,0 +1,240 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
import java.util.*;
import com.silverwrist.dynamo.RequestType;
import com.silverwrist.dynamo.Verb;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
public class SessionEventRequest extends BaseDelegatingServiceProvider implements Request
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static final String EMPTY_STRING = "";
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private DefaultSessionInfoProvider m_session;
private Verb m_verb;
private Locale[] m_locales;
private MemoryObjectStore m_attrs;
private Request m_request;
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
public SessionEventRequest(ServiceProvider services, SessionInfo session, boolean start)
{
super("SessionEventRequest",services);
m_session = new DefaultSessionInfoProvider(session);
m_verb = (start ? Verb.PUT : Verb.DELETE);
m_locales = new Locale[1];
m_locales[0] = Locale.getDefault();
m_attrs = new MemoryObjectStore(SessionEventRequest.class.getName());
m_request = null;
} // end constructor
public SessionEventRequest(SessionInfo session, boolean start, Request request)
{
super("SessionEventRequest",request);
m_session = null;
m_verb = (start ? Verb.PUT : Verb.DELETE);
m_locales = null;
m_attrs = new MemoryObjectStore(SessionEventRequest.class.getName());
m_request = request;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class BaseDelegatingServiceProvider
*--------------------------------------------------------------------------------
*/
/**
* Queries this object for a specified service.
*
* @param klass The class of the object that should be returned as a service.
* @return A service object. The service object is guaranteed to be of the class
* specified by <CODE>klass</CODE>; that is, if <CODE>queryService(klass)</CODE>
* yields some object <CODE>x</CODE>, then the expression <CODE>klass.isInstance(x)</CODE>
* is true.
* @exception com.silverwrist.dynamo.except.NoSuchServiceException If no service is available in
* the specified class.
*/
public Object queryService(Class klass)
{
if ((m_session!=null) && (klass==SessionInfoProvider.class))
return m_session;
return super.queryService(klass);
} // end queryService
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectProvider
*--------------------------------------------------------------------------------
*/
/**
* Retrieves an object from this <CODE>ObjectProvider</CODE>.
*
* @param namespace The namespace to interpret the name relative to.
* @param name The name of the object to be retrieved.
* @return The object reference specified.
*/
public Object getObject(String namespace, String name)
{
return m_attrs.getObject(namespace,name);
} // end getObject
/*--------------------------------------------------------------------------------
* Implementations from interface ObjectStore
*--------------------------------------------------------------------------------
*/
public Object setObject(String namespace, String name, Object value)
{
return m_attrs.setObject(namespace,name,value);
} // end setObject
public Object removeObject(String namespace, String name)
{
return m_attrs.removeObject(namespace,name);
} // end removeObject
public Collection getNamespaces()
{
return m_attrs.getNamespaces();
} // end getNamespaces
public Collection getNamesForNamespace(String namespace)
{
return m_attrs.getNamesForNamespace(namespace);
} // end getNamesForNamespace
/*--------------------------------------------------------------------------------
* Implementations from interface Request
*--------------------------------------------------------------------------------
*/
public RequestType getType()
{
return RequestType._SESSION;
} // end getType
public String getServerName()
{
if (m_request!=null)
return m_request.getServerName();
else
return EMPTY_STRING;
} // end getEmptyString
public int getServerPort()
{
if (m_request!=null)
return m_request.getServerPort();
else
return -1;
} // end getServerPort
public String getContextPath()
{
return EMPTY_STRING;
} // end getContextPath
public String getRequestPath()
{
return EMPTY_STRING;
} // end getRequestPath
public String getExtraPath()
{
return EMPTY_STRING;
} // end getExtraPath
public String getQueryString()
{
return EMPTY_STRING;
} // end getQueryString
public Verb getVerb()
{
return m_verb;
} // end getVerb
public String getSourceAddress()
{
if (m_request!=null)
return m_request.getSourceAddress();
else
return "127.0.0.1";
} // end getSourceAddress
public Map getParameters()
{
return Collections.EMPTY_MAP;
} // end getParameters
public Class getParametersEntryClass()
{
return Object.class;
} // end getParametersEntryClass
public Map getDataItems()
{
return Collections.EMPTY_MAP;
} // end getDataItems
public Locale[] getLocales()
{
if (m_request!=null)
return m_request.getLocales();
else
return m_locales;
} // end getLocales
} // end class SessionEventRequest

View File

@@ -0,0 +1,44 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public class SessionInfoAdapter implements SessionInfoListener
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public SessionInfoAdapter()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Implementations from interface SessionInfoListener
*--------------------------------------------------------------------------------
*/
public void sessionInitialized(SessionInfoEvent event)
{ // do nothing
} // end sessionInitialized
public void sessionExiting(SessionInfoEvent event)
{ // do nothing
} // end sessionExiting
} // end class SessionInfoAdapter

View File

@@ -0,0 +1,71 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
import com.silverwrist.dynamo.iface.*;
public class SessionInfoEvent extends DynamoEventObject
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private transient SessionInfo m_session;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
public SessionInfoEvent(Request request, SessionInfo session)
{
super(request);
m_session = session;
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class DynamoEventObject
*--------------------------------------------------------------------------------
*/
public String toString()
{
return "SessionInfoEvent: request = " + source + ", session = " + m_session;
} // end toString
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
public Request getRequest()
{
return (Request)getSource();
} // end getRequest
public SessionInfo getSession()
{
return m_session;
} // end getSession
} // end class SessionInfoEvent

View File

@@ -0,0 +1,26 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
public interface SessionInfoListener extends DynamoEventListener
{
public void sessionInitialized(SessionInfoEvent event);
public void sessionExiting(SessionInfoEvent event);
} // end interface SessionInfoListener

View File

@@ -0,0 +1,152 @@
/*
* 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) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.dynamo.event;
import com.silverwrist.dynamo.iface.*;
/**
* Events of this type are sent to an object that implements
* {@link com.silverwrist.dynamo.event.SessionValueBindListener SessionValueBindListener} when it is bound
* or unbound from a {@link com.silverwrist.dynamo.iface.SessionInfo SessionInfo} object.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class SessionValueBindEvent extends DynamoEventObject
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private transient String m_namespace; // namespace for this value
private transient String m_name; // name for this value
private transient Object m_value; // value for event
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new instance of <CODE>SessionValueBindEvent</CODE>.
*
* @param session The {@link com.silverwrist.dynamo.iface.SessionInfo SessionInfo} associated with the event.
* @param namespace The namespace URI associated with the object.
* @param name The name associated with the object.
*/
public SessionValueBindEvent(SessionInfo session, String namespace, String name)
{
super(session);
m_namespace = namespace;
m_name = name;
m_value = null;
} // end consructor
/**
* Constructs a new instance of <CODE>SessionValueBindEvent</CODE>.
*
* @param session The {@link com.silverwrist.dynamo.iface.SessionInfo SessionInfo} associated with the event.
* @param namespace The namespace URI associated with the object.
* @param name The name associated with the object.
* @param value The object value associated with the event.
*/
public SessionValueBindEvent(SessionInfo session, String namespace, String name, Object value)
{
super(session);
m_namespace = namespace;
m_name = name;
m_value = value;
} // end consructor
/*--------------------------------------------------------------------------------
* Overrides from class DynamoEventObject
*--------------------------------------------------------------------------------
*/
/**
* Returns a string representation of the object. In general, the <CODE>toString</CODE> method returns a string
* that "textually represents" this object.
*
* @return A string representation of the object.
*/
public String toString()
{
return "SessionValueBindEvent: session = " + source + ", namespace = " + m_namespace + ", name = "
+ m_name + ", value = " + m_value;
} // end toString
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the {@link com.silverwrist.dynamo.iface.SessionInfo SessionInfo} associated with this event.
*
* @return The <CODE>SessionInfo</CODE> associated with this event.
*/
public SessionInfo getSession()
{
return (SessionInfo)getSource();
} // end getSession
/**
* Returns the namespace URI that the value is/was stored under.
*
* @return The namespace URI that the value is/was stored under.
*/
public String getNamespace()
{
return m_namespace;
} // end getNamespace
/**
* Returns the name that the value is/was stored under.
*
* @return The name that the value is/was stored under.
*/
public String getName()
{
return m_name;
} // end getName
/**
* Returns the value associated with the event. For
* {@link com.silverwrist.dynamo.event.SessionValueBindListener#valueAdded(com.silverwrist.dynamo.event.SessionValueBindEvent) valueAdded()}
* events, this value is the target value itself. For
* {@link com.silverwrist.dynamo.event.SessionValueBindListener#valueReplaced(com.silverwrist.dynamo.event.SessionValueBindEvent) valueReplaced()}
* events, this value is the value that the target value was replaced with in the session. For
* {@link com.silverwrist.dynamo.event.SessionValueBindListener#valueRemoved(com.silverwrist.dynamo.event.SessionValueBindEvent) valueRemoved()}
* events, this value is <CODE>null</CODE>.
*
* @return The value associated with the event.
*/
public Object getValue()
{
return m_value;
} // end getValue
} // end class SessionValueBindEvent

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