Seam SVN: r10605 - examples/trunk/servlet-booking.
by seam-commits@lists.jboss.org
Author: dan.j.allen
Date: 2009-04-23 02:43:49 -0400 (Thu, 23 Apr 2009)
New Revision: 10605
Added:
examples/trunk/servlet-booking/readme.txt
Modified:
examples/trunk/servlet-booking/pom.xml
Log:
configured tomcat deployment plugin
Modified: examples/trunk/servlet-booking/pom.xml
===================================================================
--- examples/trunk/servlet-booking/pom.xml 2009-04-23 06:43:31 UTC (rev 10604)
+++ examples/trunk/servlet-booking/pom.xml 2009-04-23 06:43:49 UTC (rev 10605)
@@ -20,6 +20,22 @@
<plugins>
<plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>tomcat-maven-plugin</artifactId>
+ <version>1.0-beta-1</version>
+ <configuration>
+ <path>/${project.build.finalName}</path>
+ <!-- expecting username to be "admin" and a blank password for manager app -->
+ <!-- configure a server in settings.xml containing <username> and <password> to override -->
+ <!--<server>tomcatserver</server>-->
+ <url>http://localhost:${tomcat.run.port}/manager</url>
+ <port>${embedded-tomcat.run.port}</port> <!-- port for embedded Tomcat only (I don't get how to isolate this config to run goal) -->
+ </configuration>
+ <dependencies>
+ </dependencies>
+ </plugin>
+
+ <plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.16</version>
@@ -35,7 +51,8 @@
<contextPath>/${project.build.finalName}</contextPath>
</webAppConfig>
</configuration>
- <dependencies/>
+ <dependencies>
+ </dependencies>
</plugin>
</plugins>
@@ -44,6 +61,9 @@
<properties>
<jetty.run.port>9090</jetty.run.port>
<jetty.debug.port>9190</jetty.debug.port>
+ <tomcat.run.port>8080</tomcat.run.port>
+ <embedded-tomcat.run.port>${jetty.run.port}</embedded-tomcat.run.port>
+ <embedded-tomcat.debug.port>${jetty.debug.port}</embedded-tomcat.debug.port>
</properties>
<dependencies>
Added: examples/trunk/servlet-booking/readme.txt
===================================================================
--- examples/trunk/servlet-booking/readme.txt (rev 0)
+++ examples/trunk/servlet-booking/readme.txt 2009-04-23 06:43:49 UTC (rev 10605)
@@ -0,0 +1,57 @@
+Seam Booking Example
+====================
+
+This example demonstrates the use of Seam 3 in a Servlet container environment
+(Tomcat 6 or Jetty 6). Contextual state management and dependency injection are
+handled by JSR-299. Transaction and persistence context management is handled
+by the EJB 3 container. No alterations are expected to be made to the Servlet
+container. All services are self-contained within the deployment.
+
+This example uses a Maven 2 build. Execute the following command to build the
+WAR. The WAR will will be located in the target directory after completion of
+the build.
+
+ mvn
+
+Run this command to execute the application in an embedded Jetty 6 container:
+
+ mvn jetty:run
+
+You can also execute the application in an embedded Tomcat 6 container:
+
+ mvn tomcat:run
+
+In both cases, any changes to assets in src/main/webapp will take affect
+immediately. If a change to a configuration file is made, the application will
+automatically redeploy. The redeploy behavior can be fined tuned in the plugin
+configuration (at least for Jetty).
+
+If you want to run the application on a standalone Tomcat 6, first download,
+extract and start Tomcat 6. This build assumes that Tomcat is available at
+localhost on port 8080. You can deploy the packaged archive to Tomcat via HTTP
+PUT using this command:
+
+ mvn package tomcat:deploy
+
+Then you use this command to undeploy the application:
+
+ mvn tomcat:undeploy
+
+Instead of packaging the WAR, you can deploy it as an exploded archive
+immediately after the war goal is finished assembling the exploded structure:
+
+ mvn compile war:exploded tomcat:exploded
+
+Once the application is deployed, you can redeploy it using the following command:
+
+ mvn tomcat:redeploy
+
+But likely you want to run one or more build goals first before you redeploy:
+
+ mvn compile tomcat:redeploy
+ mvn war:exploded tomcat:redeploy
+ mvn compile war:exploded tomcat:redeploy
+
+Use of the war:inplace + tomcat:inplace goals are not recommended as it causes
+files to be copied to your src/main/webapp directory. You may accidently check
+them into the source repository or include them in the deployable archive.
17 years
Seam SVN: r10604 - examples/trunk/servlet-booking/src/main/webapp/META-INF.
by seam-commits@lists.jboss.org
Author: dan.j.allen
Date: 2009-04-23 02:43:31 -0400 (Thu, 23 Apr 2009)
New Revision: 10604
Modified:
examples/trunk/servlet-booking/src/main/webapp/META-INF/context.xml
Log:
don't allow Tomcat to save session state between restarts
Modified: examples/trunk/servlet-booking/src/main/webapp/META-INF/context.xml
===================================================================
--- examples/trunk/servlet-booking/src/main/webapp/META-INF/context.xml 2009-04-23 01:11:25 UTC (rev 10603)
+++ examples/trunk/servlet-booking/src/main/webapp/META-INF/context.xml 2009-04-23 06:43:31 UTC (rev 10604)
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Context>
+ <Manager pathname=""/> <!-- disables storage of sessions across restarts -->
<Resource name="jcdi/Manager"
auth="Container"
type="javax.inject.manager.Manager"
17 years
Seam SVN: r10603 - in modules/trunk/security: src/main/java/org/jboss/seam/security and 3 other directories.
by seam-commits@lists.jboss.org
Author: shane.bryzak(a)jboss.com
Date: 2009-04-22 21:11:25 -0400 (Wed, 22 Apr 2009)
New Revision: 10603
Added:
modules/trunk/security/src/main/java/org/jboss/seam/security/util/Base64.java
Removed:
modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestAuthenticator.java
modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestRequest.java
modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestUtils.java
modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestValidationException.java
modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenId.java
modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenIdPhaseListener.java
modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenIdPrincipal.java
modules/trunk/security/src/main/java/org/jboss/seam/security/package-info.java
Modified:
modules/trunk/security/pom.xml
modules/trunk/security/src/main/java/org/jboss/seam/security/Identity.java
modules/trunk/security/src/main/java/org/jboss/seam/security/RememberMe.java
modules/trunk/security/src/main/java/org/jboss/seam/security/RunAsOperation.java
modules/trunk/security/src/main/java/org/jboss/seam/security/SecurityInterceptor.java
Log:
removed digest and openid support for now, more code ported
Modified: modules/trunk/security/pom.xml
===================================================================
--- modules/trunk/security/pom.xml 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/pom.xml 2009-04-23 01:11:25 UTC (rev 10603)
@@ -27,6 +27,10 @@
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>javax.faces</groupId>
+ <artifactId>jsf-api</artifactId>
+ </dependency>
</dependencies>
</project>
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/Identity.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/Identity.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/Identity.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -609,7 +609,7 @@
this.jaasConfigName = jaasConfigName;
}
- synchronized void runAs(RunAsOperation operation)
+ public synchronized void runAs(RunAsOperation operation)
{
Principal savedPrincipal = getPrincipal();
Subject savedSubject = getSubject();
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/RememberMe.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/RememberMe.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/RememberMe.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,26 +1,26 @@
package org.jboss.seam.security;
-import static org.jboss.seam.ScopeType.SESSION;
-import static org.jboss.seam.annotations.Install.BUILT_IN;
-
import java.io.Serializable;
import java.rmi.server.UID;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
+import javax.annotation.Named;
+import javax.context.SessionScoped;
+import javax.event.Observes;
import javax.faces.context.FacesContext;
+import javax.inject.Current;
+import javax.inject.Initializer;
-import org.jboss.seam.Component;
-import org.jboss.seam.annotations.Create;
-import org.jboss.seam.annotations.Install;
-import org.jboss.seam.annotations.Name;
-import org.jboss.seam.annotations.Observer;
-import org.jboss.seam.annotations.Scope;
-import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.faces.Selector;
+import org.jboss.seam.security.events.CredentialsInitializedEvent;
+import org.jboss.seam.security.events.CredentialsUpdatedEvent;
+import org.jboss.seam.security.events.LoggedOutEvent;
+import org.jboss.seam.security.events.PostAuthenticateEvent;
+import org.jboss.seam.security.events.QuietLoginEvent;
import org.jboss.seam.security.management.IdentityManager;
-import org.jboss.seam.util.Base64;
+import org.jboss.seam.security.util.Base64;
/**
* Remember-me functionality is provided by this class, in two different flavours. The first mode
@@ -32,10 +32,8 @@
*
* @author Shane Bryzak
*/
-@Name("org.jboss.seam.security.rememberMe")
-@Scope(SESSION)
-@Install(precedence = BUILT_IN, classDependencies = "javax.faces.context.FacesContext")
-@BypassInterceptors
+@Named
+@SessionScoped
public class RememberMe implements Serializable
{
class UsernameSelector extends Selector
@@ -130,6 +128,10 @@
private Mode mode = Mode.usernameOnly;
+ @Current private Identity identity;
+ @Current private Credentials credentials;
+ @Current private IdentityManager identityManager;
+
public Mode getMode()
{
return mode;
@@ -183,7 +185,7 @@
this.tokenStore = tokenStore;
}
- @Create
+ @Initializer
public void create()
{
if (mode.equals(Mode.usernameOnly))
@@ -228,8 +230,7 @@
return ctx != null ? ctx.getExternalContext().getRequestContextPath() : null;
}
- @Observer(Credentials.EVENT_INIT_CREDENTIALS)
- public void initCredentials(Credentials credentials)
+ public void initCredentials(@Observes CredentialsInitializedEvent event)
{
String cookiePath = getCookiePath();
@@ -244,7 +245,7 @@
if (username!=null)
{
setEnabled(true);
- credentials.setUsername(username);
+ event.getCredentials().setUsername(username);
}
usernameSelector.setDirty();
@@ -265,8 +266,8 @@
if (tokenStore.validateToken(decoded.getUsername(), decoded.getValue()))
{
- credentials.setUsername(decoded.getUsername());
- credentials.setPassword(decoded.getValue());
+ event.getCredentials().setUsername(decoded.getUsername());
+ event.getCredentials().setPassword(decoded.getValue());
}
else
{
@@ -285,35 +286,32 @@
boolean value;
}
- @Observer(Identity.EVENT_QUIET_LOGIN)
- public void quietLogin()
- {
- final Identity identity = Identity.instance();
-
+ public void quietLogin(@Observes QuietLoginEvent event)
+ {
if (mode.equals(Mode.autoLogin) && isEnabled())
{
- final String username = identity.getCredentials().getUsername();
+ final String username = credentials.getUsername();
final BoolWrapper userEnabled = new BoolWrapper();
final List<String> roles = new ArrayList<String>();
// Double check our credentials again
- if (tokenStore.validateToken(username, identity.getCredentials().getPassword()))
+ if (tokenStore.validateToken(username, credentials.getPassword()))
{
- new RunAsOperation(true) {
+ identity.runAs(new RunAsOperation(true) {
@Override
public void execute()
{
- if (IdentityManager.instance().isUserEnabled(username))
+ if (identityManager.isUserEnabled(username))
{
userEnabled.value = true;
- for (String role : IdentityManager.instance().getImpliedRoles(username))
+ for (String role : identityManager.getImpliedRoles(username))
{
roles.add(role);
}
}
}
- }.run();
+ });
if (userEnabled.value)
{
@@ -336,8 +334,7 @@
}
}
- @Observer(Identity.EVENT_LOGGED_OUT)
- public void loggedOut()
+ public void loggedOut(@Observes LoggedOutEvent event)
{
if (mode.equals(Mode.autoLogin))
{
@@ -345,8 +342,7 @@
}
}
- @Observer(Identity.EVENT_POST_AUTHENTICATE)
- public void postAuthenticate(Identity identity)
+ public void postAuthenticate(@Observes PostAuthenticateEvent event)
{
if (mode.equals(Mode.usernameOnly))
{
@@ -360,7 +356,7 @@
else
{
usernameSelector.setCookieMaxAge(cookieMaxAge);
- usernameSelector.setCookieValueIfEnabled( Identity.instance().getCredentials().getUsername() );
+ usernameSelector.setCookieValueIfEnabled( credentials.getUsername() );
}
}
else if (mode.equals(Mode.autoLogin))
@@ -390,8 +386,7 @@
}
}
- @Observer(Credentials.EVENT_CREDENTIALS_UPDATED)
- public void credentialsUpdated()
+ public void credentialsUpdated(@Observes CredentialsUpdatedEvent event)
{
if (mode.equals(Mode.usernameOnly))
{
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/RunAsOperation.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/RunAsOperation.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/RunAsOperation.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -69,9 +69,4 @@
{
return systemOp;
}
-
- public void run()
- {
- Identity.instance().runAs(this);
- }
}
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/SecurityInterceptor.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/SecurityInterceptor.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/SecurityInterceptor.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -8,12 +8,14 @@
import java.util.Map;
import java.util.Set;
+import javax.inject.Current;
+import javax.inject.manager.Manager;
import javax.interceptor.Interceptor;
-import org.jboss.seam.annotations.security.PermissionCheck;
-import org.jboss.seam.annotations.security.Restrict;
-import org.jboss.seam.annotations.security.RoleCheck;
-import org.jboss.seam.util.Strings;
+import org.jboss.seam.security.annotations.PermissionCheck;
+import org.jboss.seam.security.annotations.Restrict;
+import org.jboss.seam.security.annotations.RoleCheck;
+import org.jboss.seam.security.util.Strings;
/**
* Provides authorization services for component invocations.
@@ -31,6 +33,8 @@
*/
private transient volatile Map<Method,Restriction> restrictions = new HashMap<Method,Restriction>();
+ @Current Manager manager;
+
private class Restriction
{
private String expression;
@@ -99,20 +103,20 @@
actions.add(action);
}
- public void check(Object[] parameters)
- {
+ public void check(Identity identity, Object[] parameters)
+ {
if (Identity.isSecurityEnabled())
{
if (expression != null)
{
- Identity.instance().checkRestriction(expression);
+ identity.checkRestriction(expression);
}
if (methodRestrictions != null)
{
for (String action : methodRestrictions.keySet())
{
- Identity.instance().checkPermission(methodRestrictions.get(action), action);
+ identity.checkPermission(methodRestrictions.get(action), action);
}
}
@@ -123,7 +127,7 @@
Set<String> actions = paramRestrictions.get(idx);
for (String action : actions)
{
- Identity.instance().checkPermission(parameters[idx], action);
+ identity.checkPermission(parameters[idx], action);
}
}
}
@@ -132,13 +136,13 @@
{
for (String role : roleRestrictions)
{
- Identity.instance().checkRole(role);
+ identity.checkRole(role);
}
}
if (permissionTarget != null && permissionAction != null)
{
- Identity.instance().checkPermission(permissionTarget, permissionAction);
+ identity.checkPermission(permissionTarget, permissionAction);
}
}
}
@@ -152,7 +156,11 @@
if (!"hashCode".equals(interfaceMethod.getName()))
{
Restriction restriction = getRestriction(interfaceMethod);
- if ( restriction != null ) restriction.check(invocation.getParameters());
+ if ( restriction != null )
+ {
+ Identity identity = manager.getInstanceByType(Identity.class);
+ restriction.check(identity, invocation.getParameters());
+ }
}
return invocation.proceed();
Deleted: modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestAuthenticator.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestAuthenticator.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestAuthenticator.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,40 +0,0 @@
-package org.jboss.seam.security.digest;
-
-import org.jboss.seam.contexts.Context;
-import org.jboss.seam.contexts.Contexts;
-import org.jboss.seam.security.Identity;
-
-/**
- * This class provides methods for performing Digest (RFC 2617) authentication
- * and is intended to be extended by a concrete Authenticator implementation.
- *
- * @author Shane Bryzak
- */
-public abstract class DigestAuthenticator
-{
- @SuppressWarnings("deprecation")
- protected boolean validatePassword(String password)
- {
- Context ctx = Contexts.getSessionContext();
-
- DigestRequest digestRequest = (DigestRequest) ctx.get(DigestRequest.DIGEST_REQUEST);
- if (digestRequest == null)
- {
- throw new IllegalStateException("No digest request found in session scope");
- }
-
- // Remove the digest request from the session now
- ctx.remove(DigestRequest.DIGEST_REQUEST);
-
- // Calculate the expected digest
- String serverDigestMd5 = DigestUtils.generateDigest(
- digestRequest.isPasswordAlreadyEncoded(),
- Identity.instance().getUsername(), digestRequest.getRealm(),
- password, digestRequest.getHttpMethod(),
- digestRequest.getUri(), digestRequest.getQop(),
- digestRequest.getNonce(), digestRequest.getNonceCount(),
- digestRequest.getClientNonce());
-
- return serverDigestMd5.equals(digestRequest.getClientDigest());
- }
-}
Deleted: modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestRequest.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestRequest.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestRequest.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,220 +0,0 @@
-package org.jboss.seam.security.digest;
-
-import org.jboss.seam.util.Base64;
-
-public class DigestRequest
-{
- public static final String DIGEST_REQUEST = "org.jboss.seam.security.digestRequest";
-
- private boolean passwordAlreadyEncoded;
- private String systemRealm;
- private String realm;
- private String key;
- private String password;
- private String uri;
-
- /**
- * quality of protection, defined by RFC 2617
- */
- private String qop;
- private String nonce;
- private String nonceCount;
- private String clientNonce;
- private String httpMethod;
-
- /**
- * The digest that the client responds with
- */
- private String clientDigest;
-
- public String getClientNonce()
- {
- return clientNonce;
- }
-
- public void setClientNonce(String clientNonce)
- {
- this.clientNonce = clientNonce;
- }
-
- public String getNonce()
- {
- return nonce;
- }
-
- public void setNonce(String nonce)
- {
- this.nonce = nonce;
- }
-
- public String getNonceCount()
- {
- return nonceCount;
- }
-
- public void setNonceCount(String nonceCount)
- {
- this.nonceCount = nonceCount;
- }
-
- public String getPassword()
- {
- return password;
- }
-
- public void setPassword(String password)
- {
- this.password = password;
- }
-
- public boolean isPasswordAlreadyEncoded()
- {
- return passwordAlreadyEncoded;
- }
-
- public void setPasswordAlreadyEncoded(boolean passwordAlreadyEncoded)
- {
- this.passwordAlreadyEncoded = passwordAlreadyEncoded;
- }
-
- public String getQop()
- {
- return qop;
- }
-
- public void setQop(String qop)
- {
- this.qop = qop;
- }
-
- public String getRealm()
- {
- return realm;
- }
-
- public String getSystemRealm()
- {
- return systemRealm;
- }
-
- public void setSystemRealm(String systemRealm)
- {
- this.systemRealm = systemRealm;
- }
-
- public void setRealm(String realm)
- {
- this.realm = realm;
- }
-
- public String getKey()
- {
- return key;
- }
-
- public void setKey(String key)
- {
- this.key = key;
- }
-
- public String getUri()
- {
- return uri;
- }
-
- public void setUri(String uri)
- {
- this.uri = uri;
- }
-
- public String getHttpMethod()
- {
- return httpMethod;
- }
-
- public void setHttpMethod(String httpMethod)
- {
- this.httpMethod = httpMethod;
- }
-
- public String getClientDigest()
- {
- return clientDigest;
- }
-
- public void setClientDigest(String clientDigest)
- {
- this.clientDigest = clientDigest;
- }
-
- public void validate()
- throws DigestValidationException
- {
- // Check all required parameters were supplied (ie RFC 2069)
- if (realm == null) throw new DigestValidationException("Mandatory field 'realm' not specified");
- if (nonce == null) throw new DigestValidationException("Mandatory field 'nonce' not specified");
- if (uri == null) throw new DigestValidationException("Mandatory field 'uri' not specified");
- if (clientDigest == null) throw new DigestValidationException("Mandatory field 'response' not specified");
-
- // Check all required parameters for an "auth" qop were supplied (ie RFC 2617)
- if ("auth".equals(qop))
- {
- if (nonceCount == null)
- {
- throw new DigestValidationException("Mandatory field 'nc' not specified");
- }
-
- if (clientNonce == null)
- {
- throw new DigestValidationException("Mandatory field 'cnonce' not specified");
- }
- }
-
-
- String nonceAsText = new String(Base64.decode(nonce));
- if (nonceAsText == null)
- {
- throw new DigestValidationException("Nonce is not Base64 encoded - nonce received: " + nonce);
- }
-
- String[] nonceTokens = nonceAsText.split(":");
- if (nonceTokens.length != 2)
- {
- throw new DigestValidationException("Nonce should provide two tokens - nonce received: " + nonce);
- }
-
- // Check realm name equals what we expected
- if (!systemRealm.equals(realm))
- {
- throw new DigestValidationException("Realm name [" + realm +
- "] does not match system realm name [" + systemRealm + "]");
- }
-
- long nonceExpiry = 0;
- try
- {
- nonceExpiry = new Long(nonceTokens[0]).longValue();
- }
- catch (NumberFormatException nfe)
- {
- throw new DigestValidationException("First nonce token should be numeric, but was: " + nonceTokens[0]);
- }
-
-
- // To get this far, the digest must have been valid
- // Check the nonce has not expired
- // We do this last so we can direct the user agent its nonce is stale
- // but the request was otherwise appearing to be valid
- if (nonceExpiry < System.currentTimeMillis())
- {
- throw new DigestValidationException("Nonce has expired", true);
- }
-
- String expectedNonceSignature = DigestUtils.md5Hex(nonceExpiry + ":" + key);
-
- if (!expectedNonceSignature.equals(nonceTokens[1]))
- {
- throw new DigestValidationException("Nonce token invalid: " + nonceAsText);
- }
- }
-}
Deleted: modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestUtils.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestUtils.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestUtils.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,74 +0,0 @@
-package org.jboss.seam.security.digest;
-
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-import org.jboss.seam.util.Hex;
-
-/**
- * Digest-related utility methods, adapted from Acegi and Apache Commons.
- *
- * @author Shane Bryzak
- */
-public class DigestUtils
-{
- public static String generateDigest(boolean passwordAlreadyEncoded, String username,
- String realm, String password, String httpMethod, String uri, String qop, String nonce,
- String nc, String cnonce) throws IllegalArgumentException
- {
- String a1Md5 = null;
- String a2 = httpMethod + ":" + uri;
- String a2Md5 = new String(DigestUtils.md5Hex(a2));
-
- if (passwordAlreadyEncoded)
- {
- a1Md5 = password;
- }
- else
- {
- a1Md5 = encodePasswordInA1Format(username, realm, password);
- }
-
- String digest;
-
- if (qop == null)
- {
- // as per RFC 2069 compliant clients (also reaffirmed by RFC 2617)
- digest = a1Md5 + ":" + nonce + ":" + a2Md5;
- }
- else if ("auth".equals(qop))
- {
- // As per RFC 2617 compliant clients
- digest = a1Md5 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2Md5;
- }
- else
- {
- throw new IllegalArgumentException("This method does not support a qop: '" + qop + "'");
- }
-
- String digestMd5 = new String(DigestUtils.md5Hex(digest));
-
- return digestMd5;
- }
-
- public static String encodePasswordInA1Format(String username, String realm, String password)
- {
- String a1 = username + ":" + realm + ":" + password;
- String a1Md5 = new String(DigestUtils.md5Hex(a1));
-
- return a1Md5;
- }
-
- public static String md5Hex(String value)
- {
- try
- {
- MessageDigest md = MessageDigest.getInstance("MD5");
- return new String(Hex.encodeHex(md.digest(value.getBytes())));
- }
- catch (NoSuchAlgorithmException ex)
- {
- throw new RuntimeException("Invalid algorithm");
- }
- }
-}
Deleted: modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestValidationException.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestValidationException.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/digest/DigestValidationException.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,27 +0,0 @@
-package org.jboss.seam.security.digest;
-
-/**
- * Thrown when a DigestRequest fails validation.
- *
- * @author Shane Bryzak
- */
-public class DigestValidationException extends Exception
-{
- private boolean nonceExpired = false;
-
- public DigestValidationException(String message)
- {
- super(message);
- }
-
- public DigestValidationException(String message, boolean nonceExpired)
- {
- super(message);
- this.nonceExpired = nonceExpired;
- }
-
- public boolean isNonceExpired()
- {
- return nonceExpired;
- }
-}
Deleted: modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenId.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenId.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenId.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,211 +0,0 @@
-package org.jboss.seam.security.openid;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.List;
-
-import javax.faces.context.ExternalContext;
-import javax.faces.context.FacesContext;
-import javax.servlet.http.HttpServletRequest;
-
-import org.jboss.seam.log.*;
-
-import org.jboss.seam.ScopeType;
-import org.jboss.seam.annotations.Create;
-import org.jboss.seam.annotations.Install;
-import org.jboss.seam.annotations.Name;
-import org.jboss.seam.annotations.Scope;
-import org.jboss.seam.faces.FacesManager;
-import org.jboss.seam.faces.Redirect;
-import org.jboss.seam.security.Identity;
-import org.openid4java.OpenIDException;
-import org.openid4java.consumer.ConsumerException;
-import org.openid4java.consumer.ConsumerManager;
-import org.openid4java.consumer.VerificationResult;
-import org.openid4java.discovery.DiscoveryInformation;
-import org.openid4java.discovery.Identifier;
-import org.openid4java.message.AuthRequest;
-import org.openid4java.message.AuthSuccess;
-import org.openid4java.message.ParameterList;
-import org.openid4java.message.ax.AxMessage;
-import org.openid4java.message.ax.FetchRequest;
-import org.openid4java.message.ax.FetchResponse;
-
-@Name("org.jboss.seam.security.openid.openid")
-(a)Install(precedence=Install.BUILT_IN, classDependencies="org.openid4java.consumer.ConsumerManager")
-(a)Scope(ScopeType.SESSION)
-public class OpenId
- implements Serializable
-{
- private transient LogProvider log = Logging.getLogProvider(OpenId.class);
-
- String id;
- String validatedId;
-
- ConsumerManager manager;
- DiscoveryInformation discovered;
-
- @Create
- public void init()
- throws ConsumerException
- {
- manager = new ConsumerManager();
- discovered = null;
- id = null;
- validatedId = null;
- }
-
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
-
- public String returnToUrl() {
- FacesContext context = FacesContext.getCurrentInstance();
- HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
-
- try {
- URL returnToUrl = new URL("http",
- request.getServerName(),
- request.getServerPort(),
- context.getApplication().getViewHandler().getActionURL(context, "/openid.xhtml"));
-
- return returnToUrl.toExternalForm();
- } catch (MalformedURLException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void login() throws IOException {
- validatedId = null;
- String returnToUrl = returnToUrl();
-
- String url = authRequest(id, returnToUrl);
-
- if (url != null) {
- Redirect redirect = Redirect.instance();
- redirect.captureCurrentView();
-
- FacesManager.instance().redirectToExternalURL(url);
- }
- }
-
- // --- placing the authentication request ---
- @SuppressWarnings("unchecked")
- protected String authRequest(String userSuppliedString, String returnToUrl)
- throws IOException
- {
- try {
- // perform discovery on the user-supplied identifier
- List discoveries = manager.discover(userSuppliedString);
-
- // attempt to associate with the OpenID provider
- // and retrieve one service endpoint for authentication
- discovered = manager.associate(discoveries);
-
- //// store the discovery information in the user's session
- // httpReq.getSession().setAttribute("openid-disc", discovered);
-
- // obtain a AuthRequest message to be sent to the OpenID provider
- AuthRequest authReq = manager.authenticate(discovered, returnToUrl);
-
- // Attribute Exchange example: fetching the 'email' attribute
- FetchRequest fetch = FetchRequest.createFetchRequest();
- fetch.addAttribute("email",
- "http://schema.openid.net/contact/email", // type URI
- true); // required
-
- // attach the extension to the authentication request
- authReq.addExtension(fetch);
-
- return authReq.getDestinationUrl(true);
- } catch (OpenIDException e) {
- log.error(e);
- }
-
- return null;
- }
-
- public void verify()
- {
- ExternalContext context = javax.faces.context.FacesContext.getCurrentInstance().getExternalContext();
- HttpServletRequest request = (HttpServletRequest) context.getRequest();
-
- validatedId = verifyResponse(request);
- }
-
-
- public boolean loginImmediately() {
- if (validatedId !=null) {
- Identity.instance().acceptExternallyAuthenticatedPrincipal((new OpenIdPrincipal(validatedId)));
- return true;
- }
-
- return false;
- }
-
- public boolean isValid() {
- return validatedId != null;
- }
-
- public String getValidatedId() {
- return validatedId;
- }
-
- @SuppressWarnings("unchecked")
- public String verifyResponse(HttpServletRequest httpReq)
- {
- try {
- // extract the parameters from the authentication response
- // (which comes in as a HTTP request from the OpenID provider)
- ParameterList response =
- new ParameterList(httpReq.getParameterMap());
-
- // extract the receiving URL from the HTTP request
- StringBuffer receivingURL = httpReq.getRequestURL();
- String queryString = httpReq.getQueryString();
- if (queryString != null && queryString.length() > 0)
- receivingURL.append("?").append(httpReq.getQueryString());
-
- // verify the response; ConsumerManager needs to be the same
- // (static) instance used to place the authentication request
- VerificationResult verification = manager.verify(
- receivingURL.toString(),
- response, discovered);
-
- // examine the verification result and extract the verified identifier
- Identifier verified = verification.getVerifiedId();
- if (verified != null) {
-// AuthSuccess authSuccess =
-// (AuthSuccess) verification.getAuthResponse();
-
-// if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
-// FetchResponse fetchResp = (FetchResponse) authSuccess
-// .getExtension(AxMessage.OPENID_NS_AX);
-//
-// List emails = fetchResp.getAttributeValues("email");
-// String email = (String) emails.get(0);
-// }
-
- return verified.getIdentifier();
- }
- } catch (OpenIDException e) {
- // present error to the user
- }
-
- return null;
- }
-
- public void logout()
- throws ConsumerException
- {
- init();
- }
-}
Deleted: modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenIdPhaseListener.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenIdPhaseListener.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenIdPhaseListener.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,81 +0,0 @@
-package org.jboss.seam.security.openid;
-
-
-import java.io.IOException;
-import java.io.PrintWriter;
-
-import javax.faces.context.ExternalContext;
-import javax.faces.context.FacesContext;
-import javax.faces.event.PhaseEvent;
-import javax.faces.event.PhaseId;
-import javax.faces.event.PhaseListener;
-import javax.servlet.http.HttpServletResponse;
-
-import org.jboss.seam.Component;
-import org.jboss.seam.navigation.Pages;
-import org.jboss.seam.log.*;
-
-@SuppressWarnings("serial")
-public class OpenIdPhaseListener
- implements PhaseListener
-{
- private transient LogProvider log = Logging.getLogProvider(OpenIdPhaseListener.class);
-
- @SuppressWarnings("unchecked")
- public void beforePhase(PhaseEvent event)
- {
- String viewId = Pages.getCurrentViewId();
-
- if (viewId==null || !viewId.startsWith("/openid.")) {
- return;
- }
-
- OpenId open = (OpenId) Component.getInstance(OpenId.class);
- if (open.getId() == null) {
- try {
- sendXRDS();
- } catch (IOException e) {
- log.error(e);
- }
- return;
- }
-
- OpenId openid = (OpenId) Component.getInstance(OpenId.class);
-
- openid.verify();
-
- Pages.handleOutcome(event.getFacesContext(), null, "/openid.xhtml");
- }
-
-
-
- public void sendXRDS()
- throws IOException
- {
- FacesContext context = FacesContext.getCurrentInstance();
- ExternalContext extContext = context.getExternalContext();
- HttpServletResponse response = (HttpServletResponse) extContext.getResponse();
-
- response.setContentType("application/xrds+xml");
- PrintWriter out = response.getWriter();
-
- // XXX ENCODE THE URL!
- OpenId open = (OpenId) Component.getInstance(OpenId.class);
-
- out.println("<XRDS xmlns=\"xri://$xrd*($v*2.0)\"><XRD><Service>" +
- "<Type>http://specs.openid.net/auth/2.0/return_to</Type><URI>" +
- open.returnToUrl() + "</URI></Service></XRD></XRDS>");
-
- context.responseComplete();
- }
-
-
- public void afterPhase(PhaseEvent event) {
- }
-
- public PhaseId getPhaseId()
- {
- return PhaseId.RENDER_RESPONSE;
- }
-}
-
Deleted: modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenIdPrincipal.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenIdPrincipal.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/openid/OpenIdPrincipal.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,11 +0,0 @@
-package org.jboss.seam.security.openid;
-
-import org.jboss.seam.security.SimplePrincipal;
-
-public class OpenIdPrincipal
- extends SimplePrincipal
-{
- public OpenIdPrincipal(String name) {
- super(name);
- }
-}
Deleted: modules/trunk/security/src/main/java/org/jboss/seam/security/package-info.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/package-info.java 2009-04-23 01:09:57 UTC (rev 10602)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/package-info.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -1,12 +0,0 @@
-/**
- * Seam Security
- *
- * @see org.jboss.seam.security.Identity
- * @see org.jboss.seam.annotations.security.Restrict
- */
-@Namespace(value="http://jboss.com/products/seam/security", prefix="org.jboss.seam.security")
-@AutoCreate
-package org.jboss.seam.security;
-
-import org.jboss.seam.annotations.AutoCreate;
-import org.jboss.seam.annotations.Namespace;
Added: modules/trunk/security/src/main/java/org/jboss/seam/security/util/Base64.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/util/Base64.java (rev 0)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/util/Base64.java 2009-04-23 01:11:25 UTC (rev 10603)
@@ -0,0 +1,1771 @@
+package org.jboss.seam.security.util;
+
+/**
+ * <p>Encodes and decodes to and from Base64 notation.</p>
+ * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
+ *
+ * <p>
+ * Change Log:
+ * </p>
+ * <ul>
+ * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
+ * when using very small files (~< 40 bytes).</li>
+ * <li>v2.2 - Added some helper methods for encoding/decoding directly from
+ * one file to the next. Also added a main() method to support command line
+ * encoding/decoding from one file to the next. Also added these Base64 dialects:
+ * <ol>
+ * <li>The default is RFC3548 format.</li>
+ * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
+ * URL and file name friendly format as described in Section 4 of RFC3548.
+ * http://www.faqs.org/rfcs/rfc3548.html</li>
+ * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
+ * URL and file name friendly format that preserves lexical ordering as described
+ * in http://www.faqs.org/qa/rfcc-1940.html</li>
+ * </ol>
+ * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
+ * for contributing the new Base64 dialects.
+ * </li>
+ *
+ * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
+ * some convenience methods for reading and writing to and from files.</li>
+ * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
+ * with other encodings (like EBCDIC).</li>
+ * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
+ * encoded data was a single byte.</li>
+ * <li>v2.0 - I got rid of methods that used booleans to set options.
+ * Now everything is more consolidated and cleaner. The code now detects
+ * when data that's being decoded is gzip-compressed and will decompress it
+ * automatically. Generally things are cleaner. You'll probably have to
+ * change some method calls that you were making to support the new
+ * options format (<tt>int</tt>s that you "OR" together).</li>
+ * <li>v1.5.1 - Fixed bug when decompressing and decoding to a
+ * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
+ * Added the ability to "suspend" encoding in the Output Stream so
+ * you can turn on and off the encoding if you need to embed base64
+ * data in an otherwise "normal" stream (like an XML file).</li>
+ * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
+ * This helps when using GZIP streams.
+ * Added the ability to GZip-compress objects before encoding them.</li>
+ * <li>v1.4 - Added helper methods to read/write files.</li>
+ * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
+ * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
+ * where last buffer being read, if not completely full, was not returned.</li>
+ * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
+ * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
+ * </ul>
+ *
+ * <p>
+ * I am placing this code in the Public Domain. Do with it as you will.
+ * This software comes with no guarantees or warranties but with
+ * plenty of well-wishing instead!
+ * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
+ * periodically to check for updates or to contribute improvements.
+ * </p>
+ *
+ * @author Robert Harder
+ * @author rob(a)iharder.net
+ * @version 2.2.1
+ */
+public class Base64
+{
+
+/* ******** P U B L I C F I E L D S ******** */
+
+
+ /** No options specified. Value is zero. */
+ public final static int NO_OPTIONS = 0;
+
+ /** Specify encoding. */
+ public final static int ENCODE = 1;
+
+
+ /** Specify decoding. */
+ public final static int DECODE = 0;
+
+
+ /** Specify that data should be gzip-compressed. */
+ public final static int GZIP = 2;
+
+
+ /** Don't break lines when encoding (violates strict Base64 specification) */
+ public final static int DONT_BREAK_LINES = 8;
+
+ /**
+ * Encode using Base64-like encoding that is URL- and Filename-safe as described
+ * in Section 4 of RFC3548:
+ * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
+ * It is important to note that data encoded this way is <em>not</em> officially valid Base64,
+ * or at the very least should not be called Base64 without also specifying that is
+ * was encoded using the URL- and Filename-safe dialect.
+ */
+ public final static int URL_SAFE = 16;
+
+
+ /**
+ * Encode using the special "ordered" dialect of Base64 described here:
+ * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
+ */
+ public final static int ORDERED = 32;
+
+
+/* ******** P R I V A T E F I E L D S ******** */
+
+
+ /** Maximum line length (76) of Base64 output. */
+ private final static int MAX_LINE_LENGTH = 76;
+
+
+ /** The equals sign (=) as a byte. */
+ private final static byte EQUALS_SIGN = (byte)'=';
+
+
+ /** The new line character (\n) as a byte. */
+ private final static byte NEW_LINE = (byte)'\n';
+
+
+ /** Preferred encoding. */
+ private final static String PREFERRED_ENCODING = "UTF-8";
+
+
+ // I think I end up not using the BAD_ENCODING indicator.
+ //private final static byte BAD_ENCODING = -9; // Indicates error in encoding
+ private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
+ private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
+
+
+/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
+
+ /** The 64 valid Base64 values. */
+ //private final static byte[] ALPHABET;
+ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
+ private final static byte[] _STANDARD_ALPHABET =
+ {
+ (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
+ (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
+ (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
+ (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
+ (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
+ (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
+ (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
+ (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
+ (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
+ };
+
+
+ /**
+ * Translates a Base64 value to either its 6-bit reconstruction value
+ * or a negative number indicating some other meaning.
+ **/
+ private final static byte[] _STANDARD_DECODABET =
+ {
+ -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
+ -5,-5, // Whitespace: Tab and Linefeed
+ -9,-9, // Decimal 11 - 12
+ -5, // Whitespace: Carriage Return
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
+ -9,-9,-9,-9,-9, // Decimal 27 - 31
+ -5, // Whitespace: Space
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
+ 62, // Plus sign at decimal 43
+ -9,-9,-9, // Decimal 44 - 46
+ 63, // Slash at decimal 47
+ 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
+ -9,-9,-9, // Decimal 58 - 60
+ -1, // Equals sign at decimal 61
+ -9,-9,-9, // Decimal 62 - 64
+ 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
+ 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
+ -9,-9,-9,-9,-9,-9, // Decimal 91 - 96
+ 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
+ 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
+ -9,-9,-9,-9 // Decimal 123 - 126
+ /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
+ };
+
+
+/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
+
+ /**
+ * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
+ * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
+ * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
+ */
+ private final static byte[] _URL_SAFE_ALPHABET =
+ {
+ (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
+ (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
+ (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
+ (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
+ (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
+ (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
+ (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
+ (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
+ (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
+ };
+
+ /**
+ * Used in decoding URL- and Filename-safe dialects of Base64.
+ */
+ private final static byte[] _URL_SAFE_DECODABET =
+ {
+ -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
+ -5,-5, // Whitespace: Tab and Linefeed
+ -9,-9, // Decimal 11 - 12
+ -5, // Whitespace: Carriage Return
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
+ -9,-9,-9,-9,-9, // Decimal 27 - 31
+ -5, // Whitespace: Space
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
+ -9, // Plus sign at decimal 43
+ -9, // Decimal 44
+ 62, // Minus sign at decimal 45
+ -9, // Decimal 46
+ -9, // Slash at decimal 47
+ 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
+ -9,-9,-9, // Decimal 58 - 60
+ -1, // Equals sign at decimal 61
+ -9,-9,-9, // Decimal 62 - 64
+ 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
+ 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
+ -9,-9,-9,-9, // Decimal 91 - 94
+ 63, // Underscore at decimal 95
+ -9, // Decimal 96
+ 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
+ 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
+ -9,-9,-9,-9 // Decimal 123 - 126
+ /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
+ };
+
+
+
+/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
+
+ /**
+ * I don't get the point of this technique, but it is described here:
+ * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
+ */
+ private final static byte[] _ORDERED_ALPHABET =
+ {
+ (byte)'-',
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
+ (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
+ (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
+ (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
+ (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
+ (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
+ (byte)'_',
+ (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
+ (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
+ (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
+ (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
+ };
+
+ /**
+ * Used in decoding the "ordered" dialect of Base64.
+ */
+ private final static byte[] _ORDERED_DECODABET =
+ {
+ -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
+ -5,-5, // Whitespace: Tab and Linefeed
+ -9,-9, // Decimal 11 - 12
+ -5, // Whitespace: Carriage Return
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
+ -9,-9,-9,-9,-9, // Decimal 27 - 31
+ -5, // Whitespace: Space
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
+ -9, // Plus sign at decimal 43
+ -9, // Decimal 44
+ 0, // Minus sign at decimal 45
+ -9, // Decimal 46
+ -9, // Slash at decimal 47
+ 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
+ -9,-9,-9, // Decimal 58 - 60
+ -1, // Equals sign at decimal 61
+ -9,-9,-9, // Decimal 62 - 64
+ 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
+ 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
+ -9,-9,-9,-9, // Decimal 91 - 94
+ 37, // Underscore at decimal 95
+ -9, // Decimal 96
+ 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
+ 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
+ -9,-9,-9,-9 // Decimal 123 - 126
+ /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
+ };
+
+
+/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
+
+
+ /**
+ * Returns one of the _SOMETHING_ALPHABET byte arrays depending on
+ * the options specified.
+ * It's possible, though silly, to specify ORDERED and URLSAFE
+ * in which case one of them will be picked, though there is
+ * no guarantee as to which one will be picked.
+ */
+ private final static byte[] getAlphabet( int options )
+ {
+ if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_ALPHABET;
+ else if( (options & ORDERED) == ORDERED ) return _ORDERED_ALPHABET;
+ else return _STANDARD_ALPHABET;
+
+ } // end getAlphabet
+
+
+ /**
+ * Returns one of the _SOMETHING_DECODABET byte arrays depending on
+ * the options specified.
+ * It's possible, though silly, to specify ORDERED and URL_SAFE
+ * in which case one of them will be picked, though there is
+ * no guarantee as to which one will be picked.
+ */
+ private final static byte[] getDecodabet( int options )
+ {
+ if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_DECODABET;
+ else if( (options & ORDERED) == ORDERED ) return _ORDERED_DECODABET;
+ else return _STANDARD_DECODABET;
+
+ } // end getAlphabet
+
+
+
+ /** Defeats instantiation. */
+ private Base64(){}
+
+
+ /**
+ * Encodes or decodes two files from the command line;
+ * <strong>feel free to delete this method (in fact you probably should)
+ * if you're embedding this code into a larger program.</strong>
+ */
+ public final static void main( String[] args )
+ {
+ if( args.length < 3 ){
+ usage("Not enough arguments.");
+ } // end if: args.length < 3
+ else {
+ String flag = args[0];
+ String infile = args[1];
+ String outfile = args[2];
+ if( flag.equals( "-e" ) ){
+ Base64.encodeFileToFile( infile, outfile );
+ } // end if: encode
+ else if( flag.equals( "-d" ) ) {
+ Base64.decodeFileToFile( infile, outfile );
+ } // end else if: decode
+ else {
+ usage( "Unknown flag: " + flag );
+ } // end else
+ } // end else
+ } // end main
+
+ /**
+ * Prints command line usage.
+ *
+ * @param msg A message to include with usage info.
+ */
+ private final static void usage( String msg )
+ {
+ System.err.println( msg );
+ System.err.println( "Usage: java Base64 -e|-d inputfile outputfile" );
+ } // end usage
+
+
+/* ******** E N C O D I N G M E T H O D S ******** */
+
+
+ /**
+ * Encodes up to the first three bytes of array <var>threeBytes</var>
+ * and returns a four-byte array in Base64 notation.
+ * The actual number of significant bytes in your array is
+ * given by <var>numSigBytes</var>.
+ * The array <var>threeBytes</var> needs only be as big as
+ * <var>numSigBytes</var>.
+ * Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
+ *
+ * @param b4 A reusable byte array to reduce array instantiation
+ * @param threeBytes the array to convert
+ * @param numSigBytes the number of significant bytes in your array
+ * @return four byte array in Base64 notation.
+ * @since 1.5.1
+ */
+ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options )
+ {
+ encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
+ return b4;
+ } // end encode3to4
+
+
+ /**
+ * <p>Encodes up to three bytes of the array <var>source</var>
+ * and writes the resulting four Base64 bytes to <var>destination</var>.
+ * The source and destination arrays can be manipulated
+ * anywhere along their length by specifying
+ * <var>srcOffset</var> and <var>destOffset</var>.
+ * This method does not check to make sure your arrays
+ * are large enough to accomodate <var>srcOffset</var> + 3 for
+ * the <var>source</var> array or <var>destOffset</var> + 4 for
+ * the <var>destination</var> array.
+ * The actual number of significant bytes in your array is
+ * given by <var>numSigBytes</var>.</p>
+ * <p>This is the lowest level of the encoding methods with
+ * all possible parameters.</p>
+ *
+ * @param source the array to convert
+ * @param srcOffset the index where conversion begins
+ * @param numSigBytes the number of significant bytes in your array
+ * @param destination the array to hold the conversion
+ * @param destOffset the index where output will be put
+ * @return the <var>destination</var> array
+ * @since 1.3
+ */
+ private static byte[] encode3to4(
+ byte[] source, int srcOffset, int numSigBytes,
+ byte[] destination, int destOffset, int options )
+ {
+ byte[] ALPHABET = getAlphabet( options );
+
+ // 1 2 3
+ // 01234567890123456789012345678901 Bit position
+ // --------000000001111111122222222 Array position from threeBytes
+ // --------| || || || | Six bit groups to index ALPHABET
+ // >>18 >>12 >> 6 >> 0 Right shift necessary
+ // 0x3f 0x3f 0x3f Additional AND
+
+ // Create buffer with zero-padding if there are only one or two
+ // significant bytes passed in the array.
+ // We have to shift left 24 in order to flush out the 1's that appear
+ // when Java treats a value as negative that is cast from a byte to an int.
+ int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
+ | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
+ | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
+
+ switch( numSigBytes )
+ {
+ case 3:
+ destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
+ destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
+ destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
+ destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
+ return destination;
+
+ case 2:
+ destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
+ destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
+ destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
+ destination[ destOffset + 3 ] = EQUALS_SIGN;
+ return destination;
+
+ case 1:
+ destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
+ destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
+ destination[ destOffset + 2 ] = EQUALS_SIGN;
+ destination[ destOffset + 3 ] = EQUALS_SIGN;
+ return destination;
+
+ default:
+ return destination;
+ } // end switch
+ } // end encode3to4
+
+
+
+ /**
+ * Serializes an object and returns the Base64-encoded
+ * version of that serialized object. If the object
+ * cannot be serialized or there is another error,
+ * the method will return <tt>null</tt>.
+ * The object is not GZip-compressed before being encoded.
+ *
+ * @param serializableObject The object to encode
+ * @return The Base64-encoded object
+ * @since 1.4
+ */
+ public static String encodeObject( java.io.Serializable serializableObject )
+ {
+ return encodeObject( serializableObject, NO_OPTIONS );
+ } // end encodeObject
+
+
+
+ /**
+ * Serializes an object and returns the Base64-encoded
+ * version of that serialized object. If the object
+ * cannot be serialized or there is another error,
+ * the method will return <tt>null</tt>.
+ * <p>
+ * Valid options:<pre>
+ * GZIP: gzip-compresses object before encoding it.
+ * DONT_BREAK_LINES: don't break lines at 76 characters
+ * <i>Note: Technically, this makes your encoding non-compliant.</i>
+ * </pre>
+ * <p>
+ * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
+ * <p>
+ * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
+ *
+ * @param serializableObject The object to encode
+ * @param options Specified options
+ * @return The Base64-encoded object
+ * @see Base64#GZIP
+ * @see Base64#DONT_BREAK_LINES
+ * @since 2.0
+ */
+ public static String encodeObject( java.io.Serializable serializableObject, int options )
+ {
+ // Streams
+ java.io.ByteArrayOutputStream baos = null;
+ java.io.OutputStream b64os = null;
+ java.io.ObjectOutputStream oos = null;
+ java.util.zip.GZIPOutputStream gzos = null;
+
+ // Isolate options
+ int gzip = (options & GZIP);
+ //int dontBreakLines = (options & DONT_BREAK_LINES);
+
+ try
+ {
+ // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
+ baos = new java.io.ByteArrayOutputStream();
+ b64os = new Base64.OutputStream( baos, ENCODE | options );
+
+ // GZip?
+ if( gzip == GZIP )
+ {
+ gzos = new java.util.zip.GZIPOutputStream( b64os );
+ oos = new java.io.ObjectOutputStream( gzos );
+ } // end if: gzip
+ else
+ oos = new java.io.ObjectOutputStream( b64os );
+
+ oos.writeObject( serializableObject );
+ } // end try
+ catch( java.io.IOException e )
+ {
+ e.printStackTrace();
+ return null;
+ } // end catch
+ finally
+ {
+ try{ oos.close(); } catch( Exception e ){}
+ try{ gzos.close(); } catch( Exception e ){}
+ try{ b64os.close(); } catch( Exception e ){}
+ try{ baos.close(); } catch( Exception e ){}
+ } // end finally
+
+ // Return value according to relevant encoding.
+ try
+ {
+ return new String( baos.toByteArray(), PREFERRED_ENCODING );
+ } // end try
+ catch (java.io.UnsupportedEncodingException uue)
+ {
+ return new String( baos.toByteArray() );
+ } // end catch
+
+ } // end encode
+
+
+
+ /**
+ * Encodes a byte array into Base64 notation.
+ * Does not GZip-compress data.
+ *
+ * @param source The data to convert
+ * @since 1.4
+ */
+ public static String encodeBytes( byte[] source )
+ {
+ return encodeBytes( source, 0, source.length, NO_OPTIONS );
+ } // end encodeBytes
+
+
+
+ /**
+ * Encodes a byte array into Base64 notation.
+ * <p>
+ * Valid options:<pre>
+ * GZIP: gzip-compresses object before encoding it.
+ * DONT_BREAK_LINES: don't break lines at 76 characters
+ * <i>Note: Technically, this makes your encoding non-compliant.</i>
+ * </pre>
+ * <p>
+ * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
+ * <p>
+ * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
+ *
+ *
+ * @param source The data to convert
+ * @param options Specified options
+ * @see Base64#GZIP
+ * @see Base64#DONT_BREAK_LINES
+ * @since 2.0
+ */
+ public static String encodeBytes( byte[] source, int options )
+ {
+ return encodeBytes( source, 0, source.length, options );
+ } // end encodeBytes
+
+
+ /**
+ * Encodes a byte array into Base64 notation.
+ * Does not GZip-compress data.
+ *
+ * @param source The data to convert
+ * @param off Offset in array where conversion should begin
+ * @param len Length of data to convert
+ * @since 1.4
+ */
+ public static String encodeBytes( byte[] source, int off, int len )
+ {
+ return encodeBytes( source, off, len, NO_OPTIONS );
+ } // end encodeBytes
+
+
+
+ /**
+ * Encodes a byte array into Base64 notation.
+ * <p>
+ * Valid options:<pre>
+ * GZIP: gzip-compresses object before encoding it.
+ * DONT_BREAK_LINES: don't break lines at 76 characters
+ * <i>Note: Technically, this makes your encoding non-compliant.</i>
+ * </pre>
+ * <p>
+ * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
+ * <p>
+ * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
+ *
+ *
+ * @param source The data to convert
+ * @param off Offset in array where conversion should begin
+ * @param len Length of data to convert
+ * @param options Specified options, alphabet type is pulled from this (standard, url-safe, ordered)
+ * @see Base64#GZIP
+ * @see Base64#DONT_BREAK_LINES
+ * @since 2.0
+ */
+ public static String encodeBytes( byte[] source, int off, int len, int options )
+ {
+ // Isolate options
+ int dontBreakLines = ( options & DONT_BREAK_LINES );
+ int gzip = ( options & GZIP );
+
+ // Compress?
+ if( gzip == GZIP )
+ {
+ java.io.ByteArrayOutputStream baos = null;
+ java.util.zip.GZIPOutputStream gzos = null;
+ Base64.OutputStream b64os = null;
+
+
+ try
+ {
+ // GZip -> Base64 -> ByteArray
+ baos = new java.io.ByteArrayOutputStream();
+ b64os = new Base64.OutputStream( baos, ENCODE | options );
+ gzos = new java.util.zip.GZIPOutputStream( b64os );
+
+ gzos.write( source, off, len );
+ gzos.close();
+ } // end try
+ catch( java.io.IOException e )
+ {
+ e.printStackTrace();
+ return null;
+ } // end catch
+ finally
+ {
+ try{ gzos.close(); } catch( Exception e ){}
+ try{ b64os.close(); } catch( Exception e ){}
+ try{ baos.close(); } catch( Exception e ){}
+ } // end finally
+
+ // Return value according to relevant encoding.
+ try
+ {
+ return new String( baos.toByteArray(), PREFERRED_ENCODING );
+ } // end try
+ catch (java.io.UnsupportedEncodingException uue)
+ {
+ return new String( baos.toByteArray() );
+ } // end catch
+ } // end if: compress
+
+ // Else, don't compress. Better not to use streams at all then.
+ else
+ {
+ // Convert option to boolean in way that code likes it.
+ boolean breakLines = dontBreakLines == 0;
+
+ int len43 = len * 4 / 3;
+ byte[] outBuff = new byte[ ( len43 ) // Main 4:3
+ + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
+ + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
+ int d = 0;
+ int e = 0;
+ int len2 = len - 2;
+ int lineLength = 0;
+ for( ; d < len2; d+=3, e+=4 )
+ {
+ encode3to4( source, d+off, 3, outBuff, e, options );
+
+ lineLength += 4;
+ if( breakLines && lineLength == MAX_LINE_LENGTH )
+ {
+ outBuff[e+4] = NEW_LINE;
+ e++;
+ lineLength = 0;
+ } // end if: end of line
+ } // en dfor: each piece of array
+
+ if( d < len )
+ {
+ encode3to4( source, d+off, len - d, outBuff, e, options );
+ e += 4;
+ } // end if: some padding needed
+
+
+ // Return value according to relevant encoding.
+ try
+ {
+ return new String( outBuff, 0, e, PREFERRED_ENCODING );
+ } // end try
+ catch (java.io.UnsupportedEncodingException uue)
+ {
+ return new String( outBuff, 0, e );
+ } // end catch
+
+ } // end else: don't compress
+
+ } // end encodeBytes
+
+
+
+
+
+/* ******** D E C O D I N G M E T H O D S ******** */
+
+
+ /**
+ * Decodes four bytes from array <var>source</var>
+ * and writes the resulting bytes (up to three of them)
+ * to <var>destination</var>.
+ * The source and destination arrays can be manipulated
+ * anywhere along their length by specifying
+ * <var>srcOffset</var> and <var>destOffset</var>.
+ * This method does not check to make sure your arrays
+ * are large enough to accomodate <var>srcOffset</var> + 4 for
+ * the <var>source</var> array or <var>destOffset</var> + 3 for
+ * the <var>destination</var> array.
+ * This method returns the actual number of bytes that
+ * were converted from the Base64 encoding.
+ * <p>This is the lowest level of the decoding methods with
+ * all possible parameters.</p>
+ *
+ *
+ * @param source the array to convert
+ * @param srcOffset the index where conversion begins
+ * @param destination the array to hold the conversion
+ * @param destOffset the index where output will be put
+ * @param options alphabet type is pulled from this (standard, url-safe, ordered)
+ * @return the number of decoded bytes converted
+ * @since 1.3
+ */
+ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options )
+ {
+ byte[] DECODABET = getDecodabet( options );
+
+ // Example: Dk==
+ if( source[ srcOffset + 2] == EQUALS_SIGN )
+ {
+ // Two ways to do the same thing. Don't know which way I like best.
+ //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
+ // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
+ int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
+ | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
+
+ destination[ destOffset ] = (byte)( outBuff >>> 16 );
+ return 1;
+ }
+
+ // Example: DkL=
+ else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
+ {
+ // Two ways to do the same thing. Don't know which way I like best.
+ //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
+ // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
+ // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
+ int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
+ | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
+ | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
+
+ destination[ destOffset ] = (byte)( outBuff >>> 16 );
+ destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
+ return 2;
+ }
+
+ // Example: DkLE
+ else
+ {
+ try{
+ // Two ways to do the same thing. Don't know which way I like best.
+ //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
+ // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
+ // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
+ // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
+ int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
+ | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
+ | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
+ | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
+
+
+ destination[ destOffset ] = (byte)( outBuff >> 16 );
+ destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
+ destination[ destOffset + 2 ] = (byte)( outBuff );
+
+ return 3;
+ }catch( Exception e){
+// System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
+// System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
+// System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
+// System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
+ return -1;
+ } // end catch
+ }
+ } // end decodeToBytes
+
+
+
+
+ /**
+ * Very low-level access to decoding ASCII characters in
+ * the form of a byte array. Does not support automatically
+ * gunzipping or any other "fancy" features.
+ *
+ * @param source The Base64 encoded data
+ * @param off The offset of where to begin decoding
+ * @param len The length of characters to decode
+ * @return decoded data
+ * @since 1.3
+ */
+ public static byte[] decode( byte[] source, int off, int len, int options )
+ {
+ byte[] DECODABET = getDecodabet( options );
+
+ int len34 = len * 3 / 4;
+ byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
+ int outBuffPosn = 0;
+
+ byte[] b4 = new byte[4];
+ int b4Posn = 0;
+ int i = 0;
+ byte sbiCrop = 0;
+ byte sbiDecode = 0;
+ for( i = off; i < off+len; i++ )
+ {
+ sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
+ sbiDecode = DECODABET[ sbiCrop ];
+
+ if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
+ {
+ if( sbiDecode >= EQUALS_SIGN_ENC )
+ {
+ b4[ b4Posn++ ] = sbiCrop;
+ if( b4Posn > 3 )
+ {
+ outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
+ b4Posn = 0;
+
+ // If that was the equals sign, break out of 'for' loop
+ if( sbiCrop == EQUALS_SIGN )
+ break;
+ } // end if: quartet built
+
+ } // end if: equals sign or better
+
+ } // end if: white space, equals sign or better
+ else
+ {
+ System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
+ return null;
+ } // end else:
+ } // each input character
+
+ byte[] out = new byte[ outBuffPosn ];
+ System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
+ return out;
+ } // end decode
+
+
+
+
+ /**
+ * Decodes data from Base64 notation, automatically
+ * detecting gzip-compressed data and decompressing it.
+ *
+ * @param s the string to decode
+ * @return the decoded data
+ * @since 1.4
+ */
+ public static byte[] decode( String s )
+ {
+ return decode( s, NO_OPTIONS );
+ }
+
+
+ /**
+ * Decodes data from Base64 notation, automatically
+ * detecting gzip-compressed data and decompressing it.
+ *
+ * @param s the string to decode
+ * @param options encode options such as URL_SAFE
+ * @return the decoded data
+ * @since 1.4
+ */
+ public static byte[] decode( String s, int options )
+ {
+ byte[] bytes;
+ try
+ {
+ bytes = s.getBytes( PREFERRED_ENCODING );
+ } // end try
+ catch( java.io.UnsupportedEncodingException uee )
+ {
+ bytes = s.getBytes();
+ } // end catch
+ //</change>
+
+ // Decode
+ bytes = decode( bytes, 0, bytes.length, options );
+
+
+ // Check to see if it's gzip-compressed
+ // GZIP Magic Two-Byte Number: 0x8b1f (35615)
+ if( bytes != null && bytes.length >= 4 )
+ {
+
+ int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
+ if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
+ {
+ java.io.ByteArrayInputStream bais = null;
+ java.util.zip.GZIPInputStream gzis = null;
+ java.io.ByteArrayOutputStream baos = null;
+ byte[] buffer = new byte[2048];
+ int length = 0;
+
+ try
+ {
+ baos = new java.io.ByteArrayOutputStream();
+ bais = new java.io.ByteArrayInputStream( bytes );
+ gzis = new java.util.zip.GZIPInputStream( bais );
+
+ while( ( length = gzis.read( buffer ) ) >= 0 )
+ {
+ baos.write(buffer,0,length);
+ } // end while: reading input
+
+ // No error? Get new bytes.
+ bytes = baos.toByteArray();
+
+ } // end try
+ catch( java.io.IOException e )
+ {
+ // Just return originally-decoded bytes
+ } // end catch
+ finally
+ {
+ try{ baos.close(); } catch( Exception e ){}
+ try{ gzis.close(); } catch( Exception e ){}
+ try{ bais.close(); } catch( Exception e ){}
+ } // end finally
+
+ } // end if: gzipped
+ } // end if: bytes.length >= 2
+
+ return bytes;
+ } // end decode
+
+
+
+
+ /**
+ * Attempts to decode Base64 data and deserialize a Java
+ * Object within. Returns <tt>null</tt> if there was an error.
+ *
+ * @param encodedObject The Base64 data to decode
+ * @return The decoded and deserialized object
+ * @since 1.5
+ */
+ public static Object decodeToObject( String encodedObject )
+ {
+ // Decode and gunzip if necessary
+ byte[] objBytes = decode( encodedObject );
+
+ java.io.ByteArrayInputStream bais = null;
+ java.io.ObjectInputStream ois = null;
+ Object obj = null;
+
+ try
+ {
+ bais = new java.io.ByteArrayInputStream( objBytes );
+ ois = new java.io.ObjectInputStream( bais );
+
+ obj = ois.readObject();
+ } // end try
+ catch( java.io.IOException e )
+ {
+ e.printStackTrace();
+ obj = null;
+ } // end catch
+ catch( java.lang.ClassNotFoundException e )
+ {
+ e.printStackTrace();
+ obj = null;
+ } // end catch
+ finally
+ {
+ try{ bais.close(); } catch( Exception e ){}
+ try{ ois.close(); } catch( Exception e ){}
+ } // end finally
+
+ return obj;
+ } // end decodeObject
+
+
+
+ /**
+ * Convenience method for encoding data to a file.
+ *
+ * @param dataToEncode byte array of data to encode in base64 form
+ * @param filename Filename for saving encoded data
+ * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
+ *
+ * @since 2.1
+ */
+ public static boolean encodeToFile( byte[] dataToEncode, String filename )
+ {
+ boolean success = false;
+ Base64.OutputStream bos = null;
+ try
+ {
+ bos = new Base64.OutputStream(
+ new java.io.FileOutputStream( filename ), Base64.ENCODE );
+ bos.write( dataToEncode );
+ success = true;
+ } // end try
+ catch( java.io.IOException e )
+ {
+
+ success = false;
+ } // end catch: IOException
+ finally
+ {
+ try{ bos.close(); } catch( Exception e ){}
+ } // end finally
+
+ return success;
+ } // end encodeToFile
+
+
+ /**
+ * Convenience method for decoding data to a file.
+ *
+ * @param dataToDecode Base64-encoded data as a string
+ * @param filename Filename for saving decoded data
+ * @return <tt>true</tt> if successful, <tt>false</tt> otherwise
+ *
+ * @since 2.1
+ */
+ public static boolean decodeToFile( String dataToDecode, String filename )
+ {
+ boolean success = false;
+ Base64.OutputStream bos = null;
+ try
+ {
+ bos = new Base64.OutputStream(
+ new java.io.FileOutputStream( filename ), Base64.DECODE );
+ bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
+ success = true;
+ } // end try
+ catch( java.io.IOException e )
+ {
+ success = false;
+ } // end catch: IOException
+ finally
+ {
+ try{ bos.close(); } catch( Exception e ){}
+ } // end finally
+
+ return success;
+ } // end decodeToFile
+
+
+
+
+ /**
+ * Convenience method for reading a base64-encoded
+ * file and decoding it.
+ *
+ * @param filename Filename for reading encoded data
+ * @return decoded byte array or null if unsuccessful
+ *
+ * @since 2.1
+ */
+ public static byte[] decodeFromFile( String filename )
+ {
+ byte[] decodedData = null;
+ Base64.InputStream bis = null;
+ try
+ {
+ // Set up some useful variables
+ java.io.File file = new java.io.File( filename );
+ byte[] buffer = null;
+ int length = 0;
+ int numBytes = 0;
+
+ // Check for size of file
+ if( file.length() > Integer.MAX_VALUE )
+ {
+ System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
+ return null;
+ } // end if: file too big for int index
+ buffer = new byte[ (int)file.length() ];
+
+ // Open a stream
+ bis = new Base64.InputStream(
+ new java.io.BufferedInputStream(
+ new java.io.FileInputStream( file ) ), Base64.DECODE );
+
+ // Read until done
+ while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
+ length += numBytes;
+
+ // Save in a variable to return
+ decodedData = new byte[ length ];
+ System.arraycopy( buffer, 0, decodedData, 0, length );
+
+ } // end try
+ catch( java.io.IOException e )
+ {
+ System.err.println( "Error decoding from file " + filename );
+ } // end catch: IOException
+ finally
+ {
+ try{ bis.close(); } catch( Exception e) {}
+ } // end finally
+
+ return decodedData;
+ } // end decodeFromFile
+
+
+
+ /**
+ * Convenience method for reading a binary file
+ * and base64-encoding it.
+ *
+ * @param filename Filename for reading binary data
+ * @return base64-encoded string or null if unsuccessful
+ *
+ * @since 2.1
+ */
+ public static String encodeFromFile( String filename )
+ {
+ String encodedData = null;
+ Base64.InputStream bis = null;
+ try
+ {
+ // Set up some useful variables
+ java.io.File file = new java.io.File( filename );
+ byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1)
+ int length = 0;
+ int numBytes = 0;
+
+ // Open a stream
+ bis = new Base64.InputStream(
+ new java.io.BufferedInputStream(
+ new java.io.FileInputStream( file ) ), Base64.ENCODE );
+
+ // Read until done
+ while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
+ length += numBytes;
+
+ // Save in a variable to return
+ encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
+
+ } // end try
+ catch( java.io.IOException e )
+ {
+ System.err.println( "Error encoding from file " + filename );
+ } // end catch: IOException
+ finally
+ {
+ try{ bis.close(); } catch( Exception e) {}
+ } // end finally
+
+ return encodedData;
+ } // end encodeFromFile
+
+ /**
+ * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
+ *
+ * @param infile Input file
+ * @param outfile Output file
+ * @since 2.2
+ */
+ public static void encodeFileToFile( String infile, String outfile )
+ {
+ String encoded = Base64.encodeFromFile( infile );
+ java.io.OutputStream out = null;
+ try{
+ out = new java.io.BufferedOutputStream(
+ new java.io.FileOutputStream( outfile ) );
+ out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
+ } // end try
+ catch( java.io.IOException ex ) {
+ ex.printStackTrace();
+ } // end catch
+ finally {
+ try { out.close(); }
+ catch( Exception ex ){}
+ } // end finally
+ } // end encodeFileToFile
+
+
+ /**
+ * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
+ *
+ * @param infile Input file
+ * @param outfile Output file
+ * @since 2.2
+ */
+ public static void decodeFileToFile( String infile, String outfile )
+ {
+ byte[] decoded = Base64.decodeFromFile( infile );
+ java.io.OutputStream out = null;
+ try{
+ out = new java.io.BufferedOutputStream(
+ new java.io.FileOutputStream( outfile ) );
+ out.write( decoded );
+ } // end try
+ catch( java.io.IOException ex ) {
+ ex.printStackTrace();
+ } // end catch
+ finally {
+ try { out.close(); }
+ catch( Exception ex ){}
+ } // end finally
+ } // end decodeFileToFile
+
+
+ /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
+
+
+
+ /**
+ * A {@link Base64.InputStream} will read data from another
+ * <tt>java.io.InputStream</tt>, given in the constructor,
+ * and encode/decode to/from Base64 notation on the fly.
+ *
+ * @see Base64
+ * @since 1.3
+ */
+ public static class InputStream extends java.io.FilterInputStream
+ {
+ private boolean encode; // Encoding or decoding
+ private int position; // Current position in the buffer
+ private byte[] buffer; // Small buffer holding converted data
+ private int bufferLength; // Length of buffer (3 or 4)
+ private int numSigBytes; // Number of meaningful bytes in the buffer
+ private int lineLength;
+ private boolean breakLines; // Break lines at less than 80 characters
+ private int options; // Record options used to create the stream.
+ //private byte[] alphabet; // Local copies to avoid extra method calls
+ private byte[] decodabet; // Local copies to avoid extra method calls
+
+
+ /**
+ * Constructs a {@link Base64.InputStream} in DECODE mode.
+ *
+ * @param in the <tt>java.io.InputStream</tt> from which to read data.
+ * @since 1.3
+ */
+ public InputStream( java.io.InputStream in )
+ {
+ this( in, DECODE );
+ } // end constructor
+
+
+ /**
+ * Constructs a {@link Base64.InputStream} in
+ * either ENCODE or DECODE mode.
+ * <p>
+ * Valid options:<pre>
+ * ENCODE or DECODE: Encode or Decode as data is read.
+ * DONT_BREAK_LINES: don't break lines at 76 characters
+ * (only meaningful when encoding)
+ * <i>Note: Technically, this makes your encoding non-compliant.</i>
+ * </pre>
+ * <p>
+ * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
+ *
+ *
+ * @param in the <tt>java.io.InputStream</tt> from which to read data.
+ * @param options Specified options
+ * @see Base64#ENCODE
+ * @see Base64#DECODE
+ * @see Base64#DONT_BREAK_LINES
+ * @since 2.0
+ */
+ public InputStream( java.io.InputStream in, int options )
+ {
+ super( in );
+ this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
+ this.encode = (options & ENCODE) == ENCODE;
+ this.bufferLength = encode ? 4 : 3;
+ this.buffer = new byte[ bufferLength ];
+ this.position = -1;
+ this.lineLength = 0;
+ this.options = options; // Record for later, mostly to determine which alphabet to use
+ //this.alphabet = getAlphabet(options);
+ this.decodabet = getDecodabet(options);
+ } // end constructor
+
+ /**
+ * Reads enough of the input stream to convert
+ * to/from Base64 and returns the next byte.
+ *
+ * @return next byte
+ * @since 1.3
+ */
+ @Override
+ public int read() throws java.io.IOException
+ {
+ // Do we need to get data?
+ if( position < 0 )
+ {
+ if( encode )
+ {
+ byte[] b3 = new byte[3];
+ int numBinaryBytes = 0;
+ for( int i = 0; i < 3; i++ )
+ {
+ try
+ {
+ int b = in.read();
+
+ // If end of stream, b is -1.
+ if( b >= 0 )
+ {
+ b3[i] = (byte)b;
+ numBinaryBytes++;
+ } // end if: not end of stream
+
+ } // end try: read
+ catch( java.io.IOException e )
+ {
+ // Only a problem if we got no data at all.
+ if( i == 0 )
+ throw e;
+
+ } // end catch
+ } // end for: each needed input byte
+
+ if( numBinaryBytes > 0 )
+ {
+ encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
+ position = 0;
+ numSigBytes = 4;
+ } // end if: got data
+ else
+ {
+ return -1;
+ } // end else
+ } // end if: encoding
+
+ // Else decoding
+ else
+ {
+ byte[] b4 = new byte[4];
+ int i = 0;
+ for( i = 0; i < 4; i++ )
+ {
+ // Read four "meaningful" bytes:
+ int b = 0;
+ do{ b = in.read(); }
+ while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
+
+ if( b < 0 )
+ break; // Reads a -1 if end of stream
+
+ b4[i] = (byte)b;
+ } // end for: each needed input byte
+
+ if( i == 4 )
+ {
+ numSigBytes = decode4to3( b4, 0, buffer, 0, options );
+ position = 0;
+ } // end if: got four characters
+ else if( i == 0 ){
+ return -1;
+ } // end else if: also padded correctly
+ else
+ {
+ // Must have broken out from above.
+ throw new java.io.IOException( "Improperly padded Base64 input." );
+ } // end
+
+ } // end else: decode
+ } // end else: get data
+
+ // Got data?
+ if( position >= 0 )
+ {
+ // End of relevant data?
+ if( /*!encode &&*/ position >= numSigBytes )
+ return -1;
+
+ if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
+ {
+ lineLength = 0;
+ return '\n';
+ } // end if
+ else
+ {
+ lineLength++; // This isn't important when decoding
+ // but throwing an extra "if" seems
+ // just as wasteful.
+
+ int b = buffer[ position++ ];
+
+ if( position >= bufferLength )
+ position = -1;
+
+ return b & 0xFF; // This is how you "cast" a byte that's
+ // intended to be unsigned.
+ } // end else
+ } // end if: position >= 0
+
+ // Else error
+ else
+ {
+ // When JDK1.4 is more accepted, use an assertion here.
+ throw new java.io.IOException( "Error in Base64 code reading stream." );
+ } // end else
+ } // end read
+
+
+ /**
+ * Calls {@link #read()} repeatedly until the end of stream
+ * is reached or <var>len</var> bytes are read.
+ * Returns number of bytes read into array or -1 if
+ * end of stream is encountered.
+ *
+ * @param dest array to hold values
+ * @param off offset for array
+ * @param len max number of bytes to read into array
+ * @return bytes read into array or -1 if end of stream is encountered.
+ * @since 1.3
+ */
+ @Override
+ public int read( byte[] dest, int off, int len ) throws java.io.IOException
+ {
+ int i;
+ int b;
+ for( i = 0; i < len; i++ )
+ {
+ b = read();
+
+ //if( b < 0 && i == 0 )
+ // return -1;
+
+ if( b >= 0 )
+ dest[off + i] = (byte)b;
+ else if( i == 0 )
+ return -1;
+ else
+ break; // Out of 'for' loop
+ } // end for: each byte read
+ return i;
+ } // end read
+
+ } // end inner class InputStream
+
+
+
+
+
+
+ /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
+
+
+
+ /**
+ * A {@link Base64.OutputStream} will write data to another
+ * <tt>java.io.OutputStream</tt>, given in the constructor,
+ * and encode/decode to/from Base64 notation on the fly.
+ *
+ * @see Base64
+ * @since 1.3
+ */
+ public static class OutputStream extends java.io.FilterOutputStream
+ {
+ private boolean encode;
+ private int position;
+ private byte[] buffer;
+ private int bufferLength;
+ private int lineLength;
+ private boolean breakLines;
+ private byte[] b4; // Scratch used in a few places
+ private boolean suspendEncoding;
+ private int options; // Record for later
+ //private byte[] alphabet; // Local copies to avoid extra method calls
+ private byte[] decodabet; // Local copies to avoid extra method calls
+
+ /**
+ * Constructs a {@link Base64.OutputStream} in ENCODE mode.
+ *
+ * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
+ * @since 1.3
+ */
+ public OutputStream( java.io.OutputStream out )
+ {
+ this( out, ENCODE );
+ } // end constructor
+
+
+ /**
+ * Constructs a {@link Base64.OutputStream} in
+ * either ENCODE or DECODE mode.
+ * <p>
+ * Valid options:<pre>
+ * ENCODE or DECODE: Encode or Decode as data is read.
+ * DONT_BREAK_LINES: don't break lines at 76 characters
+ * (only meaningful when encoding)
+ * <i>Note: Technically, this makes your encoding non-compliant.</i>
+ * </pre>
+ * <p>
+ * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
+ *
+ * @param out the <tt>java.io.OutputStream</tt> to which data will be written.
+ * @param options Specified options.
+ * @see Base64#ENCODE
+ * @see Base64#DECODE
+ * @see Base64#DONT_BREAK_LINES
+ * @since 1.3
+ */
+ public OutputStream( java.io.OutputStream out, int options )
+ {
+ super( out );
+ this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
+ this.encode = (options & ENCODE) == ENCODE;
+ this.bufferLength = encode ? 3 : 4;
+ this.buffer = new byte[ bufferLength ];
+ this.position = 0;
+ this.lineLength = 0;
+ this.suspendEncoding = false;
+ this.b4 = new byte[4];
+ this.options = options;
+ //this.alphabet = getAlphabet(options);
+ this.decodabet = getDecodabet(options);
+ } // end constructor
+
+
+ /**
+ * Writes the byte to the output stream after
+ * converting to/from Base64 notation.
+ * When encoding, bytes are buffered three
+ * at a time before the output stream actually
+ * gets a write() call.
+ * When decoding, bytes are buffered four
+ * at a time.
+ *
+ * @param theByte the byte to write
+ * @since 1.3
+ */
+ @Override
+ public void write(int theByte) throws java.io.IOException
+ {
+ // Encoding suspended?
+ if( suspendEncoding )
+ {
+ super.out.write( theByte );
+ return;
+ } // end if: supsended
+
+ // Encode?
+ if( encode )
+ {
+ buffer[ position++ ] = (byte)theByte;
+ if( position >= bufferLength ) // Enough to encode.
+ {
+ out.write( encode3to4( b4, buffer, bufferLength, options ) );
+
+ lineLength += 4;
+ if( breakLines && lineLength >= MAX_LINE_LENGTH )
+ {
+ out.write( NEW_LINE );
+ lineLength = 0;
+ } // end if: end of line
+
+ position = 0;
+ } // end if: enough to output
+ } // end if: encoding
+
+ // Else, Decoding
+ else
+ {
+ // Meaningful Base64 character?
+ if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC )
+ {
+ buffer[ position++ ] = (byte)theByte;
+ if( position >= bufferLength ) // Enough to output.
+ {
+ int len = Base64.decode4to3( buffer, 0, b4, 0, options );
+ out.write( b4, 0, len );
+ //out.write( Base64.decode4to3( buffer ) );
+ position = 0;
+ } // end if: enough to output
+ } // end if: meaningful base64 character
+ else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC )
+ {
+ throw new java.io.IOException( "Invalid character in Base64 data." );
+ } // end else: not white space either
+ } // end else: decoding
+ } // end write
+
+
+
+ /**
+ * Calls {@link #write(int)} repeatedly until <var>len</var>
+ * bytes are written.
+ *
+ * @param theBytes array from which to read bytes
+ * @param off offset for array
+ * @param len max number of bytes to read into array
+ * @since 1.3
+ */
+ @Override
+ public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
+ {
+ // Encoding suspended?
+ if( suspendEncoding )
+ {
+ super.out.write( theBytes, off, len );
+ return;
+ } // end if: supsended
+
+ for( int i = 0; i < len; i++ )
+ {
+ write( theBytes[ off + i ] );
+ } // end for: each byte written
+
+ } // end write
+
+
+
+ /**
+ * Method added by PHIL. [Thanks, PHIL. -Rob]
+ * This pads the buffer without closing the stream.
+ */
+ public void flushBase64() throws java.io.IOException
+ {
+ if( position > 0 )
+ {
+ if( encode )
+ {
+ out.write( encode3to4( b4, buffer, position, options ) );
+ position = 0;
+ } // end if: encoding
+ else
+ {
+ throw new java.io.IOException( "Base64 input not properly padded." );
+ } // end else: decoding
+ } // end if: buffer partially full
+
+ } // end flush
+
+
+ /**
+ * Flushes and closes (I think, in the superclass) the stream.
+ *
+ * @since 1.3
+ */
+ @Override
+ public void close() throws java.io.IOException
+ {
+ // 1. Ensure that pending characters are written
+ flushBase64();
+
+ // 2. Actually close the stream
+ // Base class both flushes and closes.
+ super.close();
+
+ buffer = null;
+ out = null;
+ } // end close
+
+
+
+ /**
+ * Suspends encoding of the stream.
+ * May be helpful if you need to embed a piece of
+ * base640-encoded data in a stream.
+ *
+ * @since 1.5.1
+ */
+ public void suspendEncoding() throws java.io.IOException
+ {
+ flushBase64();
+ this.suspendEncoding = true;
+ } // end suspendEncoding
+
+
+ /**
+ * Resumes encoding of the stream.
+ * May be helpful if you need to embed a piece of
+ * base640-encoded data in a stream.
+ *
+ * @since 1.5.1
+ */
+ public void resumeEncoding()
+ {
+ this.suspendEncoding = false;
+ } // end resumeEncoding
+
+
+
+ } // end inner class OutputStream
+
+
+} // end class Base64
17 years
Seam SVN: r10602 - in modules/trunk/faces: src/main/java/org/jboss/seam/faces and 1 other directory.
by seam-commits@lists.jboss.org
Author: shane.bryzak(a)jboss.com
Date: 2009-04-22 21:09:57 -0400 (Wed, 22 Apr 2009)
New Revision: 10602
Removed:
modules/trunk/faces/src/main/java/org/jboss/seam/faces/package-info.java
Modified:
modules/trunk/faces/
Log:
ignores
Property changes on: modules/trunk/faces
___________________________________________________________________
Name: svn:ignore
+ target
.settings
.classpath
.project
Deleted: modules/trunk/faces/src/main/java/org/jboss/seam/faces/package-info.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/package-info.java 2009-04-23 01:09:20 UTC (rev 10601)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/package-info.java 2009-04-23 01:09:57 UTC (rev 10602)
@@ -1,11 +0,0 @@
-/**
- * A set of Seam components for working with JSF.
- * Some of these components extend core components
- * and add JSF-specific functionality. Others
- * exist to put a friendly face to JSF.
- */
-@AutoCreate
-package org.jboss.seam.faces;
-
-import org.jboss.seam.annotations.AutoCreate;
-
17 years
Seam SVN: r10601 - in modules/trunk: faces and 8 other directories.
by seam-commits@lists.jboss.org
Author: shane.bryzak(a)jboss.com
Date: 2009-04-22 21:09:20 -0400 (Wed, 22 Apr 2009)
New Revision: 10601
Added:
modules/trunk/faces/
modules/trunk/faces/pom.xml
modules/trunk/faces/src/
modules/trunk/faces/src/main/
modules/trunk/faces/src/main/java/
modules/trunk/faces/src/main/java/org/
modules/trunk/faces/src/main/java/org/jboss/
modules/trunk/faces/src/main/java/org/jboss/seam/
modules/trunk/faces/src/main/java/org/jboss/seam/faces/
modules/trunk/faces/src/main/java/org/jboss/seam/faces/DataModels.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/DateConverter.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesContext.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesExpressions.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesManager.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesMessages.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesPage.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/HttpError.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/IsUserInRole.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/Navigator.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/Parameters.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/Redirect.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/RedirectException.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/Renderer.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/ResourceLoader.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/Selector.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/Switcher.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/UiComponent.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/UserPrincipal.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/Validation.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/events/
modules/trunk/faces/src/main/java/org/jboss/seam/faces/events/ValidationFailedEvent.java
modules/trunk/faces/src/main/java/org/jboss/seam/faces/package-info.java
Log:
initial import of faces module
Added: modules/trunk/faces/pom.xml
===================================================================
--- modules/trunk/faces/pom.xml (rev 0)
+++ modules/trunk/faces/pom.xml 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,36 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <parent>
+ <artifactId>seam-parent</artifactId>
+ <groupId>org.jboss.seam</groupId>
+ <version>3.0.0-SNAPSHOT</version>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.seam</groupId>
+ <artifactId>seam-faces</artifactId>
+ <packaging>jar</packaging>
+ <version>3.0.0-SNAPSHOT</version>
+ <name>Seam Faces</name>
+
+ <dependencies>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.el</groupId>
+ <artifactId>el-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.webbeans</groupId>
+ <artifactId>jsr299-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.faces</groupId>
+ <artifactId>jsf-api</artifactId>
+ </dependency>
+ </dependencies>
+
+</project>
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/DataModels.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/DataModels.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/DataModels.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,70 @@
+package org.jboss.seam.faces;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.faces.model.DataModel;
+
+import org.jboss.seam.Component;
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.framework.Query;
+import org.jboss.seam.jsf.ArrayDataModel;
+import org.jboss.seam.jsf.ListDataModel;
+import org.jboss.seam.jsf.MapDataModel;
+import org.jboss.seam.jsf.SetDataModel;
+
+/**
+ * Wraps a collection as a JSF {@link DataModel}. May be overridden
+ * and extended if you don't like the built in collections
+ * which are supported: list, map, set, array.
+ *
+ * @author pmuir
+ */
+public class DataModels
+{
+
+ /**
+ * Wrap the value in a DataModel
+ *
+ * This implementation supports {@link List}, {@link Map}, {@link Set} and
+ * arrays
+ */
+ public DataModel getDataModel(Object value)
+ {
+ if (value instanceof List)
+ {
+ return new ListDataModel( (List) value );
+ }
+ else if (value instanceof Object[])
+ {
+ return new ArrayDataModel( (Object[]) value );
+ }
+ else if (value instanceof Map)
+ {
+ return new MapDataModel( (Map) value );
+ }
+ else if (value instanceof Set)
+ {
+ return new SetDataModel( (Set) value );
+ }
+ else
+ {
+ throw new IllegalArgumentException("unknown collection type: " + value.getClass());
+ }
+ }
+
+ /**
+ * Wrap the the Seam Framework {@link Query} in a JSF DataModel
+ */
+ public DataModel getDataModel(Query query)
+ {
+ return getDataModel( query.getResultList() );
+ }
+
+ public static DataModels instance()
+ {
+ return (DataModels) Component.getInstance(DataModels.class, ScopeType.STATELESS);
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/DateConverter.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/DateConverter.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/DateConverter.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,120 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.BUILT_IN;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+import javax.faces.convert.ConverterException;
+
+import org.jboss.seam.annotations.Create;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.faces.Converter;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+import org.jboss.seam.contexts.Contexts;
+import org.jboss.seam.log.Log;
+import org.jboss.seam.log.Logging;
+
+/**
+ * Provides a default JSF converter for properties of type java.util.Date.
+ *
+ * <p>This converter is provided to save a developer from having to specify
+ * a DateTimeConverter on an input field or page parameter. By default, it
+ * assumes the type to be a date (as opposed to a time or date plus time) and
+ * uses the short input style adjusted to the Locale of the user. For Locale.US,
+ * the input pattern is mm/DD/yy. However, to comply with Y2K, the year is changed
+ * from two digits to four (e.g., mm/DD/yyyy).</p>
+ * <p>It's possible to override the input pattern globally using component configuration.
+ * Here is an example of changing the style to both and setting the date and
+ * time style to medium.</p>
+ * <pre>
+ * org.jboss.seam.faces.dateConverter.type=both
+ * org.jboss.seam.faces.dateConverter.dateStyle=medium
+ * org.jboss.seam.faces.dateConverter.timeStyle=medium
+ * </pre>
+ * <p>Alternatively, a fixed pattern can be specified.</p>
+ * <pre>
+ * org.jboss.seam.faces.dateConverter.pattern=yyyy-mm-DD
+ * </pre>
+ *
+ * @author Dan Allen
+ */
+@Converter(forClass = Date.class)
+@Name("org.jboss.seam.faces.dateConverter")
+@Install(precedence = BUILT_IN, classDependencies = "javax.faces.context.FacesContext")
+@BypassInterceptors
+public class DateConverter extends javax.faces.convert.DateTimeConverter {
+
+ private Log log = Logging.getLog(DateConverter.class);
+
+ private static final String TYPE_DATE = "date";
+ private static final String STYLE_SHORT = "short";
+ private static final String TWO_DIGIT_YEAR_PATTERN = "yy";
+ private static final String FOUR_DIGIT_YEAR_PATTERN = "yyyy";
+
+ // constructor is used to initialize converter to allow these values to be overridden using component properties
+ public DateConverter() {
+ super();
+ setType(TYPE_DATE);
+ setDateStyle(STYLE_SHORT);
+ setTimeStyle(STYLE_SHORT); // default in case developer overrides type to be time or both
+ }
+
+ @Create
+ public void create() {
+ // TODO make this work if using "both" for type; requires more analysis of time style
+ if (TYPE_DATE.equals(getType()) && STYLE_SHORT.equals(getDateStyle()) && getPattern() == null) {
+ // attempt to make the pattern Y2K compliant, which it isn't by default
+ DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, getLocale());
+ if (dateFormat instanceof SimpleDateFormat) {
+ setPattern(((SimpleDateFormat) dateFormat).toPattern().replace(TWO_DIGIT_YEAR_PATTERN, FOUR_DIGIT_YEAR_PATTERN));
+ }
+ }
+ // required since the superclass may access the fields directly
+ setTimeZone(getTimeZone());
+ setLocale(getLocale());
+ }
+
+ @Override
+ public TimeZone getTimeZone() {
+ if (Contexts.isApplicationContextActive()) {
+ return org.jboss.seam.international.TimeZone.instance();
+ } else {
+ // we don't want to use JSF's braindead default (maybe in JSF 2)
+ return TimeZone.getDefault();
+ }
+ }
+
+ @Override
+ public Locale getLocale() {
+ if (Contexts.isApplicationContextActive()) {
+ return org.jboss.seam.international.Locale.instance();
+ } else {
+ return super.getLocale();
+ }
+ }
+
+ @Override
+ public Object getAsObject(FacesContext context, UIComponent component,
+ String value) throws ConverterException {
+ if (log.isDebugEnabled()) {
+ log.debug("Converting string '#0' to date for clientId '#1' using Seam's built-in JSF date converter", value, component.getClientId(context));
+ }
+ return super.getAsObject(context, component, value);
+ }
+
+ @Override
+ public String getAsString(FacesContext context, UIComponent component,
+ Object value) throws ConverterException {
+ if (log.isDebugEnabled()) {
+ log.debug("Converting date '#0' to string for clientId '#1' using Seam's built-in JSF date converter", value, component.getClientId(context));
+ }
+ return super.getAsString(context, component, value);
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesContext.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesContext.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesContext.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,29 @@
+//$Id: FacesContext.java 5350 2007-06-20 17:53:19Z gavin $
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.BUILT_IN;
+
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.Unwrap;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+
+/**
+ * Support for injecting the JSF FacesContext object
+ *
+ * @author Gavin King
+ */
+(a)Scope(ScopeType.APPLICATION)
+@BypassInterceptors
+@Name("org.jboss.seam.faces.facesContext")
+@Install(precedence=BUILT_IN, classDependencies="javax.faces.context.FacesContext")
+public class FacesContext
+{
+ @Unwrap
+ public javax.faces.context.FacesContext getContext()
+ {
+ return javax.faces.context.FacesContext.getCurrentInstance();
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesExpressions.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesExpressions.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesExpressions.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,37 @@
+//$Id: FacesExpressions.java 9684 2008-12-01 21:41:20Z dan.j.allen $
+package org.jboss.seam.faces;
+
+import javax.annotation.Named;
+import javax.context.ApplicationScoped;
+import javax.el.ELContext;
+import javax.faces.context.FacesContext;
+
+import org.jboss.seam.contexts.FacesLifecycle;
+import org.jboss.seam.core.Expressions;
+
+/**
+ * Factory for method and value bindings in a JSF environment.
+ *
+ * @author Gavin King
+ */
+@Named
+@ApplicationScoped
+public class FacesExpressions extends Expressions
+{
+ /**
+ * Get an appropriate ELContext. If there is an active JSF request,
+ * use JSF's ELContext. Otherwise, use one that we created.
+ */
+ @Override
+ public ELContext getELContext()
+ {
+ return isFacesContextActive() ? FacesContext.getCurrentInstance().getELContext() : super.getELContext();
+ }
+
+ @Override
+ protected boolean isFacesContextActive()
+ {
+ return FacesContext.getCurrentInstance() != null && FacesLifecycle.getPhaseId() != null;
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesManager.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesManager.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesManager.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,316 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.FRAMEWORK;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+import javax.faces.context.ExternalContext;
+import javax.faces.context.FacesContext;
+import javax.faces.event.PhaseId;
+
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+import org.jboss.seam.contexts.Contexts;
+import org.jboss.seam.contexts.FacesLifecycle;
+import org.jboss.seam.core.Conversation;
+import org.jboss.seam.core.Init;
+import org.jboss.seam.core.Interpolator;
+import org.jboss.seam.core.Manager;
+import org.jboss.seam.log.LogProvider;
+import org.jboss.seam.log.Logging;
+import org.jboss.seam.navigation.ConversationIdParameter;
+import org.jboss.seam.navigation.Pages;
+import org.jboss.seam.pageflow.Pageflow;
+
+/**
+ * An extended conversation manager for the JSF environment.
+ *
+ * @author Gavin King
+ * @author <a href="mailto:theute@jboss.org">Thomas Heute</a>
+ */
+(a)Scope(ScopeType.EVENT)
+@Name("org.jboss.seam.core.manager")
+@Install(precedence=FRAMEWORK, classDependencies="javax.faces.context.FacesContext")
+@BypassInterceptors
+public class FacesManager extends Manager
+{
+ private static final LogProvider log = Logging.getLogProvider(FacesManager.class);
+
+
+
+ private boolean controllingRedirect;
+
+ /**
+ * Temporarily promote a temporary conversation to
+ * a long running conversation for the duration of
+ * a browser redirect. After the redirect, the
+ * conversation will be demoted back to a temporary
+ * conversation. Handle any changes to the conversation
+ * id, due to propagation via natural id.
+ */
+ public void beforeRedirect(String viewId)
+ {
+ beforeRedirect();
+
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ String currentViewId = Pages.getViewId(facesContext);
+ if ( viewId!=null && currentViewId!=null )
+ {
+ ConversationIdParameter currentPage = Pages.instance().getPage(currentViewId).getConversationIdParameter();
+ ConversationIdParameter targetPage = Pages.instance().getPage(viewId).getConversationIdParameter();
+ if ( isDifferentConversationId(currentPage, targetPage) )
+ {
+ updateCurrentConversationId( targetPage.getConversationId() );
+ }
+ }
+ }
+
+ public void interpolateAndRedirect(String url)
+ {
+ Map<String, Object> parameters = new HashMap<String, Object>();
+ int loc = url.indexOf('?');
+ if (loc>0)
+ {
+ StringTokenizer tokens = new StringTokenizer( url.substring(loc), "?=&" );
+ while ( tokens.hasMoreTokens() )
+ {
+ String name = tokens.nextToken();
+ String value = Interpolator.instance().interpolate( tokens.nextToken() );
+ parameters.put(name, value);
+ }
+ url = url.substring(0, loc);
+ }
+ redirect(url, parameters, true, true);
+ }
+
+ @Override
+ protected void storeConversationToViewRootIfNecessary()
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ if ( facesContext!=null && FacesLifecycle.getPhaseId()==PhaseId.RENDER_RESPONSE )
+ {
+ FacesPage.instance().storeConversation();
+ }
+ }
+
+ @Override
+ protected String generateInitialConversationId()
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ String viewId = Pages.getViewId(facesContext);
+ if ( viewId!=null )
+ {
+ return Pages.instance().getPage(viewId)
+ .getConversationIdParameter()
+ .getInitialConversationId( facesContext.getExternalContext().getRequestParameterMap() );
+ }
+ else
+ {
+ return super.generateInitialConversationId();
+ }
+ }
+
+ public void redirectToExternalURL(String url) {
+ try {
+ FacesContext.getCurrentInstance().getExternalContext().redirect(url);
+ } catch (IOException e) {
+ throw new RedirectException(e);
+ }
+ }
+
+ /**
+ * Redirect to the given view id, encoding the conversation id
+ * into the request URL.
+ *
+ * @param viewId the JSF view id
+ */
+ @Override
+ public void redirect(String viewId)
+ {
+ redirect(viewId, null, true, true);
+ }
+
+ public void redirect(String viewId, Map<String, Object> parameters,
+ boolean includeConversationId)
+ {
+ redirect(viewId, parameters, includeConversationId, true);
+ }
+
+ /**
+ * Redirect to the given view id, after encoding parameters and conversation
+ * id into the request URL.
+ *
+ * @param viewId the JSF view id
+ * @param parameters request parameters to be encoded (possibly null)
+ * @param includeConversationId determines if the conversation id is to be encoded
+ */
+ public void redirect(String viewId, Map<String, Object> parameters,
+ boolean includeConversationId, boolean includePageParams)
+ {
+ if (viewId == null)
+ {
+ throw new RedirectException("cannot redirect to a null viewId");
+ }
+ FacesContext context = FacesContext.getCurrentInstance();
+ String url = context.getApplication().getViewHandler().getActionURL(context, viewId);
+ if (parameters!=null)
+ {
+ url = encodeParameters(url, parameters);
+ }
+
+ if (includePageParams)
+ {
+ url = Pages.instance().encodePageParameters(FacesContext.getCurrentInstance(),
+ url, viewId, parameters==null ? Collections.EMPTY_SET : parameters.keySet());
+ }
+
+ if (includeConversationId)
+ {
+ beforeRedirect(viewId);
+ url = encodeConversationId(url, viewId);
+ }
+ redirect(viewId, context, url);
+ }
+
+ /**
+ * Redirect to the given view id, after encoding the given conversation
+ * id into the request URL.
+ *
+ * @param viewId the JSF view id
+ * @param conversationId an id of a long-running conversation
+ */
+ @Override
+ public void redirect(String viewId, String conversationId)
+ {
+ if (viewId == null)
+ {
+ throw new RedirectException("cannot redirect to a null viewId");
+ }
+ FacesContext context = FacesContext.getCurrentInstance();
+ String url = context.getApplication().getViewHandler().getActionURL(context, viewId);
+ url = encodeConversationId(url, viewId, conversationId);
+ redirect(viewId, context, url);
+ }
+
+ private void redirect(String viewId, FacesContext context, String url)
+ {
+ url = Pages.instance().encodeScheme(viewId, context, url);
+ if ( log.isDebugEnabled() )
+ {
+ log.debug("redirecting to: " + url);
+ }
+ ExternalContext externalContext = context.getExternalContext();
+ controllingRedirect = true;
+ try
+ {
+ Contexts.getEventContext().set(REDIRECT_FROM_MANAGER, "");
+ externalContext.redirect( externalContext.encodeActionURL(url) );
+ }
+ catch (IOException ioe)
+ {
+ throw new RedirectException(ioe);
+ }
+ finally
+ {
+ Contexts.getEventContext().remove(REDIRECT_FROM_MANAGER);
+ controllingRedirect = false;
+ }
+ context.responseComplete();
+ }
+
+ /**
+ * Called by the Seam Redirect Filter when a redirect is called.
+ * Appends the conversationId parameter if necessary.
+ *
+ * @param url the requested URL
+ * @return the resulting URL with the conversationId appended
+ */
+ public String appendConversationIdFromRedirectFilter(String url, String viewId)
+ {
+ boolean appendConversationId = !controllingRedirect;
+ if (appendConversationId)
+ {
+ beforeRedirect(viewId);
+ url = encodeConversationId(url, viewId);
+ }
+ return url;
+ }
+
+ /**
+ * If a page description is defined, remember the description and
+ * view id for the current page, to support conversation switching.
+ * Called just before the render phase.
+ */
+ public void prepareBackswitch(FacesContext facesContext)
+ {
+
+ Conversation conversation = Conversation.instance();
+
+ //stuff from jPDL takes precedence
+ org.jboss.seam.pageflow.Page page =
+ Manager.instance().isLongRunningConversation() &&
+ Init.instance().isJbpmInstalled() &&
+ Pageflow.instance().isInProcess() && Pageflow.instance().isStarted() ?
+ Pageflow.instance().getPage() : null;
+
+ if (page==null)
+ {
+ //handle stuff defined in pages.xml
+ Pages pages = Pages.instance();
+ if (pages!=null) //for tests
+ {
+ String viewId = Pages.getViewId(facesContext);
+ org.jboss.seam.navigation.Page pageEntry = pages.getPage(viewId);
+ if ( pageEntry.isSwitchEnabled() )
+ {
+ conversation.setViewId(viewId);
+ }
+ if ( pageEntry.hasDescription() )
+ {
+ conversation.setDescription( pageEntry.renderDescription() );
+ }
+ else if(pages.hasDescription(viewId))
+ {
+ conversation.setDescription( pages.renderDescription(viewId) );
+ }
+ conversation.setTimeout( pages.getTimeout(viewId) );
+ conversation.setConcurrentRequestTimeout( pages.getConcurrentRequestTimeout(viewId) );
+ }
+ }
+ else
+ {
+ //use stuff from the pageflow definition
+ if ( page.isSwitchEnabled() )
+ {
+ conversation.setViewId( Pageflow.instance().getPageViewId() );
+ }
+ if ( page.hasDescription() )
+ {
+ conversation.setDescription( page.getDescription() );
+ }
+ conversation.setTimeout( page.getTimeout() );
+ }
+
+ flushConversationMetadata();
+
+ }
+
+ public static FacesManager instance()
+ {
+ return (FacesManager) Manager.instance();
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesMessages.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesMessages.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesMessages.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,356 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.BUILT_IN;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.faces.application.FacesMessage;
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+
+import org.jboss.seam.Component;
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+import org.jboss.seam.contexts.Contexts;
+import org.jboss.seam.international.StatusMessage;
+import org.jboss.seam.international.StatusMessages;
+import org.jboss.seam.util.Strings;
+
+/**
+ * A Seam component that propagates FacesMessages across redirects
+ * and interpolates EL expressions in the message string.
+ *
+ * @author Gavin King
+ * @author Pete Muir
+ */
+(a)Scope(ScopeType.CONVERSATION)
+(a)Name(StatusMessages.COMPONENT_NAME)
+@Install(precedence=BUILT_IN, classDependencies="javax.faces.context.FacesContext")
+@BypassInterceptors
+public class FacesMessages extends StatusMessages
+{
+
+ /**
+ * Called by Seam to transfer messages from FacesMessages to JSF
+ */
+ public void beforeRenderResponse()
+ {
+ for (StatusMessage statusMessage: getMessages())
+ {
+ FacesContext.getCurrentInstance().addMessage( null, toFacesMessage(statusMessage) );
+ }
+ for ( Map.Entry<String, List<StatusMessage>> entry: getKeyedMessages().entrySet() )
+ {
+ for ( StatusMessage statusMessage: entry.getValue() )
+ {
+ String clientId = getClientId(entry.getKey());
+ FacesContext.getCurrentInstance().addMessage( clientId, toFacesMessage(statusMessage) );
+ }
+ }
+ clear();
+ }
+
+ /**
+ * Called by Seam to transfer any messages added in the phase just processed
+ * to the FacesMessages component.
+ *
+ * A task runner is used to allow the messages access to outjected values.
+ */
+ public static void afterPhase()
+ {
+ runTasks();
+ }
+
+ /**
+ * Convert a StatusMessage to a FacesMessage
+ */
+ private static FacesMessage toFacesMessage(StatusMessage statusMessage)
+ {
+ if (!Strings.isEmpty(statusMessage.getSummary()))
+ {
+ return new FacesMessage(toSeverity(statusMessage.getSeverity()), statusMessage.getSummary(), statusMessage.getDetail() );
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Convert a StatusMessage.Severity to a FacesMessage.Severity
+ */
+ private static javax.faces.application.FacesMessage.Severity toSeverity(org.jboss.seam.international.StatusMessage.Severity severity)
+ {
+ switch (severity)
+ {
+ case ERROR:
+ return FacesMessage.SEVERITY_ERROR;
+ case FATAL:
+ return FacesMessage.SEVERITY_FATAL;
+ case INFO:
+ return FacesMessage.SEVERITY_INFO;
+ case WARN:
+ return FacesMessage.SEVERITY_WARN;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Convert a FacesMessage.Severity to a StatusMessage.Severity
+ */
+ private static org.jboss.seam.international.StatusMessage.Severity toSeverity(javax.faces.application.FacesMessage.Severity severity)
+ {
+ if (FacesMessage.SEVERITY_ERROR.equals(severity))
+ {
+ return org.jboss.seam.international.StatusMessage.Severity.ERROR;
+ }
+ else if (FacesMessage.SEVERITY_FATAL.equals(severity))
+ {
+ return org.jboss.seam.international.StatusMessage.Severity.FATAL;
+ }
+ else if (FacesMessage.SEVERITY_INFO.equals(severity))
+ {
+ return org.jboss.seam.international.StatusMessage.Severity.INFO;
+ }
+ else if (FacesMessage.SEVERITY_WARN.equals(severity))
+ {
+ return org.jboss.seam.international.StatusMessage.Severity.WARN;
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Calculate the JSF client ID from the provided widget ID
+ */
+ private String getClientId(String id)
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ return getClientId( facesContext.getViewRoot(), id, facesContext);
+ }
+
+ private static String getClientId(UIComponent component, String id, FacesContext facesContext)
+ {
+ String componentId = component.getId();
+ if (componentId!=null && componentId.equals(id))
+ {
+ return component.getClientId(facesContext);
+ }
+ else
+ {
+ Iterator iter = component.getFacetsAndChildren();
+ while ( iter.hasNext() )
+ {
+ UIComponent child = (UIComponent) iter.next();
+ String clientId = getClientId(child, id, facesContext);
+ if (clientId!=null) return clientId;
+ }
+ return null;
+ }
+ }
+
+ /**
+ * Get all faces messages that have already been added
+ * to the context.
+ *
+ */
+ public List<FacesMessage> getCurrentMessages()
+ {
+ List<FacesMessage> result = new ArrayList<FacesMessage>();
+ Iterator<FacesMessage> iter = FacesContext.getCurrentInstance().getMessages();
+ while ( iter.hasNext() )
+ {
+ result.add( iter.next() );
+ }
+ return result;
+ }
+
+ /**
+ * Get all faces global messages that have already been added
+ * to the context.
+ *
+ */
+ public List<FacesMessage> getCurrentGlobalMessages()
+ {
+ List<FacesMessage> result = new ArrayList<FacesMessage>();
+ Iterator<FacesMessage> iter = FacesContext.getCurrentInstance().getMessages(null);
+ while ( iter.hasNext() )
+ {
+ result.add( iter.next() );
+ }
+ return result;
+ }
+
+ /**
+ * Get all faces messages that have already been added
+ * to the control.
+ *
+ */
+ public List<FacesMessage> getCurrentMessagesForControl(String id)
+ {
+ String clientId = getClientId(id);
+ List<FacesMessage> result = new ArrayList<FacesMessage>();
+ Iterator<FacesMessage> iter = FacesContext.getCurrentInstance().getMessages(clientId);
+ while ( iter.hasNext() )
+ {
+ result.add( iter.next() );
+ }
+ return result;
+ }
+
+ /**
+ * Utility method to create a FacesMessage from a Severity, messageTemplate
+ * and params.
+ *
+ * This method interpolates the parameters provided
+ */
+ public static FacesMessage createFacesMessage(javax.faces.application.FacesMessage.Severity severity, String messageTemplate, Object... params)
+ {
+ return createFacesMessage(severity, null, messageTemplate, params);
+ }
+
+ /**
+ * Utility method to create a FacesMessage from a Severity, key,
+ * defaultMessageTemplate and params.
+ *
+ * This method interpolates the parameters provided
+ */
+ public static FacesMessage createFacesMessage(javax.faces.application.FacesMessage.Severity severity, String key, String defaultMessageTemplate, Object... params)
+ {
+ StatusMessage message = new StatusMessage(toSeverity(severity), key, null, defaultMessageTemplate, null);
+ message.interpolate(params);
+ return toFacesMessage(message);
+ }
+
+ /**
+ * Add a FacesMessage that will be used
+ * the next time a page is rendered.
+ *
+ * Deprecated, use a method in {@link StatusMessages} instead
+ */
+ @Deprecated
+ public void add(FacesMessage facesMessage)
+ {
+ if (facesMessage!=null)
+ {
+ add(toSeverity(facesMessage.getSeverity()), null, null, facesMessage.getSummary(), facesMessage.getDetail());
+ }
+ }
+
+ /**
+ * Create a new status message, with the messageTemplate is as the message.
+ *
+ * You can also specify the severity, and parameters to be interpolated
+ *
+ * Deprecated, use {@link #add(org.jboss.seam.international.StatusMessage.Severity, String, Object...)}
+ * instead
+ */
+ @Deprecated
+ public void add(javax.faces.application.FacesMessage.Severity severity, String messageTemplate, Object... params)
+ {
+ add(toSeverity(severity), messageTemplate, params);
+ }
+
+
+ /**
+ * Create a new status message, with the messageTemplate is as the message.
+ *
+ * A severity of INFO will be used, and you can specify paramters to be
+ * interpolated
+ *
+ * Deprecated, use {@link #addToControl(String, org.jboss.seam.international.StatusMessage.Severity, String, Object...)}
+ * instead
+ */
+ @Deprecated
+ public void addToControl(String id, javax.faces.application.FacesMessage.Severity severity, String messageTemplate, Object... params)
+ {
+ addToControl(id, toSeverity(severity), messageTemplate, params);
+ }
+
+ /**
+ * Add a status message, looking up the message in the resource bundle
+ * using the provided key.
+ *
+ * You can also specify the severity, and parameters to be interpolated
+ *
+ * Deprecated, use {@link #addFromResourceBundle(org.jboss.seam.international.StatusMessage.Severity, String, Object...)}
+ * instead
+ */
+ @Deprecated
+ public void addFromResourceBundle(javax.faces.application.FacesMessage.Severity severity, String key, Object... params)
+ {
+ addFromResourceBundle(toSeverity(severity), key, params);
+ }
+
+ /**
+ * Add a status message, looking up the message in the resource bundle
+ * using the provided key.
+ *
+ * You can also specify the severity, and parameters to be interpolated
+ *
+ * Deprecated, use {@link #addFromResourceBundleOrDefault(javax.faces.application.FacesMessage.Severity, String, String, Object...)}
+ * instead
+ */
+ @Deprecated
+ public void addFromResourceBundleOrDefault(javax.faces.application.FacesMessage.Severity severity, String key, String defaultMessageTemplate, Object... params)
+ {
+ addFromResourceBundleOrDefault(toSeverity(severity), key, defaultMessageTemplate, params);
+ }
+
+ /**
+ * Create a new status message, looking up the message in the resource bundle
+ * using the provided key.
+ *
+ * The message will be added to the widget specified by the ID. The algorithm
+ * used determine which widget the id refers to is determined by the view
+ * layer implementation in use.
+ *
+ * You can also specify the severity, and parameters to be interpolated
+ *
+ * Deprecated, use {@link #addToControlFromResourceBundle(String, org.jboss.seam.international.StatusMessage.Severity, String, Object...)}
+ * instead
+ */
+ @Deprecated
+ public void addToControlFromResourceBundle(String id, javax.faces.application.FacesMessage.Severity severity, String key, Object... params)
+ {
+ addToControlFromResourceBundle(id, toSeverity(severity), key, params);
+ }
+
+ /**
+ * Add a status message, looking up the message in the resource bundle
+ * using the provided key. If the message is found, it is used, otherwise,
+ * the defaultMessageTemplate will be used.
+ *
+ * The message will be added to the widget specified by the ID. The algorithm
+ * used determine which widget the id refers to is determined by the view
+ * layer implementation in use.
+ *
+ * You can also specify the severity, and parameters to be interpolated
+ *
+ * Deprecated, use {@link #addToControlFromResourceBundleOrDefault(String, org.jboss.seam.international.StatusMessage.Severity, String, String, Object...)}
+ * instead
+ */
+ @Deprecated
+ public void addToControlFromResourceBundleOrDefault(String id, javax.faces.application.FacesMessage.Severity severity, String key, String defaultMessageTemplate, Object... params)
+ {
+ addToControlFromResourceBundleOrDefault(id, toSeverity(severity), key, defaultMessageTemplate, params);
+ }
+
+ public static FacesMessages instance()
+ {
+ if ( !Contexts.isConversationContextActive() )
+ {
+ throw new IllegalStateException("No active conversation context");
+ }
+ return (FacesMessages) Component.getInstance(StatusMessages.COMPONENT_NAME, ScopeType.CONVERSATION);
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesPage.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesPage.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/FacesPage.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,173 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.BUILT_IN;
+
+import java.io.Serializable;
+
+import org.jboss.seam.Component;
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+import org.jboss.seam.contexts.Contexts;
+import org.jboss.seam.core.Init;
+import org.jboss.seam.core.Manager;
+import org.jboss.seam.pageflow.Pageflow;
+import org.jboss.seam.web.Session;
+
+/**
+ * Book-keeping component that persists information
+ * about the conversation associated with the current
+ * page.
+ *
+ * @author Gavin King
+ *
+ */
+@Name("org.jboss.seam.faces.facesPage")
+@BypassInterceptors
+@Install(precedence=BUILT_IN, classDependencies="javax.faces.context.FacesContext")
+(a)Scope(ScopeType.PAGE)
+public class FacesPage implements Serializable
+{
+ private static final long serialVersionUID = 4807114041808347239L;
+ private String pageflowName;
+ private Integer pageflowCounter;
+ private String pageflowNodeName;
+
+ private String conversationId;
+ private boolean conversationIsLongRunning;
+
+ //private Map<String, Object> pageParameters;
+
+ public String getConversationId()
+ {
+ return conversationId;
+ }
+
+ public void discardTemporaryConversation()
+ {
+ conversationId = null;
+ conversationIsLongRunning = false;
+ }
+
+ public void discardNestedConversation(String outerConversationId)
+ {
+ conversationId = outerConversationId;
+ conversationIsLongRunning = true;
+ }
+
+ public void storeConversation(String conversationId)
+ {
+ this.conversationId = conversationId;
+ conversationIsLongRunning = true;
+ }
+
+ public void storePageflow()
+ {
+ if ( Init.instance().isJbpmInstalled() )
+ {
+ Pageflow pageflow = Pageflow.instance();
+ if ( pageflow.isInProcess() /*&& !pageflow.getProcessInstance().hasEnded()*/ && Manager.instance().isLongRunningConversation() )
+ {
+ pageflowName = pageflow.getSubProcessInstance().getProcessDefinition().getName();
+ pageflowNodeName = pageflow.getNode().getName();
+ pageflowCounter = pageflow.getPageflowCounter();
+ }
+ else
+ {
+ pageflowName = null;
+ pageflowNodeName = null;
+ pageflowCounter = null;
+ }
+ }
+ }
+
+ public static FacesPage instance()
+ {
+ if ( !Contexts.isPageContextActive() )
+ {
+ throw new IllegalStateException("No page context active");
+ }
+ return (FacesPage) Component.getInstance(FacesPage.class, ScopeType.PAGE);
+ }
+
+ public boolean isConversationLongRunning()
+ {
+ return conversationIsLongRunning;
+ }
+
+ public Integer getPageflowCounter()
+ {
+ return pageflowCounter;
+ }
+
+ public String getPageflowName()
+ {
+ return pageflowName;
+ }
+
+ public String getPageflowNodeName()
+ {
+ return pageflowNodeName;
+ }
+
+ public void storeConversation()
+ {
+ Manager manager = Manager.instance();
+
+ //we only need to execute this code when we are in the
+ //RENDER_RESPONSE phase, ie. not before redirects
+
+ Session session = Session.getInstance();
+ boolean sessionInvalid = session!=null && session.isInvalid();
+ if ( !sessionInvalid && manager.isLongRunningConversation() )
+ {
+ storeConversation( manager.getCurrentConversationId() );
+ }
+ else if ( !sessionInvalid && manager.isNestedConversation() )
+ {
+ discardNestedConversation( manager.getParentConversationId() );
+ }
+ else
+ {
+ discardTemporaryConversation();
+ }
+
+ /*if ( !sessionInvalid && Init.instance().isClientSideConversations() )
+ {
+ // if we are using client-side conversations, put the
+ // map containing the conversation context variables
+ // into the view root (or remove it for a temp
+ // conversation context)
+ Contexts.getConversationContext().flush();
+ }*/
+
+ }
+
+ /*public Map<String, Object> getPageParameters()
+ {
+ return pageParameters==null ? Collections.EMPTY_MAP : pageParameters;
+ }
+
+ public void setPageParameters(Map<String, Object> pageParameters)
+ {
+ this.pageParameters = pageParameters.isEmpty() ? null : pageParameters;
+ }
+
+ /**
+ * Used by test harness
+ *
+ * @param name the page parameter name
+ * @param value the value
+ */
+ /*public void setPageParameter(String name, Object value)
+ {
+ if (pageParameters==null)
+ {
+ pageParameters = new HashMap<String, Object>();
+ }
+ pageParameters.put(name, value);
+ }*/
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/HttpError.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/HttpError.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/HttpError.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,76 @@
+//$Id: HttpError.java 5350 2007-06-20 17:53:19Z gavin $
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.BUILT_IN;
+
+import java.io.IOException;
+
+import javax.faces.context.FacesContext;
+import javax.servlet.http.HttpServletResponse;
+
+import org.jboss.seam.Component;
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+import org.jboss.seam.contexts.Contexts;
+
+/**
+ * Convenient HTTP errors
+ *
+ * @author Gavin King
+ */
+(a)Scope(ScopeType.APPLICATION)
+@BypassInterceptors
+@Name("org.jboss.seam.faces.httpError")
+@Install(precedence=BUILT_IN, classDependencies="javax.faces.context.FacesContext")
+public class HttpError
+{
+ /**
+ * Send a HTTP error as the response
+ */
+ public void send(int code)
+ {
+ try
+ {
+ getResponse().sendError(code);
+ }
+ catch (IOException ioe)
+ {
+ throw new IllegalStateException(ioe);
+ }
+ FacesContext.getCurrentInstance().responseComplete();
+ }
+
+ /**
+ * Send a HTTP error as the response
+ */
+ public void send(int code, String message)
+ {
+ try
+ {
+ getResponse().sendError(code, message);
+ }
+ catch (IOException ioe)
+ {
+ throw new IllegalStateException(ioe);
+ }
+ FacesContext.getCurrentInstance().responseComplete();
+ }
+
+ private static HttpServletResponse getResponse()
+ {
+ return (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
+ }
+
+ public static HttpError instance()
+ {
+ if ( !Contexts.isApplicationContextActive() )
+ {
+ throw new IllegalStateException("No active application scope");
+ }
+ return (HttpError) Component.getInstance(HttpError.class, ScopeType.APPLICATION);
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/IsUserInRole.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/IsUserInRole.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/IsUserInRole.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,37 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.FRAMEWORK;
+
+import javax.faces.context.FacesContext;
+
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+
+/**
+ * Manager component for a map of roles assigned
+ * to the current user, as exposed via the JSF
+ * ExternalContext.
+ *
+ * @author Gavin King
+ */
+(a)Scope(ScopeType.APPLICATION)
+@BypassInterceptors
+@Name("org.jboss.seam.web.isUserInRole")
+@Install(precedence=FRAMEWORK, classDependencies="javax.faces.context.FacesContext")
+public class IsUserInRole extends org.jboss.seam.web.IsUserInRole
+{
+ @Override
+ protected Boolean isUserInRole(String role)
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ if ( facesContext != null )
+ {
+ return facesContext.getExternalContext().isUserInRole(role);
+ }
+
+ return super.isUserInRole(role);
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/Navigator.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/Navigator.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/Navigator.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,109 @@
+package org.jboss.seam.faces;
+
+import java.util.Map;
+
+import javax.faces.application.FacesMessage.Severity;
+import javax.faces.component.UIViewRoot;
+import javax.faces.context.FacesContext;
+
+import org.jboss.seam.contexts.Contexts;
+import org.jboss.seam.log.LogProvider;
+import org.jboss.seam.log.Logging;
+import org.jboss.seam.navigation.Pages;
+import org.jboss.seam.util.Strings;
+
+public abstract class Navigator
+{
+ private static final LogProvider log = Logging.getLogProvider(Navigator.class);
+
+ /**
+ * Send an error.
+ */
+ protected void error(int code, String message)
+ {
+ if ( log.isDebugEnabled() ) log.debug("sending error: " + code);
+ org.jboss.seam.faces.HttpError httpError = org.jboss.seam.faces.HttpError.instance();
+ if (message==null)
+ {
+ httpError.send(code);
+ }
+ else
+ {
+ httpError.send(code, message);
+ }
+ }
+
+ protected void redirectExternal(String url) {
+ FacesManager.instance().redirectToExternalURL(url);
+ }
+
+ protected void redirect(String viewId, Map<String, Object> parameters)
+ {
+ redirect(viewId, parameters, true);
+ }
+
+ /**
+ * Redirect to the view id.
+ */
+ protected void redirect(String viewId, Map<String, Object> parameters, boolean includePageParams)
+ {
+ if ( Strings.isEmpty(viewId) )
+ {
+ viewId = Pages.getCurrentViewId();
+ }
+ if ( log.isDebugEnabled() ) log.debug("redirecting to: " + viewId);
+ FacesManager.instance().redirect(viewId, parameters, true, includePageParams);
+ }
+
+ /**
+ * Render the view id.
+ */
+ protected void render(String viewId)
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ if ( !Strings.isEmpty(viewId) )
+ {
+ UIViewRoot viewRoot = facesContext.getApplication().getViewHandler()
+ .createView(facesContext, viewId);
+ facesContext.setViewRoot(viewRoot);
+ }
+ else
+ {
+ viewId = Pages.getViewId(facesContext); //just for the log message
+ }
+ if ( log.isDebugEnabled() ) log.debug("rendering: " + viewId);
+ facesContext.renderResponse();
+ }
+
+ protected static String getDisplayMessage(Exception e, String message)
+ {
+ if ( Strings.isEmpty(message) && e.getMessage()!=null )
+ {
+ return e.getMessage();
+ }
+ else
+ {
+ return message;
+ }
+ }
+
+ @SuppressWarnings("deprecation")
+ protected static void addFacesMessage(String message, Severity severity, String control, Object... params)
+ {
+ if ( Contexts.isConversationContextActive() )
+ {
+ if ( !Strings.isEmpty(message) )
+ {
+ if ( Strings.isEmpty(control) )
+ {
+ FacesMessages.instance().add(severity, message, params);
+ }
+ else
+ {
+ FacesMessages.instance().addToControl(control, severity, message, params);
+ }
+ }
+ }
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/Parameters.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/Parameters.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/Parameters.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,67 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.FRAMEWORK;
+
+import java.util.Map;
+
+import javax.faces.component.UIViewRoot;
+import javax.faces.context.FacesContext;
+import javax.faces.convert.Converter;
+
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+
+/**
+ * Access to request parameters in the JSF environment.
+ *
+ * @author Gavin King
+ *
+ */
+@Name("org.jboss.seam.web.parameters")
+@BypassInterceptors
+(a)Scope(ScopeType.STATELESS)
+@Install(precedence=FRAMEWORK, classDependencies="javax.faces.context.FacesContext")
+public class Parameters extends org.jboss.seam.web.Parameters
+{
+
+ @Override
+ protected Object convertRequestParameter(String requestParameter, Class type)
+ {
+ if ( String.class.equals(type) ) return requestParameter;
+
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ if (facesContext==null)
+ {
+ throw new IllegalStateException("No FacesContext associated with current thread, cannot convert request parameter type");
+ }
+ else
+ {
+ Converter converter = facesContext.getApplication().createConverter(type);
+ if (converter==null)
+ {
+ throw new IllegalArgumentException("no converter for type: " + type);
+ }
+ UIViewRoot viewRoot = facesContext.getViewRoot();
+ return converter.getAsObject(
+ facesContext,
+ viewRoot==null ? new UIViewRoot() : viewRoot, //have to pass something here, or get a totally useless NPE from JSF
+ requestParameter );
+ }
+ }
+
+ @Override
+ public Map<String, String[]> getRequestParameters()
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ if ( facesContext != null )
+ {
+ return facesContext.getExternalContext().getRequestParameterValuesMap();
+ }
+
+ return super.getRequestParameters();
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/Redirect.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/Redirect.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/Redirect.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,204 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.BUILT_IN;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.faces.context.FacesContext;
+
+import org.jboss.seam.Component;
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.PerNestedConversation;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+import org.jboss.seam.contexts.Contexts;
+import org.jboss.seam.core.AbstractMutable;
+import org.jboss.seam.core.Conversation;
+import org.jboss.seam.navigation.Pages;
+
+/**
+ * Convenient API for performing browser redirects with
+ * parameters.
+ *
+ * @author Gavin King
+ */
+@Name("org.jboss.seam.faces.redirect")
+@BypassInterceptors
+(a)Scope(ScopeType.CONVERSATION)
+@Install(precedence=BUILT_IN, classDependencies="javax.faces.context.FacesContext")
+@PerNestedConversation
+public class Redirect extends AbstractMutable implements Serializable
+{
+ private static final long serialVersionUID = 6947384474861235210L;
+ private String viewId;
+ private Map<String, Object> parameters = new HashMap<String, Object>();
+ private boolean conversationPropagationEnabled = true;
+ private boolean conversationBegun;
+
+ /**
+ * Get the JSF view id to redirect to
+ */
+ public String getViewId()
+ {
+ return viewId;
+ }
+
+ /**
+ * Set the JSF view id to redirect to
+ *
+ * @param viewId any JSF view id
+ */
+ public void setViewId(String viewId)
+ {
+ setDirty(this.viewId, viewId);
+ this.viewId = viewId;
+ }
+
+ /**
+ * Get all the request parameters that have been set
+ */
+ public Map<String, Object> getParameters()
+ {
+ return parameters;
+ }
+
+ /**
+ * Set a request parameter value (to set a multi-valued
+ * request parameter, pass an array or collection as
+ * the value)
+ */
+ public void setParameter(String name, Object value)
+ {
+ Object old = parameters.put(name, value);
+ setDirty(old, value);
+ }
+
+ /**
+ * Capture the view id and request parameters from the
+ * current request and squirrel them away so we can
+ * return here later in the conversation.
+ *
+ * @deprecated use captureCurrentView()
+ */
+ public void captureCurrentRequest()
+ {
+ parameters.clear();
+ FacesContext context = FacesContext.getCurrentInstance();
+ parameters.putAll( context.getExternalContext().getRequestParameterMap() );
+ viewId = Pages.getViewId(context);
+ setDirty();
+ }
+
+ /**
+ * Capture the view id, request parameters and page parameters (which take
+ * precedence) from the current request and squirrel them away so we can
+ * return here later in the conversation. If no conversation is active,
+ * begin a conversation. The conversation is terminated by {@link
+ * Redirect#returnToCapturedView()} if begun by this method.
+ *
+ * @see Redirect#returnToCapturedView()
+ */
+ public void captureCurrentView()
+ {
+ FacesContext context = FacesContext.getCurrentInstance();
+
+ // If this isn't a faces request then just return
+ if (context == null) return;
+
+ // first capture all request parameters
+ parameters.putAll( context.getExternalContext().getRequestParameterMap() );
+ // then preserve page parameters, overwriting request parameters with same names
+ parameters.putAll( Pages.instance().getStringValuesFromPageContext(context) );
+
+ // special case only needed for actionMethod if decide not to capture all request parameters
+ //if (context.getExternalContext().getRequestParameterMap().containsKey("actionMethod"))
+ //{
+ // parameters.put("actionMethod", context.getExternalContext().getRequestParameterMap().get("actionMethod"));
+ //}
+
+ viewId = Pages.getViewId(context);
+ conversationBegun = Conversation.instance().begin(true, false);
+ setDirty();
+ //if the request ends with an exception,
+ //the conversation context never gets
+ //flushed....
+ Contexts.getConversationContext().flush();
+ }
+
+ /**
+ * Should the conversation be propagated across the redirect?
+ * @return true by default
+ */
+ public boolean isConversationPropagationEnabled()
+ {
+ return conversationPropagationEnabled;
+ }
+
+ /**
+ * Note that conversations are propagated by default
+ */
+ public void setConversationPropagationEnabled(boolean conversationPropagationEnabled)
+ {
+ this.conversationPropagationEnabled = conversationPropagationEnabled;
+ }
+
+ /**
+ * Perform the redirect
+ */
+ public void execute()
+ {
+ FacesManager.instance().redirect(viewId, parameters, conversationPropagationEnabled, true);
+ }
+
+ /**
+ * Redirect to the captured view, and end any conversation
+ * that began in captureCurrentView().
+ *
+ *@see Redirect#captureCurrentView()
+ */
+ public boolean returnToCapturedView()
+ {
+ if (viewId!=null)
+ {
+ if (conversationBegun)
+ {
+ Conversation.instance().end();
+ }
+ execute();
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ //TODO: replacement for Conversation.endAndRedirect()
+ /*public boolean returnToParentView()
+ {
+ Manager manager = Manager.instance();
+ String viewId = manager.getParentConversationViewId();
+ if (viewId==null)
+ {
+ return false;
+ }
+ else
+ {
+ manager.redirect(viewId);
+ return true;
+ }
+ }*/
+
+ public static Redirect instance()
+ {
+ if ( !Contexts.isConversationContextActive() )
+ {
+ throw new IllegalStateException("No active conversation context");
+ }
+ return (Redirect) Component.getInstance(Redirect.class, ScopeType.CONVERSATION);
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/RedirectException.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/RedirectException.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/RedirectException.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,17 @@
+package org.jboss.seam.faces;
+
+import java.io.IOException;
+
+public class RedirectException extends RuntimeException
+{
+
+ public RedirectException(IOException ioe)
+ {
+ super(ioe);
+ }
+
+ public RedirectException(String message)
+ {
+ super(message);
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/Renderer.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/Renderer.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/Renderer.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,23 @@
+package org.jboss.seam.faces;
+
+import org.jboss.seam.Component;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+
+/**
+ * A component for direct rendering of
+ * templates. Especially useful with
+ * Seam Mail.
+ *
+ */
+@Name("org.jboss.seam.faces.renderer")
+@Install(false)
+public abstract class Renderer
+{
+ public abstract String render(String viewId);
+
+ public static Renderer instance()
+ {
+ return (Renderer) Component.getInstance(Renderer.class);
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/ResourceLoader.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/ResourceLoader.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/ResourceLoader.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,56 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.FRAMEWORK;
+
+import java.io.InputStream;
+import java.net.URL;
+
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+import org.jboss.seam.util.FacesResources;
+
+/**
+ * Access to application resources in tye JSF environment.
+ *
+ * @author Gavin King
+ *
+ */
+(a)Scope(ScopeType.STATELESS)
+@BypassInterceptors
+@Install(precedence=FRAMEWORK, classDependencies="javax.faces.context.FacesContext")
+@Name("org.jboss.seam.core.resourceLoader")
+public class ResourceLoader extends org.jboss.seam.core.ResourceLoader
+{
+
+ @Override
+ public InputStream getResourceAsStream(String resource)
+ {
+ javax.faces.context.FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
+ if (context!=null)
+ {
+ return FacesResources.getResourceAsStream( resource, context.getExternalContext() );
+ }
+ else
+ {
+ return super.getResourceAsStream(resource);
+ }
+ }
+
+ @Override
+ public URL getResource(String resource)
+ {
+ javax.faces.context.FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
+ if (context!=null)
+ {
+ return FacesResources.getResource( resource, context.getExternalContext() );
+ }
+ else
+ {
+ return super.getResource(resource);
+ }
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/Selector.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/Selector.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/Selector.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,122 @@
+package org.jboss.seam.faces;
+
+import java.io.Serializable;
+
+import javax.faces.context.FacesContext;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+
+import org.jboss.seam.core.AbstractMutable;
+
+/**
+ * Support for selector objects which remember their selection as a cookie
+ *
+ * @author Gavin King
+ */
+public abstract class Selector extends AbstractMutable implements Serializable
+{
+ public static final int DEFAULT_MAX_AGE = 31536000; // 1 year in seconds
+ private boolean cookieEnabled;
+ private int cookieMaxAge = DEFAULT_MAX_AGE;
+ private String cookiePath= "/";
+
+ /**
+ * Is the cookie enabled?
+ * @return false by default
+ */
+ public boolean isCookieEnabled()
+ {
+ return cookieEnabled;
+ }
+ public void setCookieEnabled(boolean cookieEnabled)
+ {
+ setDirty(this.cookieEnabled, cookieEnabled);
+ this.cookieEnabled = cookieEnabled;
+ }
+ /**
+ * The max age of the cookie
+ * @return 1 year by default
+ */
+ public int getCookieMaxAge()
+ {
+ return cookieMaxAge;
+ }
+ public void setCookieMaxAge(int cookieMaxAge)
+ {
+ this.cookieMaxAge = cookieMaxAge;
+ }
+
+ public String getCookiePath()
+ {
+ return cookiePath;
+ }
+
+ public void setCookiePath(String cookiePath)
+ {
+ this.cookiePath = cookiePath;
+ }
+
+ /**
+ * Override to define the cookie name
+ */
+ protected abstract String getCookieName();
+
+ /**
+ * Get the value of the cookie
+ */
+ protected String getCookieValueIfEnabled()
+ {
+ return isCookieEnabled() ?
+ getCookieValue() : null;
+ }
+
+ protected Cookie getCookie()
+ {
+ FacesContext ctx = FacesContext.getCurrentInstance();
+ if (ctx != null)
+ {
+ return (Cookie) ctx.getExternalContext().getRequestCookieMap()
+ .get( getCookieName() );
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ protected String getCookieValue()
+ {
+ Cookie cookie = getCookie();
+ return cookie==null ? null : cookie.getValue();
+ }
+
+ protected void clearCookieValue()
+ {
+ Cookie cookie = getCookie();
+ if ( cookie!=null )
+ {
+ HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
+ cookie.setValue(null);
+ cookie.setPath(cookiePath);
+ cookie.setMaxAge(0);
+ response.addCookie(cookie);
+ }
+ }
+
+ /**
+ * Set the cookie
+ */
+ protected void setCookieValueIfEnabled(String value)
+ {
+ FacesContext ctx = FacesContext.getCurrentInstance();
+
+ if ( isCookieEnabled() && ctx != null)
+ {
+ HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();
+ Cookie cookie = new Cookie( getCookieName(), value );
+ cookie.setMaxAge( getCookieMaxAge() );
+ cookie.setPath(cookiePath);
+ response.addCookie(cookie);
+ }
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/Switcher.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/Switcher.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/Switcher.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,125 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.annotations.Install.BUILT_IN;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.faces.model.SelectItem;
+
+import org.jboss.seam.ScopeType;
+import org.jboss.seam.annotations.Create;
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+import org.jboss.seam.core.ConversationEntries;
+import org.jboss.seam.core.ConversationEntry;
+import org.jboss.seam.core.Manager;
+import org.jboss.seam.web.Session;
+
+/**
+ * Support for the conversation switcher drop-down menu.
+ *
+ * @author Gavin King
+ */
+(a)Scope(ScopeType.PAGE)
+@Name("org.jboss.seam.faces.switcher")
+@Install(precedence=BUILT_IN, classDependencies="javax.faces.context.FacesContext")
+@BypassInterceptors
+public class Switcher implements Serializable
+{
+
+ private static final long serialVersionUID = -6403911073853051938L;
+ private List<SelectItem> selectItems;
+ private String conversationIdOrOutcome;
+ private String resultingConversationIdOrOutcome;
+
+ @Create
+ public void createSelectItems()
+ {
+ ConversationEntries conversationEntries = ConversationEntries.getInstance();
+ if (conversationEntries==null)
+ {
+ selectItems = Collections.EMPTY_LIST;
+ }
+ else
+ {
+ Set<ConversationEntry> orderedEntries = new TreeSet<ConversationEntry>();
+ orderedEntries.addAll( conversationEntries.getConversationEntries() );
+ selectItems = new ArrayList<SelectItem>( conversationEntries.size() );
+ for ( ConversationEntry entry: orderedEntries )
+ {
+ if ( entry.isDisplayable() && !Session.instance().isInvalid() )
+ {
+ selectItems.add( new SelectItem( entry.getId(), entry.getDescription() ) );
+ }
+ }
+ }
+ }
+
+ public List<SelectItem> getSelectItems()
+ {
+ return selectItems;
+ }
+
+ private String getLongRunningConversationId()
+ {
+ Manager manager = Manager.instance();
+ if ( manager.isLongRunningConversation() )
+ {
+ return manager.getCurrentConversationId();
+ }
+ else if ( manager.isNestedConversation() )
+ {
+ return manager.getParentConversationId();
+ }
+ else
+ {
+ //TODO: is there any way to set it to the current outcome, instead of null?
+ return null;
+ }
+ }
+
+ public String getConversationIdOrOutcome()
+ {
+ return resultingConversationIdOrOutcome==null ?
+ getLongRunningConversationId() :
+ resultingConversationIdOrOutcome;
+ }
+
+ public void setConversationIdOrOutcome(String selectedId)
+ {
+ this.conversationIdOrOutcome = selectedId;
+ }
+
+ public String select()
+ {
+
+ boolean isOutcome = conversationIdOrOutcome==null ||
+ (!Character.isDigit(conversationIdOrOutcome.charAt(0)) && conversationIdOrOutcome.indexOf(':') < 0);
+
+ String actualOutcome;
+ if (isOutcome)
+ {
+ resultingConversationIdOrOutcome = conversationIdOrOutcome;
+ actualOutcome = conversationIdOrOutcome;
+ }
+ else
+ {
+ ConversationEntry ce = ConversationEntries.instance().getConversationEntry(conversationIdOrOutcome);
+ if (ce!=null)
+ {
+ resultingConversationIdOrOutcome = ce.getId();
+ ce.redirect();
+ }
+ actualOutcome = null;
+ }
+ return actualOutcome;
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/UiComponent.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/UiComponent.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/UiComponent.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,81 @@
+package org.jboss.seam.faces;
+
+import static org.jboss.seam.ScopeType.STATELESS;
+import static org.jboss.seam.annotations.Install.BUILT_IN;
+
+import java.util.AbstractMap;
+import java.util.Map;
+import java.util.Set;
+
+import javax.faces.component.UIComponent;
+import javax.faces.component.UIViewRoot;
+import javax.faces.context.FacesContext;
+
+import org.jboss.seam.annotations.Install;
+import org.jboss.seam.annotations.Name;
+import org.jboss.seam.annotations.Scope;
+import org.jboss.seam.annotations.Unwrap;
+import org.jboss.seam.annotations.intercept.BypassInterceptors;
+
+/**
+ * Access to UIComponents in the current view, by id.
+ *
+ * @author Gavin King
+ *
+ */
+@Name("org.jboss.seam.faces.uiComponent")
+@BypassInterceptors
+@Scope(STATELESS)
+@Install(precedence=BUILT_IN, classDependencies="javax.faces.context.FacesContext")
+public class UiComponent
+{
+
+ @Unwrap
+ public Map<String, UIComponent> getViewComponents()
+ {
+ return new AbstractMap<String, UIComponent>()
+ {
+
+ @Override
+ public boolean containsKey(Object key) {
+ return get(key) != null;
+ }
+
+
+ @Override
+ public Set<Map.Entry<String, UIComponent>> entrySet()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public UIComponent get(Object key)
+ {
+ if ( !(key instanceof String) ) return null;
+ try
+ {
+ FacesContext context = FacesContext.getCurrentInstance();
+
+ if (context == null) {
+ return null;
+ }
+
+ UIViewRoot viewRoot = context.getViewRoot();
+
+ if (viewRoot == null)
+ {
+ return null;
+ }
+
+ return viewRoot.findComponent( (String) key );
+ }
+ catch (IllegalArgumentException iae)
+ {
+ return null;
+ }
+ }
+
+ };
+ }
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/UserPrincipal.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/UserPrincipal.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/UserPrincipal.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,30 @@
+package org.jboss.seam.faces;
+
+import java.security.Principal;
+
+import javax.annotation.Named;
+import javax.context.ApplicationScoped;
+import javax.faces.context.FacesContext;
+
+/**
+ * Manager component for the current user Principal
+ * exposed via the JSF ExternalContext.
+ *
+ * @author Gavin King
+ */
+@Named
+@ApplicationScoped
+public class UserPrincipal extends org.jboss.seam.web.UserPrincipal
+{
+ @Unwrap @Override
+ public Principal getUserPrincipal()
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ if ( facesContext != null )
+ {
+ return facesContext.getExternalContext().getUserPrincipal();
+ }
+
+ return super.getUserPrincipal();
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/Validation.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/Validation.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/Validation.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,51 @@
+package org.jboss.seam.faces;
+
+import javax.annotation.Named;
+import javax.faces.context.FacesContext;
+import javax.inject.Current;
+import javax.inject.manager.Manager;
+
+import org.jboss.seam.faces.events.ValidationFailedEvent;
+
+/**
+ * Allows the application to determine whether the JSF validation
+ * phase completed successfully, or if a validation failure
+ * occurred.
+ *
+ * @author Gavin king
+ *
+ */
+@Named
+public class Validation
+{
+ private boolean succeeded;
+ private boolean failed;
+
+ @Current Manager manager;
+
+ public void afterProcessValidations(FacesContext facesContext)
+ {
+ failed = facesContext.getRenderResponse();
+ if (failed)
+ {
+ manager.fireEvent(new ValidationFailedEvent());
+ }
+ succeeded = !failed;
+ }
+
+ public boolean isSucceeded()
+ {
+ return succeeded;
+ }
+
+ public boolean isFailed()
+ {
+ return failed;
+ }
+
+ public void fail()
+ {
+ failed = true;
+ succeeded = false;
+ }
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/events/ValidationFailedEvent.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/events/ValidationFailedEvent.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/events/ValidationFailedEvent.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,11 @@
+package org.jboss.seam.faces.events;
+
+/**
+ * This event is raised when JSF validation fails.
+ *
+ * @author Shane Bryzak
+ */
+public class ValidationFailedEvent
+{
+
+}
Added: modules/trunk/faces/src/main/java/org/jboss/seam/faces/package-info.java
===================================================================
--- modules/trunk/faces/src/main/java/org/jboss/seam/faces/package-info.java (rev 0)
+++ modules/trunk/faces/src/main/java/org/jboss/seam/faces/package-info.java 2009-04-23 01:09:20 UTC (rev 10601)
@@ -0,0 +1,11 @@
+/**
+ * A set of Seam components for working with JSF.
+ * Some of these components extend core components
+ * and add JSF-specific functionality. Others
+ * exist to put a friendly face to JSF.
+ */
+@AutoCreate
+package org.jboss.seam.faces;
+
+import org.jboss.seam.annotations.AutoCreate;
+
17 years
Seam SVN: r10600 - branches/community/Seam_2_1/src/main/org/jboss/seam/intercept.
by seam-commits@lists.jboss.org
Author: shane.bryzak(a)jboss.com
Date: 2009-04-22 20:41:03 -0400 (Wed, 22 Apr 2009)
New Revision: 10600
Modified:
branches/community/Seam_2_1/src/main/org/jboss/seam/intercept/RootInterceptor.java
Log:
JBSEAM-4143
Modified: branches/community/Seam_2_1/src/main/org/jboss/seam/intercept/RootInterceptor.java
===================================================================
--- branches/community/Seam_2_1/src/main/org/jboss/seam/intercept/RootInterceptor.java 2009-04-23 00:37:40 UTC (rev 10599)
+++ branches/community/Seam_2_1/src/main/org/jboss/seam/intercept/RootInterceptor.java 2009-04-23 00:41:03 UTC (rev 10600)
@@ -202,23 +202,7 @@
getComponent().isInterceptionEnabled() &&
!isBypassed(method) &&
!isClearDirtyMethod(method, bean);
-
- if (componentName.equals("hotelSearch") && method !=null) {
- System.out.println("*********** BYPASS?[" + res + "] " + componentName + ":" + method);
- System.out.println("-" + method.isAnnotationPresent(BypassInterceptors.class));
- if (method.getName().equals("hashCode")) {
-
- try {
- System.out.println("*A " + bean.getClass().getMethod("hashCode"));
-
- System.out.println("*B " + bean.getClass().getDeclaredMethod("hashCode"));
- } catch (Exception e) {}
- return false;
- }
-
- }
-
return res;
}
17 years
Seam SVN: r10599 - in modules/trunk/security/src/main/java/org/jboss/seam/security: callbacks and 3 other directories.
by seam-commits@lists.jboss.org
Author: shane.bryzak(a)jboss.com
Date: 2009-04-22 20:37:40 -0400 (Wed, 22 Apr 2009)
New Revision: 10599
Added:
modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/
modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/AuthenticatorCallback.java
modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/IdentityCallback.java
modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/IdentityManagerCallback.java
modules/trunk/security/src/main/java/org/jboss/seam/security/util/
modules/trunk/security/src/main/java/org/jboss/seam/security/util/Strings.java
Modified:
modules/trunk/security/src/main/java/org/jboss/seam/security/Authenticator.java
modules/trunk/security/src/main/java/org/jboss/seam/security/Credentials.java
modules/trunk/security/src/main/java/org/jboss/seam/security/Identity.java
modules/trunk/security/src/main/java/org/jboss/seam/security/JaasConfiguration.java
modules/trunk/security/src/main/java/org/jboss/seam/security/jaas/SeamLoginModule.java
modules/trunk/security/src/main/java/org/jboss/seam/security/management/IdentityManager.java
Log:
fix SeamLoginModule
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/Authenticator.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/Authenticator.java 2009-04-22 22:55:46 UTC (rev 10598)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/Authenticator.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -7,5 +7,5 @@
*/
public interface Authenticator
{
- void authenticate();
+ boolean authenticate();
}
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/Credentials.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/Credentials.java 2009-04-22 22:55:46 UTC (rev 10598)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/Credentials.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -109,37 +109,5 @@
public String toString()
{
return "Credentials[" + username + "]";
- }
-
-
- /**
- * Creates a callback handler that can handle a standard username/password
- * callback, using the username and password properties.
- */
- public CallbackHandler createCallbackHandler()
- {
- return new CallbackHandler()
- {
- public void handle(Callback[] callbacks)
- throws IOException, UnsupportedCallbackException
- {
- for (int i=0; i < callbacks.length; i++)
- {
- if (callbacks[i] instanceof NameCallback)
- {
- ( (NameCallback) callbacks[i] ).setName(getUsername());
- }
- else if (callbacks[i] instanceof PasswordCallback)
- {
- ( (PasswordCallback) callbacks[i] ).setPassword( getPassword() != null ?
- getPassword().toCharArray() : null );
- }
- else
- {
- log.warn("Unsupported callback " + callbacks[i]);
- }
- }
- }
- };
- }
+ }
}
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/Identity.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/Identity.java 2009-04-22 22:55:46 UTC (rev 10598)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/Identity.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -1,5 +1,6 @@
package org.jboss.seam.security;
+import java.io.IOException;
import java.io.Serializable;
import java.security.Principal;
import java.security.acl.Group;
@@ -7,18 +8,29 @@
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
+import java.util.Set;
import javax.annotation.Named;
import javax.context.SessionScoped;
import javax.inject.Current;
import javax.inject.Initializer;
+import javax.inject.manager.Bean;
import javax.inject.manager.Manager;
import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.jboss.webbeans.log.LogProvider;
import org.jboss.webbeans.log.Logging;
+import org.jboss.seam.security.callbacks.AuthenticatorCallback;
+import org.jboss.seam.security.callbacks.IdentityCallback;
+import org.jboss.seam.security.callbacks.IdentityManagerCallback;
import org.jboss.seam.security.events.AlreadyLoggedInEvent;
import org.jboss.seam.security.events.LoggedInEvent;
import org.jboss.seam.security.events.LoggedOutEvent;
@@ -28,6 +40,7 @@
import org.jboss.seam.security.events.PostAuthenticateEvent;
import org.jboss.seam.security.events.PreAuthenticateEvent;
import org.jboss.seam.security.events.QuietLoginEvent;
+import org.jboss.seam.security.management.IdentityManager;
import org.jboss.seam.security.permission.PermissionMapper;
/**
@@ -78,12 +91,6 @@
{
securityEnabled = enabled;
}
-
- public static Identity instance()
- {
- // TODO - implement
- return null;
- }
/**
* Simple check that returns true if the user is logged in, without attempting to authenticate
@@ -348,13 +355,75 @@
if (getJaasConfigName() != null)
{
return new LoginContext(getJaasConfigName(), getSubject(),
- credentials.createCallbackHandler());
+ createCallbackHandler());
}
+ Bean<Configuration> configBean = manager.resolveByType(Configuration.class).iterator().next();
+ Configuration config = manager.getInstance(configBean);
+
return new LoginContext(JaasConfiguration.DEFAULT_JAAS_CONFIG_NAME, getSubject(),
- credentials.createCallbackHandler(), JaasConfiguration.instance());
+ createCallbackHandler(), config);
}
+
+ /**
+ * Creates a callback handler that can handle a standard username/password
+ * callback, using the credentials username and password properties
+ */
+ public CallbackHandler createCallbackHandler()
+ {
+ final Identity identity = this;
+ final Authenticator authenticator;
+ final IdentityManager identityManager = manager.getInstanceByType(IdentityManager.class);
+
+ Set<Bean<Authenticator>> authenticators = manager.resolveByType(Authenticator.class);
+ if (authenticators.size() > 0)
+ {
+ Bean<Authenticator> authenticatorBean = authenticators.iterator().next();
+ authenticator = manager.getInstance(authenticatorBean);
+ }
+ else
+ {
+ authenticator = null;
+ }
+
+ return new CallbackHandler()
+ {
+ public void handle(Callback[] callbacks)
+ throws IOException, UnsupportedCallbackException
+ {
+ for (int i=0; i < callbacks.length; i++)
+ {
+ if (callbacks[i] instanceof NameCallback)
+ {
+ ( (NameCallback) callbacks[i] ).setName(credentials.getUsername());
+ }
+ else if (callbacks[i] instanceof PasswordCallback)
+ {
+ ( (PasswordCallback) callbacks[i] ).setPassword( credentials.getPassword() != null ?
+ credentials.getPassword().toCharArray() : null );
+ }
+ else if (callbacks[i] instanceof IdentityCallback)
+ {
+ ((IdentityCallback ) callbacks[i]).setIdentity(identity);
+ }
+ else if (callbacks[i] instanceof AuthenticatorCallback)
+ {
+ ((AuthenticatorCallback) callbacks[i]).setAuthenticator(authenticator);
+ }
+ else if (callbacks[i] instanceof IdentityManagerCallback)
+ {
+ ((IdentityManagerCallback) callbacks[i]).setIdentityManager(identityManager);
+ }
+ else
+ {
+ log.warn("Unsupported callback " + callbacks[i]);
+ }
+ }
+ }
+ };
+ }
+
public void logout()
{
if (isLoggedIn())
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/JaasConfiguration.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/JaasConfiguration.java 2009-04-22 22:55:46 UTC (rev 10598)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/JaasConfiguration.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -5,12 +5,13 @@
import javax.context.ApplicationScoped;
import javax.inject.Produces;
import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
import org.jboss.seam.security.jaas.SeamLoginModule;
/**
- * Factory for the JAAS Configuration used by Seam Security.
+ * Producer for the JAAS Configuration used by Seam Security.
*
* @author Shane Bryzak
*
@@ -19,9 +20,9 @@
{
static final String DEFAULT_JAAS_CONFIG_NAME = "default";
- protected javax.security.auth.login.Configuration createConfiguration()
+ protected Configuration createConfiguration()
{
- return new javax.security.auth.login.Configuration()
+ return new Configuration()
{
private AppConfigurationEntry[] aces = { createAppConfigurationEntry() };
@@ -45,7 +46,7 @@
);
}
- @Produces @ApplicationScoped javax.security.auth.login.Configuration getConfiguration()
+ @Produces @ApplicationScoped Configuration getConfiguration()
{
return createConfiguration();
}
Added: modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/AuthenticatorCallback.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/AuthenticatorCallback.java (rev 0)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/AuthenticatorCallback.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -0,0 +1,29 @@
+package org.jboss.seam.security.callbacks;
+
+import java.io.Serializable;
+
+import javax.security.auth.callback.Callback;
+
+import org.jboss.seam.security.Authenticator;
+
+/**
+ * This callback implementation is used to provide an instance of the Authenticator bean to the LoginModule
+ *
+ * @author Shane Bryzak
+ */
+public class AuthenticatorCallback implements Serializable, Callback
+{
+ private static final long serialVersionUID = -6186364148255506167L;
+
+ private Authenticator authenticator;
+
+ public Authenticator getAuthenticator()
+ {
+ return authenticator;
+ }
+
+ public void setAuthenticator(Authenticator authenticator)
+ {
+ this.authenticator = authenticator;
+ }
+}
Added: modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/IdentityCallback.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/IdentityCallback.java (rev 0)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/IdentityCallback.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -0,0 +1,29 @@
+package org.jboss.seam.security.callbacks;
+
+import java.io.Serializable;
+
+import javax.security.auth.callback.Callback;
+
+import org.jboss.seam.security.Identity;
+
+/**
+ * This callback implementation is used to provide an instance of the Identity bean to the LoginModule
+ *
+ * @author Shane Bryzak
+ */
+public class IdentityCallback implements Serializable, Callback
+{
+ private static final long serialVersionUID = 5720975438991518059L;
+
+ private Identity identity;
+
+ public void setIdentity(Identity identity)
+ {
+ this.identity = identity;
+ }
+
+ public Identity getIdentity()
+ {
+ return identity;
+ }
+}
Added: modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/IdentityManagerCallback.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/IdentityManagerCallback.java (rev 0)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/callbacks/IdentityManagerCallback.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -0,0 +1,29 @@
+package org.jboss.seam.security.callbacks;
+
+import java.io.Serializable;
+
+import javax.security.auth.callback.Callback;
+
+import org.jboss.seam.security.management.IdentityManager;
+
+/**
+ * This callback implementation is used to provide an instance of the IdentityManager bean to the LoginModule
+ *
+ * @author Shane Bryzak
+ */
+public class IdentityManagerCallback implements Serializable, Callback
+{
+ private static final long serialVersionUID = 8430300053672194472L;
+
+ private IdentityManager identityManager;
+
+ public IdentityManager getIdentityManager()
+ {
+ return identityManager;
+ }
+
+ public void setIdentityManager(IdentityManager identityManager)
+ {
+ this.identityManager = identityManager;
+ }
+}
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/jaas/SeamLoginModule.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/jaas/SeamLoginModule.java 2009-04-22 22:55:46 UTC (rev 10598)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/jaas/SeamLoginModule.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -7,7 +7,6 @@
import java.util.Map;
import java.util.Set;
-import javax.inject.manager.Manager;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
@@ -16,15 +15,17 @@
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
-import org.jboss.webbeans.log.LogProvider;
-import org.jboss.webbeans.log.Logging;
-import org.jboss.seam.security.Identity;
import org.jboss.seam.security.SimpleGroup;
import org.jboss.seam.security.SimplePrincipal;
+import org.jboss.seam.security.callbacks.AuthenticatorCallback;
+import org.jboss.seam.security.callbacks.IdentityCallback;
+import org.jboss.seam.security.callbacks.IdentityManagerCallback;
import org.jboss.seam.security.management.IdentityManager;
+import org.jboss.webbeans.log.LogProvider;
+import org.jboss.webbeans.log.Logging;
/**
- * Performs authentication using a Seam component
+ * Performs authentication using a Seam component or Identity Management
*
* @author Shane Bryzak
*/
@@ -82,74 +83,63 @@
public boolean login()
throws LoginException
- {
+ {
+ PasswordCallback cbPassword = null;
try
{
NameCallback cbName = new NameCallback("Enter username");
- PasswordCallback cbPassword = new PasswordCallback("Enter password", false);
-
- // Get the username and password from the callback handler
- callbackHandler.handle(new Callback[] { cbName, cbPassword });
- username = cbName.getName();
- }
- catch (Exception ex)
- {
- log.error("Error logging in", ex);
- LoginException le = new LoginException(ex.getMessage());
- le.initCause(ex);
- throw le;
- }
+ cbPassword = new PasswordCallback("Enter password", false);
+
+ IdentityCallback idCallback = new IdentityCallback();
+ AuthenticatorCallback authCallback = new AuthenticatorCallback();
+ IdentityManagerCallback idmCallback = new IdentityManagerCallback();
- // If an authentication method has been specified, use that to authenticate
- MethodExpression mb = Identity.instance().getAuthenticateMethod();
- if (mb != null)
- {
- try
- {
- return (Boolean) mb.invoke();
- }
- catch (Exception ex)
- {
- log.error("Error invoking login method", ex);
- throw new LoginException(ex.getMessage());
- }
- }
-
- // Otherwise if identity management is enabled, use it.
- IdentityManager identityManager = IdentityManager.instance();
- if (identityManager != null && identityManager.isEnabled())
- {
- Identity identity = Identity.instance();
+ // Get the username, password and identity from the callback handler
+ callbackHandler.handle(new Callback[] { cbName, cbPassword, idCallback, authCallback, idmCallback });
- try
+ username = cbName.getName();
+
+ // If an authenticator method has been specified, use that to authenticate
+ if (authCallback.getAuthenticator() != null)
{
- boolean success = identityManager.authenticate(username, identity.getCredentials().getPassword());
+ return authCallback.getAuthenticator().authenticate();
+ }
+
+ // Otherwise if identity management is enabled, use it.
+ IdentityManager identityManager = idmCallback.getIdentityManager();
+ if (identityManager != null && identityManager.isEnabled())
+ {
+ boolean success = identityManager.authenticate(username,
+ new String(cbPassword.getPassword()));
if (success)
{
for (String role : identityManager.getImpliedRoles(username))
{
- identity.addRole(role);
+ idCallback.getIdentity().addRole(role);
}
}
return success;
}
- catch (Exception ex)
+ else
{
- log.error("Error invoking login method", ex);
- LoginException le = new LoginException(ex.getMessage());
- le.initCause(ex);
- throw le;
+ log.error("No authentication method defined - " +
+ "please define authenticate-method for <security:identity/> in components.xml");
+ throw new LoginException("No authentication method defined");
}
}
- else
+ catch (Exception ex)
{
- log.error("No authentication method defined - " +
- "please define authenticate-method for <security:identity/> in components.xml");
- throw new LoginException("No authentication method defined");
+ log.error("Error logging in", ex);
+ LoginException le = new LoginException(ex.getMessage());
+ le.initCause(ex);
+ throw le;
+ }
+ finally
+ {
+ cbPassword.clearPassword();
}
-
}
public boolean logout() throws LoginException
Modified: modules/trunk/security/src/main/java/org/jboss/seam/security/management/IdentityManager.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/management/IdentityManager.java 2009-04-22 22:55:46 UTC (rev 10598)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/management/IdentityManager.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -1,37 +1,33 @@
package org.jboss.seam.security.management;
-import static org.jboss.seam.ScopeType.EVENT;
-import static org.jboss.seam.annotations.Install.BUILT_IN;
-
import java.io.Serializable;
import java.security.Principal;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
-import org.jboss.seam.Component;
-import org.jboss.seam.annotations.Create;
-import org.jboss.seam.annotations.Install;
-import org.jboss.seam.annotations.Name;
-import org.jboss.seam.annotations.Scope;
-import org.jboss.seam.annotations.intercept.BypassInterceptors;
-import org.jboss.seam.contexts.Contexts;
-import org.jboss.seam.log.LogProvider;
-import org.jboss.seam.log.Logging;
+import javax.annotation.Named;
+import javax.context.RequestScoped;
+import javax.inject.Current;
+import javax.inject.Initializer;
+import javax.inject.manager.Manager;
+
+import org.jboss.webbeans.log.LogProvider;
+import org.jboss.webbeans.log.Logging;
import org.jboss.seam.security.Identity;
-import org.jboss.seam.util.Strings;
+import org.jboss.seam.security.util.Strings;
/**
* Identity Management API, deals with user name/password-based identity management.
*
* @author Shane Bryzak
*/
-@Scope(EVENT)
-@Name("org.jboss.seam.security.identityManager")
-@Install(precedence = BUILT_IN)
-@BypassInterceptors
+@Named
+@RequestScoped
public class IdentityManager implements Serializable
{
+ private static final long serialVersionUID = 6864253169970552893L;
+
public static final String USER_PERMISSION_NAME = "seam.user";
public static final String ROLE_PERMISSION_NAME = "seam.role";
@@ -45,7 +41,10 @@
private IdentityStore identityStore;
private IdentityStore roleIdentityStore;
- @Create
+ @Current Manager manager;
+ @Current Identity identity;
+
+ @Initializer
public void create()
{
initIdentityStore();
@@ -55,7 +54,7 @@
{
// Default to JpaIdentityStore
if (identityStore == null)
- {
+ {
identityStore = (IdentityStore) Component.getInstance(JpaIdentityStore.class, true);
}
@@ -71,24 +70,6 @@
}
}
- public static IdentityManager instance()
- {
- if ( !Contexts.isEventContextActive() )
- {
- throw new IllegalStateException("No active event context");
- }
-
- IdentityManager instance = (IdentityManager) Component.getInstance(
- IdentityManager.class, EVENT);
-
- if (instance == null)
- {
- throw new IllegalStateException("No IdentityManager could be created");
- }
-
- return instance;
- }
-
public boolean createUser(String name, String password)
{
return createUser(name, password, null, null);
@@ -96,79 +77,79 @@
public boolean createUser(String name, String password, String firstname, String lastname)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_CREATE);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_CREATE);
return identityStore.createUser(name, password, firstname, lastname);
}
public boolean deleteUser(String name)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_DELETE);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_DELETE);
return identityStore.deleteUser(name);
}
public boolean enableUser(String name)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
return identityStore.enableUser(name);
}
public boolean disableUser(String name)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
return identityStore.disableUser(name);
}
public boolean changePassword(String name, String password)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
return identityStore.changePassword(name, password);
}
public boolean isUserEnabled(String name)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_READ);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_READ);
return identityStore.isUserEnabled(name);
}
public boolean grantRole(String name, String role)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
return roleIdentityStore.grantRole(name, role);
}
public boolean revokeRole(String name, String role)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_UPDATE);
return roleIdentityStore.revokeRole(name, role);
}
public boolean createRole(String role)
{
- Identity.instance().checkPermission(ROLE_PERMISSION_NAME, PERMISSION_CREATE);
+ identity.checkPermission(ROLE_PERMISSION_NAME, PERMISSION_CREATE);
return roleIdentityStore.createRole(role);
}
public boolean deleteRole(String role)
{
- Identity.instance().checkPermission(ROLE_PERMISSION_NAME, PERMISSION_DELETE);
+ identity.checkPermission(ROLE_PERMISSION_NAME, PERMISSION_DELETE);
return roleIdentityStore.deleteRole(role);
}
public boolean addRoleToGroup(String role, String group)
{
- Identity.instance().checkPermission(ROLE_PERMISSION_NAME, PERMISSION_UPDATE);
+ identity.checkPermission(ROLE_PERMISSION_NAME, PERMISSION_UPDATE);
return roleIdentityStore.addRoleToGroup(role, group);
}
public boolean removeRoleFromGroup(String role, String group)
{
- Identity.instance().checkPermission(ROLE_PERMISSION_NAME, PERMISSION_UPDATE);
+ identity.checkPermission(ROLE_PERMISSION_NAME, PERMISSION_UPDATE);
return roleIdentityStore.removeRoleFromGroup(role, group);
}
public boolean userExists(String name)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_READ);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_READ);
return identityStore.userExists(name);
}
@@ -179,7 +160,7 @@
public List<String> listUsers()
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_READ);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_READ);
List<String> users = identityStore.listUsers();
Collections.sort(users, new Comparator<String>() {
@@ -193,7 +174,7 @@
public List<String> listUsers(String filter)
{
- Identity.instance().checkPermission(USER_PERMISSION_NAME, PERMISSION_READ);
+ identity.checkPermission(USER_PERMISSION_NAME, PERMISSION_READ);
List<String> users = identityStore.listUsers(filter);
Collections.sort(users, new Comparator<String>() {
@@ -207,7 +188,7 @@
public List<String> listRoles()
{
- Identity.instance().checkPermission(ROLE_PERMISSION_NAME, PERMISSION_READ);
+ identity.checkPermission(ROLE_PERMISSION_NAME, PERMISSION_READ);
List<String> roles = roleIdentityStore.listRoles();
Collections.sort(roles, new Comparator<String>() {
@@ -256,7 +237,7 @@
public List<Principal> listMembers(String role)
{
- Identity.instance().checkPermission(ROLE_PERMISSION_NAME, PERMISSION_READ);
+ identity.checkPermission(ROLE_PERMISSION_NAME, PERMISSION_READ);
return roleIdentityStore.listMembers(role);
}
Added: modules/trunk/security/src/main/java/org/jboss/seam/security/util/Strings.java
===================================================================
--- modules/trunk/security/src/main/java/org/jboss/seam/security/util/Strings.java (rev 0)
+++ modules/trunk/security/src/main/java/org/jboss/seam/security/util/Strings.java 2009-04-23 00:37:40 UTC (rev 10599)
@@ -0,0 +1,22 @@
+package org.jboss.seam.security.util;
+
+public class Strings
+{
+ public static boolean isEmpty(String string)
+ {
+ int len;
+ if (string == null || (len = string.length()) == 0)
+ {
+ return true;
+ }
+
+ for (int i = 0; i < len; i++)
+ {
+ if ((Character.isWhitespace(string.charAt(i)) == false))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+}
17 years
Seam SVN: r10598 - examples/trunk.
by seam-commits@lists.jboss.org
Author: dan.j.allen
Date: 2009-04-22 18:55:46 -0400 (Wed, 22 Apr 2009)
New Revision: 10598
Modified:
examples/trunk/pom.xml
Log:
add servlet-booking
Modified: examples/trunk/pom.xml
===================================================================
--- examples/trunk/pom.xml 2009-04-22 22:55:22 UTC (rev 10597)
+++ examples/trunk/pom.xml 2009-04-22 22:55:46 UTC (rev 10598)
@@ -75,6 +75,7 @@
<modules>
<module>booking</module>
+ <module>servlet-booking</module>
</modules>
<build>
17 years
Seam SVN: r10597 - in examples/trunk: servlet-booking and 14 other directories.
by seam-commits@lists.jboss.org
Author: dan.j.allen
Date: 2009-04-22 18:55:22 -0400 (Wed, 22 Apr 2009)
New Revision: 10597
Added:
examples/trunk/servlet-booking/
examples/trunk/servlet-booking/pom.xml
examples/trunk/servlet-booking/src/
examples/trunk/servlet-booking/src/main/
examples/trunk/servlet-booking/src/main/java/
examples/trunk/servlet-booking/src/main/java/org/
examples/trunk/servlet-booking/src/main/java/org/jboss/
examples/trunk/servlet-booking/src/main/java/org/jboss/seam/
examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/
examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/
examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/BeanLookup.java
examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/HelloWorld.java
examples/trunk/servlet-booking/src/main/java/org/jboss/webbeans/
examples/trunk/servlet-booking/src/main/java/org/jboss/webbeans/resources/
examples/trunk/servlet-booking/src/main/java/org/jboss/webbeans/resources/ManagerReferenceFactory.java
examples/trunk/servlet-booking/src/main/resources/
examples/trunk/servlet-booking/src/main/webapp/
examples/trunk/servlet-booking/src/main/webapp/META-INF/
examples/trunk/servlet-booking/src/main/webapp/META-INF/context.xml
examples/trunk/servlet-booking/src/main/webapp/WEB-INF/
examples/trunk/servlet-booking/src/main/webapp/WEB-INF/beans.xml
examples/trunk/servlet-booking/src/main/webapp/WEB-INF/faces-config.xml
examples/trunk/servlet-booking/src/main/webapp/WEB-INF/jetty-env.xml
examples/trunk/servlet-booking/src/main/webapp/WEB-INF/layout/
examples/trunk/servlet-booking/src/main/webapp/WEB-INF/layout/template.xhtml
examples/trunk/servlet-booking/src/main/webapp/WEB-INF/web.xml
examples/trunk/servlet-booking/src/main/webapp/home.xhtml
examples/trunk/servlet-booking/src/main/webapp/index.html
Log:
Skeleton of the booking example for servlet containers. Works for both Tomcat and Jetty.
Property changes on: examples/trunk/servlet-booking
___________________________________________________________________
Name: svn:ignore
+ target
Added: examples/trunk/servlet-booking/pom.xml
===================================================================
--- examples/trunk/servlet-booking/pom.xml (rev 0)
+++ examples/trunk/servlet-booking/pom.xml 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,97 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.jboss.seam.examples</groupId>
+ <artifactId>parent</artifactId>
+ <version>3.0.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>seam-servlet-booking</artifactId>
+ <packaging>war</packaging>
+ <name>Seam Booking Example (Servlet Container)</name>
+
+ <build>
+ <defaultGoal>package</defaultGoal>
+ <finalName>${project.artifactId}</finalName>
+ <plugins>
+
+ <plugin>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>maven-jetty-plugin</artifactId>
+ <version>6.1.16</version>
+ <configuration>
+ <connectors>
+ <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
+ <port>${jetty.run.port}</port>
+ <maxIdleTime>3600000</maxIdleTime>
+ </connector>
+ </connectors>
+ <scanIntervalSeconds>10</scanIntervalSeconds>
+ <webAppConfig>
+ <contextPath>/${project.build.finalName}</contextPath>
+ </webAppConfig>
+ </configuration>
+ <dependencies/>
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <properties>
+ <jetty.run.port>9090</jetty.run.port>
+ <jetty.debug.port>9190</jetty.debug.port>
+ </properties>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ <scope>test</scope>
+ <classifier>jdk15</classifier>
+ </dependency>
+
+ <!-- disable after upgrading to JSF 2 -->
+ <dependency>
+ <groupId>com.sun.facelets</groupId>
+ <artifactId>jsf-facelets</artifactId>
+ <scope>runtime</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.annotation</groupId>
+ <artifactId>jsr250-api</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.faces</groupId>
+ <artifactId>jsf-api</artifactId>
+ <version>1.2_12</version>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.faces</groupId>
+ <artifactId>jsf-impl</artifactId>
+ <scope>runtime</scope>
+ <version>1.2_12</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.webbeans</groupId>
+ <artifactId>jsr299-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.webbeans.servlet</groupId>
+ <artifactId>webbeans-servlet</artifactId>
+ <scope>compile</scope> <!-- change to runtime after removing ManagerReference -->
+ </dependency>
+
+ </dependencies>
+
+</project>
Added: examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/BeanLookup.java
===================================================================
--- examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/BeanLookup.java (rev 0)
+++ examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/BeanLookup.java 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,27 @@
+package org.jboss.seam.examples.booking;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+//import javax.faces.ManagedBean;
+//import javax.faces.RequestScoped;
+import javax.inject.manager.Manager;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+//@ManagedBean
+//@RequestScoped
+public class BeanLookup {
+ public void lookupManager() {
+ try {
+ InitialContext ic = new InitialContext();
+ Manager manager = (Manager) ic.lookup("java:comp/env/jcdi/Manager");
+ if (manager != null) {
+ Logger logger = Logger.getLogger(BeanLookup.class.getName());
+ logger.log(Level.INFO, "JCDI manager: " + manager.toString());
+ logger.log(Level.INFO, "helloWorld bean: " + String.valueOf(manager.getInstanceByName("helloWorld")));
+ }
+ } catch (NamingException ex) {
+ Logger.getLogger(BeanLookup.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ }
+}
Added: examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/HelloWorld.java
===================================================================
--- examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/HelloWorld.java (rev 0)
+++ examples/trunk/servlet-booking/src/main/java/org/jboss/seam/examples/booking/HelloWorld.java 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,18 @@
+package org.jboss.seam.examples.booking;
+
+import javax.annotation.Named;
+import javax.inject.Current;
+import javax.inject.manager.Manager;
+import javax.context.RequestScoped;
+
+@Named
+@RequestScoped
+public class HelloWorld {
+
+ private @Current Manager manager;
+
+ public void sayHello() {
+ System.out.println("Hello! Here is the manager that I found: " + manager);
+ }
+
+}
Added: examples/trunk/servlet-booking/src/main/java/org/jboss/webbeans/resources/ManagerReferenceFactory.java
===================================================================
--- examples/trunk/servlet-booking/src/main/java/org/jboss/webbeans/resources/ManagerReferenceFactory.java (rev 0)
+++ examples/trunk/servlet-booking/src/main/java/org/jboss/webbeans/resources/ManagerReferenceFactory.java 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,37 @@
+package org.jboss.webbeans.resources;
+
+import java.util.Hashtable;
+import javax.inject.manager.Manager;
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.Reference;
+import javax.naming.spi.ObjectFactory;
+import org.jboss.webbeans.CurrentManager;
+
+/**
+ * A JNDI object factory which will return the current {@link javax.inject.manager.Manager}
+ * when the JNDI name under which this factory is registered gets resolved.
+ *
+ * @author Dan Allen
+ */
+public class ManagerReferenceFactory extends Reference implements ObjectFactory
+{
+ public ManagerReferenceFactory()
+ {
+ super(Manager.class.getName(), ManagerReferenceFactory.class.getName(), null);
+ }
+
+ /**
+ * Called by the JNDI container when the JNDI name under which this factory is registered gets resolved.
+ *
+ * @param ref the Reference
+ * @param name not used
+ * @param ctx not used
+ * @param env not used
+ *
+ * @return The current JCDI root manager instance
+ */
+ public Object getObjectInstance(Object ref, Name name, Context ctx, Hashtable<?, ?> env) throws Exception {
+ return CurrentManager.rootManager().getCurrent();
+ }
+}
Added: examples/trunk/servlet-booking/src/main/webapp/META-INF/context.xml
===================================================================
--- examples/trunk/servlet-booking/src/main/webapp/META-INF/context.xml (rev 0)
+++ examples/trunk/servlet-booking/src/main/webapp/META-INF/context.xml 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Context>
+ <Resource name="jcdi/Manager"
+ auth="Container"
+ type="javax.inject.manager.Manager"
+ factory="org.jboss.webbeans.resources.ManagerReferenceFactory"/>
+</Context>
Added: examples/trunk/servlet-booking/src/main/webapp/WEB-INF/beans.xml
===================================================================
Added: examples/trunk/servlet-booking/src/main/webapp/WEB-INF/faces-config.xml
===================================================================
--- examples/trunk/servlet-booking/src/main/webapp/WEB-INF/faces-config.xml (rev 0)
+++ examples/trunk/servlet-booking/src/main/webapp/WEB-INF/faces-config.xml 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
+ version="2.0">
+
+ <application>
+ <!-- disable after upgrading to JSF 2 -->
+ <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
+ </application>
+
+ <managed-bean>
+ <managed-bean-name>beanLookup</managed-bean-name>
+ <managed-bean-class>org.jboss.seam.examples.booking.BeanLookup</managed-bean-class>
+ <managed-bean-scope>request</managed-bean-scope>
+ </managed-bean>
+
+</faces-config>
Added: examples/trunk/servlet-booking/src/main/webapp/WEB-INF/jetty-env.xml
===================================================================
--- examples/trunk/servlet-booking/src/main/webapp/WEB-INF/jetty-env.xml (rev 0)
+++ examples/trunk/servlet-booking/src/main/webapp/WEB-INF/jetty-env.xml 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN"
+ "http://jetty.mortbay.org/configure.dtd">
+<Configure id="webAppCtx" class="org.mortbay.jetty.webapp.WebAppContext">
+ <New id="jdci" class="org.mortbay.jetty.plus.naming.Resource">
+ <Arg><Ref id="webAppCtx"/></Arg>
+ <Arg>jcdi/Manager</Arg>
+ <Arg>
+ <New class="org.jboss.webbeans.resources.ManagerReferenceFactory"/>
+ </Arg>
+ </New>
+</Configure>
Added: examples/trunk/servlet-booking/src/main/webapp/WEB-INF/layout/template.xhtml
===================================================================
--- examples/trunk/servlet-booking/src/main/webapp/WEB-INF/layout/template.xhtml (rev 0)
+++ examples/trunk/servlet-booking/src/main/webapp/WEB-INF/layout/template.xhtml 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,17 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<f:view xmlns="http://www.w3.org/1999/xhtml"
+ xmlns:ui="http://java.sun.com/jsf/facelets"
+ xmlns:h="http://java.sun.com/jsf/html"
+ xmlns:f="http://java.sun.com/jsf/core"
+ contentType="text/html">
+<html>
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
+ <title>Hello World</title>
+ </head>
+ <body>
+ <ui:insert name="content"/>
+ </body>
+</html>
+</f:view>
Added: examples/trunk/servlet-booking/src/main/webapp/WEB-INF/web.xml
===================================================================
--- examples/trunk/servlet-booking/src/main/webapp/WEB-INF/web.xml (rev 0)
+++ examples/trunk/servlet-booking/src/main/webapp/WEB-INF/web.xml 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<web-app xmlns="http://java.sun.com/xml/ns/javaee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
+ version="2.5">
+
+ <display-name>Seam Booking Example (Servlet Container)</display-name>
+
+ <!-- disable after upgrading to JSF 2 -->
+ <context-param>
+ <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
+ <param-value>.xhtml</param-value>
+ </context-param>
+
+ <context-param>
+ <param-name>facelets.DEVELOPMENT</param-name>
+ <param-value>true</param-value>
+ </context-param>
+
+ <listener>
+ <listener-class>org.jboss.webbeans.environment.servlet.Listener</listener-class>
+ </listener>
+
+ <servlet>
+ <servlet-name>Faces Servlet</servlet-name>
+ <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
+ <load-on-startup>1</load-on-startup>
+ </servlet>
+
+ <servlet-mapping>
+ <servlet-name>Faces Servlet</servlet-name>
+ <url-pattern>*.seam</url-pattern>
+ </servlet-mapping>
+
+ <session-config>
+ <session-timeout>10</session-timeout>
+ </session-config>
+
+ <resource-env-ref>
+ <description>Object factory for the JCDI Manager</description>
+ <resource-env-ref-name>jcdi/Manager</resource-env-ref-name>
+ <resource-env-ref-type>javax.inject.manager.Manager</resource-env-ref-type>
+ </resource-env-ref>
+
+</web-app>
Added: examples/trunk/servlet-booking/src/main/webapp/home.xhtml
===================================================================
--- examples/trunk/servlet-booking/src/main/webapp/home.xhtml (rev 0)
+++ examples/trunk/servlet-booking/src/main/webapp/home.xhtml 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1,19 @@
+<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<ui:composition xmlns="http://www.w3.org/1999/xhtml"
+ xmlns:ui="http://java.sun.com/jsf/facelets"
+ xmlns:f="http://java.sun.com/jsf/core"
+ xmlns:h="http://java.sun.com/jsf/html"
+ template="/WEB-INF/layout/template.xhtml">
+
+ <ui:define name="content">
+
+ <h1>Seam 3</h1>
+
+ <h:form>
+ <h:commandButton action="#{beanLookup.lookupManager}" value="Lookup Manager"/>
+ </h:form>
+
+ </ui:define>
+
+</ui:composition>
Added: examples/trunk/servlet-booking/src/main/webapp/index.html
===================================================================
--- examples/trunk/servlet-booking/src/main/webapp/index.html (rev 0)
+++ examples/trunk/servlet-booking/src/main/webapp/index.html 2009-04-22 22:55:22 UTC (rev 10597)
@@ -0,0 +1 @@
+<html><head><meta http-equiv="Refresh" content="0; URL=home.seam"/></head></html>
17 years
Seam SVN: r10596 - examples/trunk/booking/seam-booking-ear.
by seam-commits@lists.jboss.org
Author: dan.j.allen
Date: 2009-04-22 18:54:51 -0400 (Wed, 22 Apr 2009)
New Revision: 10596
Modified:
examples/trunk/booking/seam-booking-ear/pom.xml
Log:
note
Modified: examples/trunk/booking/seam-booking-ear/pom.xml
===================================================================
--- examples/trunk/booking/seam-booking-ear/pom.xml 2009-04-22 22:51:33 UTC (rev 10595)
+++ examples/trunk/booking/seam-booking-ear/pom.xml 2009-04-22 22:54:51 UTC (rev 10596)
@@ -26,7 +26,7 @@
<defaultJavaBundleDir>lib</defaultJavaBundleDir>
<jboss>
<version>4.2</version>
- <!-- If you use loader-repository, it will break Web Beans -->
+ <!-- loader-repository gets added automatically by Web Beans -->
<!--<loader-repository>${project.groupId}:loader=${project.build.finalName}</loader-repository>-->
<data-sources>
<data-source>${project.parent.artifactId}-ds.xml</data-source>
17 years