<version>2.0.0</version>
<scope>compile</scope>
</dependency>
-
-
-
+
</dependencies>
</dependencyManagement>
<goals>javadoc:jar deploy</goals>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>2.5</version>
+ <dependencies>
+ <dependency>
+ <groupId>org.wamblee</groupId>
+ <artifactId>wamblee-code-style</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4</version>
<fileFormat>UNIX</fileFormat>
<convention>org.wamblee.jalopy.xml</convention>
</configuration>
+ <dependencies>
+ <dependency>
+ <groupId>org.wamblee</groupId>
+ <artifactId>wamblee-code-style</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ </dependency>
+ </dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
+ <version>2.5</version>
<configuration>
- <configLocation>config/sun_checks.xml</configLocation>
+ <configLocation>org.wamblee.checkstyle.xml</configLocation>
</configuration>
</plugin>
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
/**
- * An superclass of all other operations.
+ * An superclass of all other operations.
*/
public class AllOperation implements Operation {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final String OPERATION = "all";
-
+
/**
- * Operation name.
+ * Operation name.
*/
private String name;
-
- /**
+
+/**
* Constructs an all operation.
*
*/
- public AllOperation() {
- name = OPERATION;
+ public AllOperation() {
+ name = OPERATION;
}
-
- /**
+
+/**
* Constructs the operation, this constructor is the one that must be used
* by subclasses.
* @param aName Name of the operation. This name must be unique among all operations.
*/
- protected AllOperation(String aName) {
- name = aName;
+ protected AllOperation(String aName) {
+ name = aName;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.Operation#getName()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public String getName() {
- return name;
+ return name;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.wamblee.persistence.AbstractPersistent;
+
import org.wamblee.usermgt.User;
+
/**
- * Matches any user.
+ * Matches any user.
*
* @author Erik Brakkee
*/
-public class AnyUserCondition extends AbstractPersistent implements UserCondition {
-
- /**
+public class AnyUserCondition extends AbstractPersistent
+ implements UserCondition {
+/**
* Constructs the condition.
*
*/
- public AnyUserCondition() {
+ public AnyUserCondition() {
// Empty.
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean matches(User aUser) {
- return true;
+ return true;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
- return "AnyUserCondition()";
+ return "AnyUserCondition()";
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
/**
- * Authorization exception to be thrown when
- * a resouce may not be accessed.
+ * Authorization exception to be thrown when a resouce may not be accessed.
*
* @author Erik Brakkee
*/
public class AuthorizationException extends RuntimeException {
-
- private Object resource;
- private Operation operation;
+ /**
+ * DOCUMENT ME!
+ */
+ private Object resource;
+ /**
+ * DOCUMENT ME!
+ */
+ private Operation operation;
+
+/**
+ * Creates a new AuthorizationException object.
+ *
+ * @param aResource DOCUMENT ME!
+ * @param aOperation DOCUMENT ME!
+ */
public AuthorizationException(Object aResource, Operation aOperation) {
- super("Operation '" + aOperation + "' not allowed on '" + aResource + "'");
- resource = aResource;
- operation = aOperation;
+ super("Operation '" + aOperation + "' not allowed on '" + aResource
+ + "'");
+ resource = aResource;
+ operation = aOperation;
}
-
- public Object getResource() {
- return resource;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Object getResource() {
+ return resource;
}
-
- public Operation getOperation() {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Operation getOperation() {
return operation;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.apache.log4j.Logger;
/**
- * Inititializer class for authorization rules. This class initializes the
- * authorization rules in case none are present.
+ * Inititializer class for authorization rules. This class initializes the
+ * authorization rules in case none are present.
*/
public class AuthorizationInitializer {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final Logger LOGGER = Logger.getLogger(AuthorizationInitializer.class);
- /**
+/**
* Initializes authorization rules in case none are present.
* @param aService Authorization service.
* @param aRules Default rules for initialization.
*/
- public AuthorizationInitializer(AuthorizationService aService, AuthorizationRule[] aRules) {
- if ( aService.getRules().length == 0 ) {
- for (AuthorizationRule rule: aRules) {
- LOGGER.info("Appending authorization rule " + rule);
- aService.appendRule(rule);
- }
- }
+ public AuthorizationInitializer(AuthorizationService aService,
+ AuthorizationRule[] aRules) {
+ if (aService.getRules().length == 0) {
+ for (AuthorizationRule rule : aRules) {
+ LOGGER.info("Appending authorization rule " + rule);
+ aService.appendRule(rule);
+ }
+ }
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.security.authorization;
/**
* @author Erik Brakkee
*/
public enum AuthorizationResult {
- /**
+/**
* Access is granted.
*/
GRANTED,
-
- /**
+/**
* Access is denied.
*/
DENIED,
-
- /**
+/**
* Access is undecided.
*/
UNDECIDED,
-
- /**
+/**
* Unsupported resource.
*/
- UNSUPPORTED_RESOURCE
+ UNSUPPORTED_RESOURCE;
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.wamblee.persistence.Persistent;
+
import org.wamblee.usermgt.User;
+
/**
* Represents an authorization rule to determine whether an operation is allowed on a resource.
*
* @author Erik Brakkee
*/
public interface AuthorizationRule extends Persistent {
-
/**
- * Returns the supported object types for which this authorization rule applies.
- * This can be used by the authorization service for optimization.
- * @return Array of supported types.
+ * Returns the supported object types for which this authorization
+ * rule applies. This can be used by the authorization service for
+ * optimization.
+ *
+ * @return Array of supported types.
*/
Class[] getSupportedTypes();
/**
- * Determines whether an operation is allowed on a certain resource.
- * The rule implementation must be prepared to deal with resources for which it does
- * not apply. In those cases it should return {@link AuthorizationResult#UNSUPPORTED_RESOURCE}.
- * @param aResource Resource.
- * @param anOperation Operation.
- * @param aUser Current user.
- * @return Authorization result.
+ * Determines whether an operation is allowed on a certain
+ * resource. The rule implementation must be prepared to deal with
+ * resources for which it does not apply. In those cases it should return
+ * {@link AuthorizationResult#UNSUPPORTED_RESOURCE}.
+ *
+ * @param aResource Resource.
+ * @param anOperation Operation.
+ * @param aUser Current user.
+ *
+ * @return Authorization result.
*/
- AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser);
+ AuthorizationResult isAllowed(Object aResource, Operation anOperation,
+ User aUser);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.wamblee.persistence.Persistent;
+
/**
* Service to determine if access to a certain resource is allowed.
*
* @author Erik Brakkee
*/
public interface AuthorizationService extends Persistent {
-
/**
- * Checks whether an operation is allowed on a resource.
- * @param aResource Resource.
- * @param aOperation Operation.
- * @return Checks whether the operation is allowed on a resource.
+ * Checks whether an operation is allowed on a resource.
+ *
+ * @param aResource Resource.
+ * @param aOperation Operation.
+ *
+ * @return Checks whether the operation is allowed on a resource.
*/
boolean isAllowed(Object aResource, Operation aOperation);
-
+
/**
- * Same as {@link #isAllowed(Object, Operation)} but throws a
- * <code>RuntimeException</code> in case access is not allowed.
- * @param aResource Resource to check.
- * @param aOperation Operation to perform.
- * @return Resource that was checked.
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aResource DOCUMENT ME!
+ * @param aOperation DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
*/
- <T> T check(T aResource, Operation aOperation);
-
+ <T> T check(T aResource, Operation aOperation);
+
/**
- * Gets the authorization rules.
- * @return Rules.
+ * Gets the authorization rules.
+ *
+ * @return Rules.
*/
- AuthorizationRule[] getRules();
-
+ AuthorizationRule[] getRules();
+
/**
- * Appends a new authorization rule to the end.
- * @param aRule Rule to append.
+ * Appends a new authorization rule to the end.
+ *
+ * @param aRule Rule to append.
*/
- void appendRule(AuthorizationRule aRule);
-
+ void appendRule(AuthorizationRule aRule);
+
/**
- * Removes a rule.
- * @param aRule Index of the rule to remove.
+ * Removes a rule.
+ *
+ * @param aIndex Index of the rule to remove.
*/
- void removeRule(int aIndex);
-
+ void removeRule(int aIndex);
+
/**
- * Inserts a rule.
- * @param aIndex Index of the position of the rule after insertion.
- * @param aRule Rule to insert.
+ * Inserts a rule.
+ *
+ * @param aIndex Index of the position of the rule after insertion.
+ * @param aRule Rule to insert.
*/
void insertRuleAfter(int aIndex, AuthorizationRule aRule);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
/**
- * Represents an operation to create something.
+ * Represents an operation to create something.
*
* @author Erik Brakkee
*/
public class CreateOperation extends AllOperation {
-
- private static final String OPERATION = "create";
-
/**
+ * DOCUMENT ME!
+ */
+ private static final String OPERATION = "create";
+
+/**
* Constructs the operation.
*
*/
- public CreateOperation() {
+ public CreateOperation() {
super(OPERATION);
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
-import java.util.ArrayList;
-import java.util.List;
-
import org.wamblee.persistence.AbstractPersistent;
+
import org.wamblee.usermgt.User;
import org.wamblee.usermgt.UserAccessor;
+import java.util.ArrayList;
+import java.util.List;
+
+
/**
- * Default implementation of an authorization service.
- * To determine whether access to a resource is allowed, the service consults a number
- * of authorization rules in a fixed order. The first rule that gives a result GRANTED or
- * DENIED determines the result of the evaluation. Rules that return any other result are
- * ignoed. If none of the rules match, than access is denied.
+ * Default implementation of an authorization service. To determine
+ * whether access to a resource is allowed, the service consults a number of
+ * authorization rules in a fixed order. The first rule that gives a result
+ * GRANTED or DENIED determines the result of the evaluation. Rules that
+ * return any other result are ignoed. If none of the rules match, than
+ * access is denied.
*
* @author Erik Brakkee
*/
-public class DefaultAuthorizationService extends AbstractPersistent implements AuthorizationService {
-
+public class DefaultAuthorizationService extends AbstractPersistent
+ implements AuthorizationService {
/**
- * List of ordered authorization rules.
+ * List of ordered authorization rules.
*/
- private List<AuthorizationRule> rules;
-
+ private List<AuthorizationRule> rules;
+
/**
- * User accessor used to obtain the current user.
+ * User accessor used to obtain the current user.
*/
- private UserAccessor userAccessor;
-
+ private UserAccessor userAccessor;
+
/**
- * Name for this instance of the authorization service.
+ * Name for this instance of the authorization service.
*/
private String name;
-
- /**
+
+/**
* Constructs the service.
* @param aAccessor User accessor.
* @param aName Name of this instance of the service.
*/
public DefaultAuthorizationService(UserAccessor aAccessor, String aName) {
- rules = new ArrayList<AuthorizationRule>();
- userAccessor = aAccessor;
- name = aName;
+ rules = new ArrayList<AuthorizationRule>();
+ userAccessor = aAccessor;
+ name = aName;
}
-
- /**
+
+/**
* Constructs the authorization service.
*/
public DefaultAuthorizationService() {
- rules = new ArrayList<AuthorizationRule>();
- userAccessor = null;
- name = null;
+ rules = new ArrayList<AuthorizationRule>();
+ userAccessor = null;
+ name = null;
}
-
+
/**
- * Sets the user accessor.
- * @param aUserAccessor User accessor.
+ * Sets the user accessor.
+ *
+ * @param aUserAccessor User accessor.
*/
- public void setUserAccessor(UserAccessor aUserAccessor) {
- userAccessor = aUserAccessor;
+ public void setUserAccessor(UserAccessor aUserAccessor) {
+ userAccessor = aUserAccessor;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResource DOCUMENT ME!
+ * @param aOperation DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean isAllowed(Object aResource, Operation aOperation) {
- User user = userAccessor.getCurrentUser();
- for (AuthorizationRule rule: rules) {
- switch ( rule.isAllowed(aResource, aOperation, user)) {
- case DENIED: { return false; }
- case GRANTED: { return true; }
+ User user = userAccessor.getCurrentUser();
+
+ for (AuthorizationRule rule : rules) {
+ switch (rule.isAllowed(aResource, aOperation, user)) {
+ case DENIED:
+ return false;
+
+ case GRANTED:
+ return true;
}
}
- return false;
+
+ return false;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aResource DOCUMENT ME!
+ * @param aOperation DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws AuthorizationException DOCUMENT ME!
+ */
public <T> T check(T aResource, Operation aOperation) {
- if ( !isAllowed(aResource, aOperation)) {
+ if (!isAllowed(aResource, aOperation)) {
throw new AuthorizationException(aResource, aOperation);
}
+
return aResource;
}
-
- protected String getName() {
- return name;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected String getName() {
+ return name;
}
-
- public void setName(String aName) {
- name = aName;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ */
+ public void setName(String aName) {
+ name = aName;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#getRules()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public AuthorizationRule[] getRules() {
- return rules.toArray(new AuthorizationRule[0]);
+ return rules.toArray(new AuthorizationRule[0]);
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRule DOCUMENT ME!
+ */
public void appendRule(AuthorizationRule aRule) {
- rules.add(aRule);
+ rules.add(aRule);
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int, org.wamblee.security.authorization.AuthorizationRule)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aIndex DOCUMENT ME!
+ * @param aRule DOCUMENT ME!
+ */
public void insertRuleAfter(int aIndex, AuthorizationRule aRule) {
- rules.add(aIndex, aRule);
+ rules.add(aIndex, aRule);
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#removeRule(int)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aIndex DOCUMENT ME!
+ */
public void removeRule(int aIndex) {
- rules.remove(aIndex);
+ rules.remove(aIndex);
}
-
+
/**
- * For OR mapping.
- * @return The rules.
+ * For OR mapping.
+ *
+ * @return The rules.
*/
protected List<AuthorizationRule> getMappedRules() {
- return rules;
+ return rules;
}
-
+
/**
* For OR mapping.
- * @param aRules The rules.
+ *
+ * @param aRules The rules.
*/
- protected void setMappedRules(List<AuthorizationRule> aRules) {
- rules = aRules;
+ protected void setMappedRules(List<AuthorizationRule> aRules) {
+ rules = aRules;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
+
/**
- * Operation registry implementation.
- * This implementation ignores the distinction between different types of resources
- * and simply assumes that every operation is applicable to every type of resource.
+ * Operation registry implementation. This implementation ignores the
+ * distinction between different types of resources and simply assumes that
+ * every operation is applicable to every type of resource.
*
* @author Erik Brakkee
*/
public class DefaultOperationRegistry implements OperationRegistry {
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<String, Operation> operations;
- private Map<String,Operation> operations;
-
- public DefaultOperationRegistry(Operation[] aOperations) {
+/**
+ * Creates a new DefaultOperationRegistry object.
+ *
+ * @param aOperations DOCUMENT ME!
+ */
+ public DefaultOperationRegistry(Operation[] aOperations) {
operations = new TreeMap<String, Operation>();
- for (Operation operation: aOperations) {
+
+ for (Operation operation : aOperations) {
operations.put(operation.getName(), operation);
}
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.OperationRegistry#getOperations(java.lang.Class)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResourceClass DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Operation[] getOperations(Class aResourceClass) {
- return operations.values().toArray(new Operation[0]);
+ return operations.values().toArray(new Operation[0]);
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.OperationRegistry#encode(org.wamblee.security.authorization.Operation[])
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aOperations DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public String encode(Operation[] aOperations) {
- StringBuffer buffer = new StringBuffer();
- for (Operation operation: aOperations) {
- if ( buffer.length() > 0 ) {
+ StringBuffer buffer = new StringBuffer();
+
+ for (Operation operation : aOperations) {
+ if (buffer.length() > 0) {
buffer.append(',');
}
+
buffer.append(operation.getName());
}
+
return buffer.toString();
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.Class, java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResourceClass DOCUMENT ME!
+ * @param aOperationsString DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Operation[] decode(Class aResourceClass, String aOperationsString) {
- return decode(aOperationsString);
+ return decode(aOperationsString);
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aOperationsString DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
+ */
public Operation[] decode(String aOperationsString) {
- if ( aOperationsString.length() == 0 ) {
- return new Operation[0];
+ if (aOperationsString.length() == 0) {
+ return new Operation[0];
}
- String[] names = aOperationsString.split(",");
- ArrayList<Operation> result = new ArrayList<Operation>();
- for (String name: names) {
+
+ String[] names = aOperationsString.split(",");
+ ArrayList<Operation> result = new ArrayList<Operation>();
+
+ for (String name : names) {
Operation operation = operations.get(name);
- if ( operation == null ) {
- throw new IllegalArgumentException("Unknown operation '" + name + "'");
+
+ if (operation == null) {
+ throw new IllegalArgumentException("Unknown operation '" + name
+ + "'");
}
+
result.add(operation);
}
- return result.toArray(new Operation[0]);
- }
+ return result.toArray(new Operation[0]);
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
/**
- * Deletes the operation.
+ * Deletes the operation.
*
* @author Erik Brakkee
*/
public class DeleteOperation extends AllOperation {
-
- private static final String OPERATION = "delete";
-
/**
+ * DOCUMENT ME!
+ */
+ private static final String OPERATION = "delete";
+
+/**
* Constructs the operation.
*
*/
- public DeleteOperation() {
+ public DeleteOperation() {
super(OPERATION);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.wamblee.persistence.AbstractPersistent;
+
import org.wamblee.usermgt.User;
+
/**
- * Checks if a user against a specific group.
+ * Checks if a user against a specific group.
*
* @author Erik Brakkee
*/
-public class GroupUserCondition extends AbstractPersistent implements UserCondition {
-
+public class GroupUserCondition extends AbstractPersistent
+ implements UserCondition {
/**
- * Group the user must be in.
+ * Group the user must be in.
*/
- private String group;
-
- /**
+ private String group;
+
+/**
* Constructs the condition.
* @param aGroup Group the user must be in.
*/
public GroupUserCondition(String aGroup) {
- group = aGroup;
+ group = aGroup;
}
-
- /**
+
+/**
* For OR mapping.
*
*/
- protected GroupUserCondition() {
- group = null;
+ protected GroupUserCondition() {
+ group = null;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.UserAccessor)
*/
- public boolean matches(User aUser) {
- return aUser.isInGroup(group);
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public boolean matches(User aUser) {
+ return aUser.isInGroup(group);
}
/**
+ * DOCUMENT ME!
+ *
* @return Returns the group.
*/
protected String getGroup() {
}
/**
- * @param group The group to set.
+ * DOCUMENT ME!
+ *
+ * @param aGroup The group to set.
*/
protected void setGroup(String aGroup) {
group = aGroup;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
return "GroupUserCondition(group=" + group + ")";
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.security.authorization;
import org.wamblee.persistence.AbstractPersistent;
+
/**
* Determiens if an operation is a subclass of a specified operation.
*/
-public class IsaOperationCondition extends AbstractPersistent implements
- OperationCondition {
-
+public class IsaOperationCondition extends AbstractPersistent
+ implements OperationCondition {
/**
* Operation that the other operation must be a subclass of.
*/
- private Class<? extends Operation> operation;
+ private Class<?extends Operation> operation;
- /**
+/**
* Constructs the condition.
*
* @param aOperation
* Operation that an operation must be an instance of.
*/
- public IsaOperationCondition(Class<? extends Operation> aOperation) {
+ public IsaOperationCondition(Class<?extends Operation> aOperation) {
operation = aOperation;
}
- /**
+/**
* For OR mapping.
*
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.OperationCondition#matches(org.wamblee.security.authorization.Operation)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aOperation DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean matches(Operation aOperation) {
return operation.isInstance(aOperation);
}
/**
* Gets the operation as a string. For OR mapping only.
- *
+ *
* @return Operation string.
*/
protected String getOperationString() {
if (operation == null) {
- return null;
+ return null;
}
- return operation.getName();
+
+ return operation.getName();
}
/**
* Sets the operation as a string. For OR mapping only.
- *
- * @param aOperation
- * Operation string.
+ *
+ * @param aOperation Operation string.
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
*/
protected void setOperationString(String aOperation) {
- if (aOperation == null ) {
+ if (aOperation == null) {
return;
}
- try {
- operation = (Class<? extends Operation>)Class.forName(aOperation);
- } catch (Exception e) {
- throw new IllegalArgumentException("Unknown class '" + aOperation + "'");
+
+ try {
+ operation = (Class<?extends Operation>) Class.forName(aOperation);
+ } catch (Exception e) {
+ throw new IllegalArgumentException("Unknown class '" + aOperation
+ + "'");
}
}
/*
* (non-Javadoc)
- *
+ *
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
return "IsaOperationCondition(operation=" + operation.getName() + ")";
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
/**
* @author Erik Brakkee
*/
public interface Operation {
-
/**
- * Gets the name of the operation.
- * @return Operation.
+ * Gets the name of the operation.
+ *
+ * @return Operation.
*/
- String getName();
+ String getName();
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.wamblee.persistence.Persistent;
+
/**
* Checks if an operation matches a condition.
*
* @author Erik Brakkee
*/
public interface OperationCondition extends Persistent {
-
-
/**
- * Determines if the operation matches.
- * @param aOperation Operation.
- * @return True iff the operation matches.
+ * Determines if the operation matches.
+ *
+ * @param aOperation Operation.
+ *
+ * @return True iff the operation matches.
*/
- boolean matches(Operation aOperation);
+ boolean matches(Operation aOperation);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
-
/**
* Utility to map between a list of operations and a string based
* on the names of the operations.
* @author Erik Brakkee
*/
public interface OperationRegistry {
-
/**
- * Gets the supported operations for a given resource class.
- * @param aResourceClass Resource class.
- * @return Supported operations for that class.
+ * Gets the supported operations for a given resource class.
+ *
+ * @param aResourceClass Resource class.
+ *
+ * @return Supported operations for that class.
*/
Operation[] getOperations(Class aResourceClass);
-
+
/**
- * Converts a number of operations to a string.
- * @param aOperations Operations to convert.
- * @return String representation of the allowed operations.
+ * Converts a number of operations to a string.
+ *
+ * @param aOperations Operations to convert.
+ *
+ * @return String representation of the allowed operations.
*/
String encode(Operation[] aOperations);
-
+
/**
* Converts an operations string to an array of operations.
- * @param aResourceClass Resource class.
- * @param aOperationsString Operations string as returned by {@link #encode(Operation[])}.
- * @return Operations array.
+ *
+ * @param aResourceClass Resource class.
+ * @param aOperationsString Operations string as returned by {@link
+ * #encode(Operation[])}.
+ *
+ * @return Operations array.
*/
Operation[] decode(Class aResourceClass, String aOperationsString);
-
+
/**
* Converts an operations string to an array of operations.
- * @param aOperationsString Operations string as returned by {@link #encode(Operation[])}.
- * @return Operations array.
+ *
+ * @param aOperationsString Operations string as returned by {@link
+ * #encode(Operation[])}.
+ *
+ * @return Operations array.
*/
Operation[] decode(String aOperationsString);
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.wamblee.persistence.Persistent;
+
/**
* Checks if a path satisfies a condition.
*
* @author Erik Brakkee
*/
public interface PathCondition extends Persistent {
-
/**
- * Checks if the path matches the condition.
- * @param aPath Path to match.
- * @return True iff the path matches.
+ * Checks if the path matches the condition.
+ *
+ * @param aPath Path to match.
+ *
+ * @return True iff the path matches.
*/
- boolean matches(String aPath);
+ boolean matches(String aPath);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
/**
- * Represents a read operation on a resource.
+ * Represents a read operation on a resource.
*
* @author Erik Brakkee
*/
public class ReadOperation extends AllOperation {
-
- private static final String OPERATION = "read";
-
/**
+ * DOCUMENT ME!
+ */
+ private static final String OPERATION = "read";
+
+/**
* Constructs the operation.
*
*/
- public ReadOperation() {
- super(OPERATION);
+ public ReadOperation() {
+ super(OPERATION);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.wamblee.persistence.AbstractPersistent;
+
/**
* Condition to check whether a path matches a given regula expression.
*
* @author Erik Brakkee
*/
-public class RegexpPathCondition extends AbstractPersistent implements PathCondition {
-
+public class RegexpPathCondition extends AbstractPersistent
+ implements PathCondition {
/**
- * String the path must start with.
+ * String the path must start with.
*/
- private String pattern;
-
- /**
+ private String pattern;
+
+/**
* Constructs the condition.
* @param aPattern String the path must start with.
*/
- public RegexpPathCondition(String aPattern) {
- pattern = aPattern;
+ public RegexpPathCondition(String aPattern) {
+ pattern = aPattern;
}
-
- /**
+
+/**
* For OR mapping.
*
*/
- protected RegexpPathCondition() {
- pattern = null;
+ protected RegexpPathCondition() {
+ pattern = null;
}
/* (non-Javadoc)
* @see org.wamblee.security.authorization.PathCondition#matches(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPath DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean matches(String aPath) {
return aPath.matches(pattern);
}
/**
+ * DOCUMENT ME!
+ *
* @return Returns the _path.
*/
protected String getPattern() {
}
/**
+ * DOCUMENT ME!
+ *
* @param aPattern The _path to set.
*/
protected void setPattern(String aPattern) {
pattern = aPattern;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
return "RegexpCondition(pattern = '" + pattern + "')";
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
-
/**
- * Condition to check whether a path starts with a given string.
+ * Condition to check whether a path starts with a given string.
*
* @author Erik Brakkee
*/
public class StartsWithPathCondition extends RegexpPathCondition {
-
- /**
+/**
* Constructs the condition.
* @param aPath String the path must start with.
*/
- public StartsWithPathCondition(String aPath) {
- super( aPath + ".*");
+ public StartsWithPathCondition(String aPath) {
+ super(aPath + ".*");
}
-
- /**
+
+/**
* For OR mapping.
*
*/
- protected StartsWithPathCondition() {
- super();
+ protected StartsWithPathCondition() {
+ super();
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
return "StartsWithPathCondition(pattern = '" + getPattern() + "')";
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.security.authorization;
+import org.apache.log4j.Logger;
+
+import org.wamblee.persistence.AbstractPersistent;
import static org.wamblee.security.authorization.AuthorizationResult.DENIED;
import static org.wamblee.security.authorization.AuthorizationResult.GRANTED;
import static org.wamblee.security.authorization.AuthorizationResult.UNDECIDED;
import static org.wamblee.security.authorization.AuthorizationResult.UNSUPPORTED_RESOURCE;
-import org.apache.log4j.Logger;
-import org.wamblee.persistence.AbstractPersistent;
import org.wamblee.usermgt.User;
+
/**
- * Utility base class for implementation of authentication rules based on the
- * <ul>
- * <li> The path of the resource. To obtain the path of a resource, subclasses
- * must implement {@link #getResourcePath(Object)}.
- * Whether a path is appropriate is determined by a
- * {@link org.wamblee.security.authorization.PathCondition}.
- * </li>
- * <li> The user identity with which the resource is accessed.
- * Whether a user is appropriate is determined by
- * a {@link org.wamblee.security.authorization.UserCondition}.
- * </li>
- * <li> The operation that is requested.
- * Whether the operation is appropriate is determined by a
- * {@link org.wamblee.security.authorization.OperationCondition}.
- * </li>
- * </ul>
- *
- * In case all three conditions match, the condition returns the configured
- * result passed at construction (GRANTED or DENIED). If the resource is not
- * of the specified type, the result is UNSUPPORTED_RESOURCE, otherwise, the
- * result is UNDECIDED.
+ * Utility base class for implementation of authentication rules based on
+ * the
+ * <ul>
+ * <li>The path of the resource. To obtain the path of a resource,
+ * subclasses must implement {@link #getResourcePath(Object)}. Whether a
+ * path is appropriate is determined by a {@link
+ * org.wamblee.security.authorization.PathCondition}.</li>
+ * <li>The user identity with which the resource is accessed.
+ * Whether a user is appropriate is determined by a {@link
+ * org.wamblee.security.authorization.UserCondition}.</li>
+ * <li>The operation that is requested. Whether the operation is
+ * appropriate is determined by a {@link
+ * org.wamblee.security.authorization.OperationCondition}.</li>
+ * </ul>
+ * In case all three conditions match, the condition returns the
+ * configured result passed at construction (GRANTED or DENIED). If the
+ * resource is not of the specified type, the result is UNSUPPORTED_RESOURCE,
+ * otherwise, the result is UNDECIDED.
*/
-public abstract class UrlAuthorizationRule extends AbstractPersistent implements AuthorizationRule {
-
+public abstract class UrlAuthorizationRule extends AbstractPersistent
+ implements AuthorizationRule {
+ /**
+ * DOCUMENT ME!
+ */
private static final Logger LOGGER = Logger.getLogger(UrlAuthorizationRule.class);
/**
- * Result that the rule will return in case there is a match.
+ * Result that the rule will return in case there is a match.
*/
private AuthorizationResult result;
/**
- * A condition which specifies which users the rule is for.
+ * A condition which specifies which users the rule is for.
*/
- private UserCondition userCondition;
+ private UserCondition userCondition;
/**
- * Path the rule applies for.
+ * Path the rule applies for.
*/
private PathCondition pathCondition;
/**
- * Resource class that the rule applies for.
+ * Resource class that the rule applies for.
*/
private Class resourceClass;
-
+
/**
- * Operation that this rule is for.
+ * Operation that this rule is for.
*/
- private OperationCondition operationCondition;
+ private OperationCondition operationCondition;
- /**
+/**
* Constructs an authorization rule.
* IF the group and path match, then the provided result will be returned.
* @param aResult Result of the authorization when the path and group match.
* @param aResourceClass Supported resource class this is for.
* @param aOperationCondition Condition to match the operation with.
*/
- protected UrlAuthorizationRule(AuthorizationResult aResult, UserCondition aUserCondition,
- PathCondition aPathCondition, Class aResourceClass, OperationCondition aOperationCondition) {
- if ( !aResult.equals(GRANTED) && !aResult.equals(DENIED)) {
- throw new IllegalArgumentException("Only GRANTED or DENIED may be used: " + aResult);
+ protected UrlAuthorizationRule(AuthorizationResult aResult,
+ UserCondition aUserCondition, PathCondition aPathCondition,
+ Class aResourceClass, OperationCondition aOperationCondition) {
+ if (!aResult.equals(GRANTED) && !aResult.equals(DENIED)) {
+ throw new IllegalArgumentException(
+ "Only GRANTED or DENIED may be used: " + aResult);
}
- result = aResult;
- userCondition = aUserCondition;
- pathCondition = aPathCondition;
- resourceClass = aResourceClass;
- operationCondition = aOperationCondition;
+
+ result = aResult;
+ userCondition = aUserCondition;
+ pathCondition = aPathCondition;
+ resourceClass = aResourceClass;
+ operationCondition = aOperationCondition;
}
-
- /**
+
+/**
* For OR mapping.
*
*/
- protected UrlAuthorizationRule(Class aResourceClass) {
- result = null;
- userCondition = null;
- pathCondition = null;
- resourceClass = aResourceClass;
- operationCondition = null;
+ protected UrlAuthorizationRule(Class aResourceClass) {
+ result = null;
+ userCondition = null;
+ pathCondition = null;
+ resourceClass = aResourceClass;
+ operationCondition = null;
}
-
- /**
+
+/**
* For OR mapping.
*
*/
- protected UrlAuthorizationRule() {
- result = null;
- userCondition = null;
- pathCondition = null;
- resourceClass = null;
- operationCondition = null;
+ protected UrlAuthorizationRule() {
+ result = null;
+ userCondition = null;
+ pathCondition = null;
+ resourceClass = null;
+ operationCondition = null;
}
-
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Class[] getSupportedTypes() {
return new Class[] { resourceClass };
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.AuthorizationRule#isAllowed(java.lang.Object,
* org.wamblee.security.authorization.Operation)
*/
- public AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser) {
- if ( ! resourceClass.isInstance(aResource)) {
- return UNSUPPORTED_RESOURCE;
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResource DOCUMENT ME!
+ * @param anOperation DOCUMENT ME!
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public AuthorizationResult isAllowed(Object aResource,
+ Operation anOperation, User aUser) {
+ if (!resourceClass.isInstance(aResource)) {
+ return UNSUPPORTED_RESOURCE;
}
+
String path = getResourcePath(aResource);
- return isAllowed(path, anOperation, aUser);
+
+ return isAllowed(path, anOperation, aUser);
}
-
+
/**
- * Determines if the operation is allowed on the resource.
- * @param aPath Path of the resource.
- * @param aOperation Operation to be done.
- * @param aUser Currently logged in user or null if no user is logged in.
- * @return Authorization result,
+ * Determines if the operation is allowed on the resource.
+ *
+ * @param aPath Path of the resource.
+ * @param aOperation Operation to be done.
+ * @param aUser Currently logged in user or null if no user is logged in.
+ *
+ * @return Authorization result,
*/
- protected AuthorizationResult isAllowed(String aPath, Operation aOperation, User aUser) {
- if ( ! pathCondition.matches(aPath) ) {
+ protected AuthorizationResult isAllowed(String aPath, Operation aOperation,
+ User aUser) {
+ if (!pathCondition.matches(aPath)) {
return UNDECIDED;
}
- if ( !operationCondition.matches(aOperation) ) {
- return UNDECIDED;
+
+ if (!operationCondition.matches(aOperation)) {
+ return UNDECIDED;
}
- if ( !userCondition.matches(aUser)) {
+
+ if (!userCondition.matches(aUser)) {
return UNDECIDED;
}
- return result;
+
+ return result;
}
/**
- * Gets the path of the resource.
- * @param aResource Resource, guaranteed to be an instance of
- * {@link #resourceClass}.
- * @return Path of the resource.
+ * Gets the path of the resource.
+ *
+ * @param aResource Resource, guaranteed to be an instance of {@link
+ * #resourceClass}.
+ *
+ * @return Path of the resource.
*/
protected abstract String getResourcePath(Object aResource);
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
- return "UrlAUthorizationRule(result = " + result +
- ", pathCondition = " + pathCondition +
- ", userCondition = " + userCondition +
- ", resourceClass = " + resourceClass + ")";
+ return "UrlAUthorizationRule(result = " + result + ", pathCondition = "
+ + pathCondition + ", userCondition = " + userCondition
+ + ", resourceClass = " + resourceClass + ")";
}
-
+
/**
- * Gets the authorization result for OR mapping.
- * @return Result.
+ * Gets the authorization result for OR mapping.
+ *
+ * @return Result.
*/
protected String getAuthorizationResultString() {
- if ( result == null ) {
- return null;
+ if (result == null) {
+ return null;
}
- return result.toString();
+
+ return result.toString();
}
-
+
/**
- * Sets the authorization result, for OR mapping.
- * @param aResult Result.
+ * Sets the authorization result, for OR mapping.
+ *
+ * @param aResult Result.
*/
protected void setAuthorizationResultString(String aResult) {
result = AuthorizationResult.valueOf(aResult);
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
protected String getResourceClassName() {
- if ( resourceClass == null ) {
+ if (resourceClass == null) {
return "";
}
- return resourceClass.getName();
+
+ return resourceClass.getName();
}
-
- protected void setResourceClassName(String aResourceClass) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResourceClass DOCUMENT ME!
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
+ */
+ protected void setResourceClassName(String aResourceClass) {
try {
resourceClass = Class.forName(aResourceClass);
} catch (ClassNotFoundException e) {
- LOGGER.error("Cannot find resource class '" + aResourceClass + "'", e);
- throw new IllegalArgumentException(e.getMessage(), e);
+ LOGGER.error("Cannot find resource class '" + aResourceClass + "'",
+ e);
+ throw new IllegalArgumentException(e.getMessage(), e);
}
}
/**
+ * DOCUMENT ME!
+ *
* @return Returns the operationCondition.
*/
public OperationCondition getOperationCondition() {
}
/**
+ * DOCUMENT ME!
+ *
* @param aOperationCondition The operationCondition to set.
*/
protected void setOperationCondition(OperationCondition aOperationCondition) {
}
/**
+ * DOCUMENT ME!
+ *
* @return Returns the pathCondition.
*/
public PathCondition getPathCondition() {
}
/**
+ * DOCUMENT ME!
+ *
* @param aPathCondition The pathCondition to set.
*/
protected void setPathCondition(PathCondition aPathCondition) {
}
/**
+ * DOCUMENT ME!
+ *
* @return Returns the userCondition.
*/
public UserCondition getUserCondition() {
}
/**
+ * DOCUMENT ME!
+ *
* @param aUserCondition The userCondition to set.
*/
protected void setUserCondition(UserCondition aUserCondition) {
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import org.wamblee.persistence.Persistent;
+
import org.wamblee.usermgt.User;
+
/**
* Condition used to match a user against a specified set of users.
*
* @author Erik Brakkee
*/
public interface UserCondition extends Persistent {
-
/**
- * Determines if the condition matches.
- * @param aUser user to check.
- * @return True if the condition matches, false otherwise.
+ * Determines if the condition matches.
+ *
+ * @param aUser user to check.
+ *
+ * @return True if the condition matches, false otherwise.
*/
boolean matches(User aUser);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
/**
- * Represents a write operation on a resource.
+ * Represents a write operation on a resource.
*
* @author Erik Brakkee
*/
public class WriteOperation extends AllOperation {
-
- private static final String OPERATION = "write";
-
/**
+ * DOCUMENT ME!
+ */
+ private static final String OPERATION = "write";
+
+/**
* Constructs the operation.
*
*/
- public WriteOperation() {
- super(OPERATION);
+ public WriteOperation() {
+ super(OPERATION);
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization.hibernate;
import org.wamblee.usermgt.hibernate.UsermgtHibernateMappingFiles;
+
/**
- * Mapping files for authorization.
+ * Mapping files for authorization.
*
* @author Erik Brakkee
*/
public class AuthorizationMappingFiles extends UsermgtHibernateMappingFiles {
-
- public AuthorizationMappingFiles() {
- super(new String[]{ "hbm/AuthorizationRule.hbm.xml", "hbm/UserCondition.hbm.xml",
- "hbm/AuthorizationService.hbm.xml", "hbm/OperationCondition.hbm.xml", "hbm/PathCondition.hbm.xml",
- "hbm/TestAuthorizationRule.hbm.xml" });
+/**
+ * Creates a new AuthorizationMappingFiles object.
+ */
+ public AuthorizationMappingFiles() {
+ super(new String[] {
+ "hbm/AuthorizationRule.hbm.xml", "hbm/UserCondition.hbm.xml",
+ "hbm/AuthorizationService.hbm.xml",
+ "hbm/OperationCondition.hbm.xml", "hbm/PathCondition.hbm.xml",
+ "hbm/TestAuthorizationRule.hbm.xml"
+ });
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.security.authorization.hibernate;
-import java.util.List;
-
import org.springframework.orm.hibernate3.HibernateTemplate;
+
import org.wamblee.persistence.AbstractPersistent;
import org.wamblee.persistence.hibernate.HibernateSupport;
+
import org.wamblee.security.authorization.AuthorizationRule;
import org.wamblee.security.authorization.AuthorizationService;
import org.wamblee.security.authorization.DefaultAuthorizationService;
import org.wamblee.security.authorization.Operation;
+
import org.wamblee.usermgt.UserAccessor;
+import java.util.List;
+
+
/**
- * Authorization service with persistent storage.
- * This is a wrapper for {@link org.wamblee.security.authorization.DefaultAuthorizationService}
- * which refreshes the state of the service at certain time intervals.
+ * Authorization service with persistent storage. This is a wrapper for
+ * {@link org.wamblee.security.authorization.DefaultAuthorizationService}
+ * which refreshes the state of the service at certain time intervals.
*
* @author Erik Brakkee
*/
public class PersistentAuthorizationService extends AbstractPersistent
- implements AuthorizationService {
-
+ implements AuthorizationService {
/**
* Name of query to find the service by name.
*/
* User accessor.
*/
private UserAccessor userAccessor;
-
+
/**
- * Name of the service.
+ * Name of the service.
*/
- private String name;
+ private String name;
/**
- * Refresh interval in milliseconds.
+ * Refresh interval in milliseconds.
*/
private final long refreshInterval;
-
+
/**
- * Last refresh time.
+ * Last refresh time.
*/
- private long lastRefreshTime;
+ private long lastRefreshTime;
- /**
+/**
* Constructs the persistent service.
*
* @param aName
* start of every operation.
*/
public PersistentAuthorizationService(String aName,
- HibernateTemplate aTemplate, UserAccessor aAccessor,
- long aRefreshInterval) {
- template = aTemplate;
- refreshInterval = aRefreshInterval;
- lastRefreshTime = System.currentTimeMillis();
- userAccessor = aAccessor;
- name = aName;
+ HibernateTemplate aTemplate, UserAccessor aAccessor,
+ long aRefreshInterval) {
+ template = aTemplate;
+ refreshInterval = aRefreshInterval;
+ lastRefreshTime = System.currentTimeMillis();
+ userAccessor = aAccessor;
+ name = aName;
}
/**
- * Initialize service if needed.
+ * Initialize service if needed.
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
*/
private void initialize() {
if (service == null) {
List<DefaultAuthorizationService> result = template
- .findByNamedQueryAndNamedParam(FIND_QUERY, NAME_PARAM,
- name);
+ .findByNamedQueryAndNamedParam(FIND_QUERY, NAME_PARAM, name);
if (result.size() > 1) {
throw new IllegalArgumentException(
- "Returned more than one service for name '" + name
- + "' (" + result.size() + ")");
+ "Returned more than one service for name '" + name + "' ("
+ + result.size() + ")");
}
if (result.size() == 0) {
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object,
* org.wamblee.security.authorization.Operation)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResource DOCUMENT ME!
+ * @param aOperation DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean isAllowed(Object aResource, Operation aOperation) {
initialize();
refresh();
+
return service.isAllowed(aResource, aOperation);
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aResource DOCUMENT ME!
+ * @param aOperation DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public <T> T check(T aResource, Operation aOperation) {
initialize();
refresh();
+
return service.check(aResource, aOperation);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.AuthorizationService#getRules()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public AuthorizationRule[] getRules() {
initialize();
refresh();
+
return service.getRules();
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRule DOCUMENT ME!
+ */
public void appendRule(AuthorizationRule aRule) {
initialize();
refresh();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.AuthorizationService#removeRule(int)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aIndex DOCUMENT ME!
+ */
public void removeRule(int aIndex) {
initialize();
refresh();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int,
* org.wamblee.security.authorization.AuthorizationRule)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aIndex DOCUMENT ME!
+ * @param aRule DOCUMENT ME!
+ */
public void insertRuleAfter(int aIndex, AuthorizationRule aRule) {
initialize();
refresh();
/**
* Refreshes the state of the service through hibernate.
- *
*/
private synchronized void refresh() {
- long time = System.currentTimeMillis();
- if ( time - lastRefreshTime > refreshInterval ) {
+ long time = System.currentTimeMillis();
+
+ if ((time - lastRefreshTime) > refreshInterval) {
template.refresh(service);
- lastRefreshTime = time;
+ lastRefreshTime = time;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.security.encryption;
+import org.apache.commons.codec.binary.Hex;
+
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
-import org.apache.commons.codec.binary.Hex;
/**
- * MD5 Hex encoder.
+ * MD5 Hex encoder.
*
* @author Erik Brakkee
*/
public class Md5HexMessageDigester implements MessageDigester {
-
- /**
+/**
* Constructs the message digester.
*
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.security.MessageDigester#hash(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aValue DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
+ */
public String hash(String aValue) {
try {
- MessageDigest digest = MessageDigest.getInstance("MD5");
- byte[] result = digest.digest(aValue.getBytes());
- char[] charResult = Hex.encodeHex(result);
+ MessageDigest digest = MessageDigest.getInstance("MD5");
+ byte[] result = digest.digest(aValue.getBytes());
+ char[] charResult = Hex.encodeHex(result);
+
return new String(charResult);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("MD5 not supported????");
}
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.encryption;
/**
* Utility class that encapsulates a message digest method.
*/
public interface MessageDigester {
-
/**
- * Computes a message digest for a value and encodes it in some way.
- * @param aValue Value to compute digest for.
- * @return Encoded digest.
+ * Computes a message digest for a value and encodes it in some
+ * way.
+ *
+ * @param aValue Value to compute digest for.
+ *
+ * @return Encoded digest.
*/
- String hash(String aValue);
-
+ String hash(String aValue);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
-import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_USER;
-
import org.wamblee.security.encryption.MessageDigester;
+import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_USER;
/**
- * User set base class.
+ * User set base class.
*/
public abstract class AbstractUserSet implements UserSet {
-
/**
- * Password validator.
+ * Password validator.
*/
- private NameValidator passwordValidator;
-
+ private NameValidator passwordValidator;
+
/**
- * Password encoder.
+ * Password encoder.
*/
- private MessageDigester passwordEncoder;
+ private MessageDigester passwordEncoder;
-
- protected AbstractUserSet(NameValidator aPasswordValidator,
- MessageDigester aPasswordEncoder) {
- passwordValidator = aPasswordValidator;
- passwordEncoder = aPasswordEncoder;
+/**
+ * Creates a new AbstractUserSet object.
+ *
+ * @param aPasswordValidator DOCUMENT ME!
+ * @param aPasswordEncoder DOCUMENT ME!
+ */
+ protected AbstractUserSet(NameValidator aPasswordValidator,
+ MessageDigester aPasswordEncoder) {
+ passwordValidator = aPasswordValidator;
+ passwordEncoder = aPasswordEncoder;
}
-
+
/**
- * Sets the password validtor and encoder in the user.
- * @param aUser User.
+ * Sets the password validtor and encoder in the user.
+ *
+ * @param aUser User.
*/
- protected void setPasswordInfo(User aUser) {
+ protected void setPasswordInfo(User aUser) {
aUser.setPasswordValidator(passwordValidator);
aUser.setPasswordEncoder(passwordEncoder);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.UserSet#createUser(java.lang.String, java.lang.String, org.wamblee.usermgt.Group)
*/
- public User createUser(String aUsername, String aPassword, Group aGroup) throws UserMgtException {
- User user = new User(aUsername, aPassword, aGroup, passwordValidator, passwordEncoder);
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUsername DOCUMENT ME!
+ * @param aPassword DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ public User createUser(String aUsername, String aPassword, Group aGroup)
+ throws UserMgtException {
+ User user = new User(aUsername, aPassword, aGroup, passwordValidator,
+ passwordEncoder);
+
if (contains(user)) {
throw new UserMgtException(DUPLICATE_USER, user);
}
+
add(user);
+
return user;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
+import org.wamblee.persistence.AbstractPersistent;
+
import java.io.Serializable;
-import org.wamblee.persistence.AbstractPersistent;
/**
- * Represents a group.
+ * Represents a group.
*
* @author Erik Brakkee
*/
-public class Group extends AbstractPersistent implements Serializable, Comparable {
-
+public class Group extends AbstractPersistent implements Serializable,
+ Comparable {
/**
- * Group name.
+ * Group name.
*/
- private String name;
+ private String name;
- /**
+/**
* Constructs the group.
* @param aName
*/
Group(String aName) {
super();
- name = aName;
+ name = aName;
}
-
- public Group(Group aGroup) {
- super(aGroup);
+
+/**
+ * Creates a new Group object.
+ *
+ * @param aGroup DOCUMENT ME!
+ */
+ public Group(Group aGroup) {
+ super(aGroup);
name = aGroup.name;
}
-
- protected Group() {
- super();
- name = null;
+
+/**
+ * Creates a new Group object.
+ */
+ protected Group() {
+ super();
+ name = null;
}
-
+
/**
- * Gets the name of the group.
- * @return Group name.
+ * Gets the name of the group.
+ *
+ * @return Group name.
*/
- public String getName() {
- return name;
+ public String getName() {
+ return name;
}
-
+
/**
- * Sets the group name.
- * @param aName Group name.
+ * Sets the group name.
+ *
+ * @param aName Group name.
*/
void setName(String aName) {
- name = aName;
+ name = aName;
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public boolean equals(Object aGroup) {
- if ( !( aGroup instanceof Group )) {
- return false;
+ if (!(aGroup instanceof Group)) {
+ return false;
}
- return name.equals(((Group)aGroup).name);
+
+ return name.equals(((Group) aGroup).name);
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public int hashCode() {
- return name.hashCode();
+ return name.hashCode();
}
-
+
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(T)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int compareTo(Object aGroup) {
- return name.compareTo(((Group)aGroup).name);
+ return name.compareTo(((Group) aGroup).name);
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
return "Group(pk = " + getPrimaryKey() + ", name=" + name + ")";
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
import java.util.Set;
+
/**
* Represents a set of groups. A typical implemnetation would be, a readonly implementation
* defined in a configuration file or a list of groups defined in a database.
* @author Erik Brakkee
*/
public interface GroupSet {
-
/**
- * Must be called when the group has been modified to notify the group set.
- * @param aGroup Group that was modified.
+ * Must be called when the group has been modified to notify the
+ * group set.
+ *
+ * @param aGroup Group that was modified.
*/
- void groupModified(Group aGroup);
-
+ void groupModified(Group aGroup);
+
/**
- * Finds the group by name.
- * @param aName Group name.
- * @return Group or null if not found.
+ * Finds the group by name.
+ *
+ * @param aName Group name.
+ *
+ * @return Group or null if not found.
*/
Group find(String aName);
-
+
/**
- * Determines if the group exists.
- * @param aGroup Group.
- * @return True iff the group exists.
+ * Determines if the group exists.
+ *
+ * @param aGroup Group.
+ *
+ * @return True iff the group exists.
*/
boolean contains(Group aGroup);
-
+
/**
- * Adds a group. If the group already exists, the existing group set
- * is left unchanged.
+ * Adds a group. If the group already exists, the existing group
+ * set is left unchanged.
+ *
* @param aGroup Group.
+ *
+ * @return DOCUMENT ME!
*/
boolean add(Group aGroup);
-
+
/**
- * Removes a group. If the group does not exist, this method is a no-op.
+ * Removes a group. If the group does not exist, this method is a
+ * no-op.
+ *
* @param aGroup Group to remove.
- * @return True if the group was removed, false otherwise.
+ *
+ * @return True if the group was removed, false otherwise.
*/
boolean remove(Group aGroup);
-
+
/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
* Returns the current groups.
* @return Groups.
*/
Set<Group> list();
/**
- * @return The number of groups.
+ * DOCUMENT ME!
+ *
+ * @return The number of groups.
*/
- int size();
+ int size();
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
import java.util.Set;
import java.util.TreeSet;
+
/**
- * In-memory group set implementation.
+ * In-memory group set implementation.
*
* @author Erik Brakkee
*/
public class InMemoryGroupSet implements GroupSet {
-
/**
- * Groups.
+ * Groups.
*/
- private Set<Group> groups;
-
- /**
+ private Set<Group> groups;
+
+/**
* Constructs an empty group set.
*/
- public InMemoryGroupSet() {
+ public InMemoryGroupSet() {
groups = new TreeSet<Group>();
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ */
public void groupModified(Group aGroup) {
- groups.remove(aGroup);
+ groups.remove(aGroup);
groups.add(aGroup);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#find(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Group find(String aName) {
- for (Group group: groups) {
- if ( group.getName().equals(aName)) {
+ for (Group group : groups) {
+ if (group.getName().equals(aName)) {
return new Group(group);
}
}
- return null;
+
+ return null;
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean contains(Group aGroup) {
return groups.contains(aGroup);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean add(Group aGroup) {
return groups.add(aGroup);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean remove(Group aGroup) {
return groups.remove(aGroup);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#list()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<Group> list() {
- Set<Group> list = new TreeSet<Group>();
- for (Group group: groups) {
+ Set<Group> list = new TreeSet<Group>();
+
+ for (Group group : groups) {
list.add(new Group(group));
}
+
return list;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#size()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int size() {
- return groups.size();
+ return groups.size();
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt;
+import org.wamblee.security.encryption.MessageDigester;
+
import java.util.Set;
import java.util.TreeSet;
-import org.wamblee.security.encryption.MessageDigester;
/**
* In-memory user set.
* @author Erik Brakkee
*/
public class InMemoryUserSet extends AbstractUserSet {
-
/**
- * Users. All users in this set have their password validator and encoder set.
+ * Users. All users in this set have their password validator and
+ * encoder set.
*/
private Set<User> users;
- /**
+/**
* Constructs an empty user set.
*/
- public InMemoryUserSet(NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) {
+ public InMemoryUserSet(NameValidator aPasswordValidator,
+ MessageDigester aPasswordEncoder) {
super(aPasswordValidator, aPasswordEncoder);
users = new TreeSet<User>();
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ */
public void userModified(User aUser) {
users.remove(aUser);
- setPasswordInfo(aUser);
+ setPasswordInfo(aUser);
users.add(aUser);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#find(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public User find(String aName) {
for (User user : users) {
if (user.getName().equals(aName)) {
return new User(user);
}
}
+
return null;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean add(User aUser) {
setPasswordInfo(aUser);
+
return users.add(aUser);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean contains(User aUser) {
return users.contains(aUser);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean remove(User aUser) {
return users.remove(aUser);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#list()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<User> list() {
Set<User> list = new TreeSet<User>();
+
for (User user : users) {
list.add(new User(user));
}
+
return list;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#list(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<User> list(Group aGroup) {
Set<User> result = new TreeSet<User>();
+
for (User user : users) {
if (user.getGroups().contains(aGroup)) {
result.add(new User(user));
}
}
+
return result;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.UserSet#size()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int size() {
- return users.size();
+ return users.size();
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt;
import java.security.AccessController;
import java.security.Principal;
+
import java.util.Set;
import javax.security.auth.Subject;
+
/**
- * Implementation of the user accessor that retrieves user information
- * from JAAS.
+ * Implementation of the user accessor that retrieves user information from
+ * JAAS.
*
* @author Erik Brakkee
*/
public class JaasUserAccessor implements UserAccessor {
-
/**
- * User administration to use.
+ * User administration to use.
*/
private UserAdministration admin;
/**
- * Class of the JAAS user principal.
+ * Class of the JAAS user principal.
*/
private Class userPrincipalClass;
- /**
+/**
* Constructs user accessor.
* @param aAdmin User administration.
* @param aUserClassName Class name of the user principal.
*/
public JaasUserAccessor(UserAdministration aAdmin, String aUserClassName) {
admin = aAdmin;
+
try {
userPrincipalClass = Class.forName(aUserClassName);
- if ( !Principal.class.isAssignableFrom(userPrincipalClass)) {
- throw new IllegalArgumentException("Specified class '" + aUserClassName + "' is not a subclass of '" +
- Principal.class.getName());
+
+ if (!Principal.class.isAssignableFrom(userPrincipalClass)) {
+ throw new IllegalArgumentException("Specified class '"
+ + aUserClassName + "' is not a subclass of '"
+ + Principal.class.getName());
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public User getCurrentUser() {
Subject subject = Subject.getSubject(AccessController.getContext());
+
if (subject == null) {
return null;
}
+
Principal userPrincipal = getUserPrincipal(subject);
-
+
return admin.getUser(userPrincipal.getName());
}
/**
- * Gets the user principal from the subject.
- * @param subject Subject.
- * @return User principal.
- * @throws IllegalArgumentException In case there is a duplicate principal or the principal was not found.
+ * Gets the user principal from the subject.
+ *
+ * @param subject Subject.
+ *
+ * @return User principal.
+ *
+ * @throws IllegalArgumentException In case there is a duplicate principal
+ * or the principal was not found.
*/
private Principal getUserPrincipal(Subject subject) {
- Set<Principal> principals = subject.getPrincipals();
- Principal userPrincipal = null;
- for ( Principal principal: principals) {
- if ( principal.getClass().equals(userPrincipalClass)) {
- if ( userPrincipal != null ) {
+ Set<Principal> principals = subject.getPrincipals();
+ Principal userPrincipal = null;
+
+ for (Principal principal : principals) {
+ if (principal.getClass().equals(userPrincipalClass)) {
+ if (userPrincipal != null) {
throw new IllegalArgumentException(
- "Multiple principals for class '" + userPrincipalClass + "', subject: " + subject);
+ "Multiple principals for class '" + userPrincipalClass
+ + "', subject: " + subject);
}
- userPrincipal = principal;
+
+ userPrincipal = principal;
}
}
- if ( userPrincipal == null ) {
+
+ if (userPrincipal == null) {
throw new IllegalArgumentException(
- "No user principal found for class '" + userPrincipalClass + "', subject: " + subject);
+ "No user principal found for class '" + userPrincipalClass
+ + "', subject: " + subject);
}
+
return userPrincipal;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
/**
* @author Erik Brakkee
*/
public interface NameValidator {
-
/**
- * Validates a name.
+ * Validates a name.
+ *
* @param aName Name
- * @throws UserMgtException In case the name is invalid.
+ *
+ * @throws UserMgtException In case the name is invalid.
*/
- void validate(String aName) throws UserMgtException;
+ void validate(String aName) throws UserMgtException;
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
import org.wamblee.usermgt.UserMgtException.Reason;
+
/**
- * Validation of names based on a regular expression.
+ * Validation of names based on a regular expression.
*
* @author Erik Brakkee
*/
public class RegexpNameValidator implements NameValidator {
-
/**
- * Convenience pattern for an id.
+ * Convenience pattern for an id.
*/
public static final String ID_PATTERN = "[a-zA-Z]+[a-zA-Z0-9]*";
-
+
/**
- * Convenience pattern for a password consisting of at least 6 characters.
+ * Convenience pattern for a password consisting of at least 6
+ * characters.
*/
public static final String PASSWORD_PATTERN = ".{6}.*";
-
+
/**
- * Pattern to use.
+ * Pattern to use.
*/
private String pattern;
-
+
/**
- * Reason to use when validation fails.
+ * Reason to use when validation fails.
*/
- private Reason reason;
-
+ private Reason reason;
+
/**
- * Message to report.
+ * Message to report.
*/
- private String message;
-
- /**
+ private String message;
+
+/**
* Validates a regular expression.
* @param aPattern Pattern that names must comply to.
* @param aReason Reason to report when validation fails.
* @param aMessage Message to report.
*/
- public RegexpNameValidator(String aPattern, Reason aReason, String aMessage) {
- pattern = aPattern;
- reason = aReason;
- message = aMessage;
+ public RegexpNameValidator(String aPattern, Reason aReason, String aMessage) {
+ pattern = aPattern;
+ reason = aReason;
+ message = aMessage;
}
-
- /**
+
+/**
* Convenience constructor with all string parameters. Useful for configuration
* in Spring.
* @param aPattern Pattern to use.
* @param aReason Reason.
* @param aMessage Message.
*/
- public RegexpNameValidator(String aPattern, String aReason, String aMessage) {
+ public RegexpNameValidator(String aPattern, String aReason, String aMessage) {
this(aPattern, Reason.valueOf(aReason), aMessage);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.NameValidator#validate(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public void validate(String aName) throws UserMgtException {
- if ( !aName.matches(pattern)) {
- throw new UserMgtException(reason, message);
+ if (!aName.matches(pattern)) {
+ throw new UserMgtException(reason, message);
}
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt;
+import org.wamblee.persistence.AbstractPersistent;
+
+import org.wamblee.security.encryption.MessageDigester;
+
+import org.wamblee.usermgt.UserMgtException.Reason;
+
import java.io.Serializable;
+
import java.util.Set;
import java.util.TreeSet;
-import org.wamblee.persistence.AbstractPersistent;
-import org.wamblee.security.encryption.MessageDigester;
-import org.wamblee.usermgt.UserMgtException.Reason;
/**
- * Represents a user.
- * The methods for managing the groups of the user have package scope.
- * Managing the groups of the user should be done through the
- * {@link org.wamblee.usermgt.UserAdministration} interface.
+ * Represents a user. The methods for managing the groups of the user have
+ * package scope. Managing the groups of the user should be done through the
+ * {@link org.wamblee.usermgt.UserAdministration} interface.
*/
-public class User extends AbstractPersistent implements Serializable, Comparable {
-
+public class User extends AbstractPersistent implements Serializable,
+ Comparable {
/**
- * User name.
+ * User name.
*/
private String name;
/**
- * Password.
+ * Password.
*/
private String password;
/**
- * Groups the user belongs to.
+ * Groups the user belongs to.
*/
private Set<Group> groups;
-
+
/**
- * Password validator.
+ * Password validator.
*/
- private NameValidator passwordValidator;
+ private NameValidator passwordValidator;
/**
- * Password encoder.
+ * Password encoder.
*/
private MessageDigester passwordEncoder;
-
- /**
+
+/**
* Constructs the user.
* @param aName User name.
* @param aPassword Password.
* @param aGroup Group the user belongs to.
*/
- User(String aName, String aPassword, Group aGroup, NameValidator aPasswordValidator,
- MessageDigester aPasswordEncoder) throws UserMgtException {
- super();
+ User(String aName, String aPassword, Group aGroup,
+ NameValidator aPasswordValidator, MessageDigester aPasswordEncoder)
+ throws UserMgtException {
+ super();
name = aName;
aPasswordValidator.validate(aPassword);
- password = aPasswordEncoder.hash(aPassword);
- groups = new TreeSet<Group>();
+ password = aPasswordEncoder.hash(aPassword);
+ groups = new TreeSet<Group>();
groups.add(aGroup);
- passwordValidator = aPasswordValidator;
- passwordEncoder = aPasswordEncoder;
+ passwordValidator = aPasswordValidator;
+ passwordEncoder = aPasswordEncoder;
}
-
- public User(User aUser) {
- super(aUser);
- name = aUser.name;
- password = aUser.password;
- groups = new TreeSet<Group>();
- for (Group group: aUser.groups) {
- groups.add(new Group(group));
+
+/**
+ * Creates a new User object.
+ *
+ * @param aUser DOCUMENT ME!
+ */
+ public User(User aUser) {
+ super(aUser);
+ name = aUser.name;
+ password = aUser.password;
+ groups = new TreeSet<Group>();
+
+ for (Group group : aUser.groups) {
+ groups.add(new Group(group));
}
- passwordValidator = aUser.passwordValidator;
- passwordEncoder = aUser.passwordEncoder;
+
+ passwordValidator = aUser.passwordValidator;
+ passwordEncoder = aUser.passwordEncoder;
}
-
- User() {
- super();
- name = null;
- password = null;
- groups = null;
- passwordValidator = null;
- passwordEncoder = null;
+
+/**
+ * Creates a new User object.
+ */
+ User() {
+ super();
+ name = null;
+ password = null;
+ groups = null;
+ passwordValidator = null;
+ passwordEncoder = null;
}
-
+
/**
- * Sets the password validator.
- * @param aPasswordValidator Validator.
+ * Sets the password validator.
+ *
+ * @param aPasswordValidator Validator.
*/
- public void setPasswordValidator(NameValidator aPasswordValidator) {
+ public void setPasswordValidator(NameValidator aPasswordValidator) {
passwordValidator = aPasswordValidator;
}
-
+
/**
- * Sets the password encoder.
- * @param aPasswordEncoder Encoder.
+ * Sets the password encoder.
+ *
+ * @param aPasswordEncoder Encoder.
*/
- public void setPasswordEncoder(MessageDigester aPasswordEncoder) {
- passwordEncoder = aPasswordEncoder;
+ public void setPasswordEncoder(MessageDigester aPasswordEncoder) {
+ passwordEncoder = aPasswordEncoder;
}
/**
+ * DOCUMENT ME!
+ *
* @return Returns the password.
*/
String getPassword() {
return password;
}
-
+
/**
- * Checks the password.
- * @param aPassword Password to check.
- * @throws UserMgtException In case the password is incorrect.
+ * Checks the password.
+ *
+ * @param aPassword Password to check.
+ *
+ * @throws UserMgtException In case the password is incorrect.
*/
public void checkPassword(String aPassword) throws UserMgtException {
String encoded = passwordEncoder.hash(aPassword);
- if ( !password.equals(encoded) ) {
+
+ if (!password.equals(encoded)) {
throw new UserMgtException(Reason.INVALID_PASSWORD, this);
}
}
-
+
/**
- * Changes the password.
- * @param aOldPassword Old password.
- * @param aNewPassword New password.
- * @throws UserMgtException In case the old password is incorrect.
+ * Changes the password.
+ *
+ * @param aOldPassword Old password.
+ * @param aNewPassword New password.
+ *
+ * @throws UserMgtException In case the old password is incorrect.
*/
- public void changePassword(String aOldPassword, String aNewPassword) throws UserMgtException {
+ public void changePassword(String aOldPassword, String aNewPassword)
+ throws UserMgtException {
checkPassword(aOldPassword);
passwordValidator.validate(aNewPassword);
setPassword(aNewPassword);
}
/**
- * @param aPassword
- * The password to set.
+ * DOCUMENT ME!
+ *
+ * @param aPassword The password to set.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void setPassword(String aPassword) throws UserMgtException {
passwordValidator.validate(aPassword);
password = passwordEncoder.hash(aPassword);
}
-
+
/**
- * For OR mapping.
- * @return Password.
+ * For OR mapping.
+ *
+ * @return Password.
*/
- protected String getPasswordString() {
+ protected String getPasswordString() {
return password;
}
-
+
/**
- * For OR mapping.
- * @param aPassword Password.
+ * For OR mapping.
+ *
+ * @param aPassword Password.
*/
- protected void setPasswordString(String aPassword) {
- password = aPassword;
+ protected void setPasswordString(String aPassword) {
+ password = aPassword;
}
/**
+ * DOCUMENT ME!
+ *
* @return Returns the _user.
*/
public String getName() {
}
/**
- * @param aName
- * The username to set.
+ * DOCUMENT ME!
+ *
+ * @param aName The username to set.
*/
void setName(String aName) {
name = aName;
}
/**
- * Gets the groups the user belongs to.
+ * Gets the groups the user belongs to.
+ *
* @return Groups.
*/
public Set<Group> getGroups() {
- Set<Group> result = new TreeSet<Group>();
+ Set<Group> result = new TreeSet<Group>();
result.addAll(groups);
- return result;
+
+ return result;
}
-
+
/**
- * Checks whether the user belongs to the given group.
- * @param aGroup Group.
+ * Checks whether the user belongs to the given group.
+ *
+ * @param aGroup Group.
+ *
* @return True if the user belongs to the group.
*/
public boolean isInGroup(Group aGroup) {
return groups.contains(aGroup);
}
-
+
/**
- * Checks whether the user belongs to the given group.
- * @param aGroup Group.
+ * Checks whether the user belongs to the given group.
+ *
+ * @param aGroup Group.
+ *
* @return True if the user belongs to the group.
*/
public boolean isInGroup(String aGroup) {
return groups.contains(new Group(aGroup));
}
-
+
/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
* Gets the group set. For OR mapping.
* @return set of groups.
*/
- Set<Group> getGroupSet() {
+ Set<Group> getGroupSet() {
return groups;
}
/**
- * Sets the groups the user belongs to, for OR mapping.
+ * Sets the groups the user belongs to, for OR mapping.
+ *
* @param aGroups Groups.
*/
void setGroupSet(Set<Group> aGroups) {
}
/**
- * Adds the user to a group.
+ * Adds the user to a group.
+ *
* @param aGroup Group to add the user to.
- * @throws UserMgtException In case the user already belongs to the group.
+ *
+ * @throws UserMgtException In case the user already belongs to the group.
*/
void addGroup(Group aGroup) throws UserMgtException {
if (groups.contains(aGroup)) {
throw new UserMgtException(Reason.USER_ALREADY_IN_GROUP, aGroup);
}
+
groups.add(aGroup);
}
/**
- * Removes the user from a group.
- * @param aGroup Group.
+ * Removes the user from a group.
+ *
+ * @param aGroup Group.
+ *
* @throws UserMgtException In case the user does not belong to the group.
*/
void removeGroup(Group aGroup) throws UserMgtException {
if (!groups.contains(aGroup)) {
throw new UserMgtException(Reason.USER_NOT_IN_GROUP, this, aGroup);
}
- if ( groups.size() == 1 ) {
- throw new UserMgtException(Reason.USER_MUST_BE_IN_A_GROUP, this, aGroup);
+
+ if (groups.size() == 1) {
+ throw new UserMgtException(Reason.USER_MUST_BE_IN_A_GROUP, this,
+ aGroup);
}
+
groups.remove(aGroup);
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public boolean equals(Object aUser) {
- if ( !(aUser instanceof User)) {
- return false;
+ if (!(aUser instanceof User)) {
+ return false;
}
- User user = (User)aUser;
+
+ User user = (User) aUser;
+
return name.equals(user.name);
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public int hashCode() {
- return name.hashCode();
+ return name.hashCode();
}
-
+
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
String result = "User(name=" + name + ", password=" + password;
- for (Group group: groups) {
- result += ", group=" + group;
+
+ for (Group group : groups) {
+ result += (", group=" + group);
}
- return result + ")";
+
+ return result + ")";
}
-
+
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(T)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int compareTo(Object aUser) {
- return name.compareTo(((User)aUser).name);
+ return name.compareTo(((User) aUser).name);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
/**
*/
public interface UserAccessor {
/**
- * Gets the current user.
- * @return Currently logged in user or null if no user is found.
+ * Gets the current user.
+ *
+ * @return Currently logged in user or null if no user is found.
*/
- User getCurrentUser();
+ User getCurrentUser();
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt;
+import org.apache.log4j.Logger;
+
import java.security.NoSuchAlgorithmException;
-import org.apache.log4j.Logger;
/**
- * User administration initializer. It populates the user administration with a
- * number of groups and users but only in case no users exist.
+ * User administration initializer. It populates the user administration
+ * with a number of groups and users but only in case no users exist.
*
* @author Erik Brakkee
*/
public class UserAdminInitializer {
-
- private static final Logger LOGGER = Logger.getLogger(UserAdminInitializer.class);
-
/**
+ * DOCUMENT ME!
+ */
+ private static final Logger LOGGER = Logger.getLogger(UserAdminInitializer.class);
+
+/**
* Initializes the user administration in case no users are present.
*
*/
public UserAdminInitializer(UserAdministration aAdmin, String[] aUsers,
- String[] aGroups, String[] aPasswords) throws UserMgtException, NoSuchAlgorithmException {
- if (aUsers.length != aGroups.length
- || aUsers.length != aPasswords.length) {
+ String[] aGroups, String[] aPasswords)
+ throws UserMgtException, NoSuchAlgorithmException {
+ if ((aUsers.length != aGroups.length)
+ || (aUsers.length != aPasswords.length)) {
throw new IllegalArgumentException(
- "Array sizes for users, groups, and passwords differ: "
- + aUsers.length + "," + aGroups.length + ","
- + aPasswords.length);
-
+ "Array sizes for users, groups, and passwords differ: "
+ + aUsers.length + "," + aGroups.length + ","
+ + aPasswords.length);
}
+
if (aAdmin.getUserCount() == 0) {
initialize(aAdmin, aUsers, aGroups, aPasswords);
}
-
}
/**
- * Adds the specified users and groups to the user administration.
- * @param aAdmin User administration.
- * @param aUsers Users.
- * @param aGroups Groups.
- * @param aPasswords Passwords.
- * @throws UserMgtException In case of a problem creating users or groups.
+ * Adds the specified users and groups to the user administration.
+ *
+ * @param aAdmin User administration.
+ * @param aUsers Users.
+ * @param aGroups Groups.
+ * @param aPasswords Passwords.
+ *
+ * @throws UserMgtException In case of a problem creating users or groups.
*/
private void initialize(UserAdministration aAdmin, String[] aUsers,
- String[] aGroups, String[] aPasswords) throws UserMgtException {
+ String[] aGroups, String[] aPasswords) throws UserMgtException {
for (int i = 0; i < aUsers.length; i++) {
- String user = aUsers[i];
- String group = aGroups[i];
+ String user = aUsers[i];
+ String group = aGroups[i];
String password = aPasswords[i];
-
+
if (aAdmin.getUser(user) == null) {
// must create user.
Group groupObj = aAdmin.getGroup(group);
+
if (groupObj == null) {
// must create group
LOGGER.info("Creating group: " + group);
groupObj = aAdmin.createGroup(group);
}
- assert groupObj != null;
-
+ assert groupObj != null;
+
LOGGER.info("Creating user: " + user + " password: " + password);
aAdmin.createUser(user, password, groupObj);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt;
import java.util.Set;
+
/**
* Interface for user administration. Manages the users and groups.
*
* @author Erik Brakkee
*/
public interface UserAdministration {
-
/**
- * Creates a new user.
- * @param aUser Username.
- * @param aPassword Password.
- * @param aGroup Group.
- * @return User.
- * @throws UserMgtException In case there is a conflict with an existing user.
- */
- User createUser(String aUser, String aPassword, Group aGroup) throws UserMgtException;
-
+ * Creates a new user.
+ *
+ * @param aUser Username.
+ * @param aPassword Password.
+ * @param aGroup Group.
+ *
+ * @return User.
+ *
+ * @throws UserMgtException In case there is a conflict with an existing
+ * user.
+ */
+ User createUser(String aUser, String aPassword, Group aGroup)
+ throws UserMgtException;
+
/**
- * Creates a new group.
- * @param aName Group name.
+ * Creates a new group.
+ *
+ * @param aName Group name.
+ *
* @return Group
- * @throws UserMgtException In case there is a conflict with an existing group.
+ *
+ * @throws UserMgtException In case there is a conflict with an existing
+ * group.
*/
Group createGroup(String aName) throws UserMgtException;
-
- /**
- * @return Number of users.
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return Number of users.
*/
- int getUserCount();
-
+ int getUserCount();
+
/**
- * @return Number of groups.
+ * DOCUMENT ME!
+ *
+ * @return Number of groups.
*/
- int getGroupCount();
-
+ int getGroupCount();
+
/**
- * Must be called when the user is modified.
+ * Must be called when the user is modified.
+ *
* @param aUser User.
*/
void userModified(User aUser);
-
+
/**
- * Must be called when the group is modified.
- * @param aGroup Group.
+ * Must be called when the group is modified.
+ *
+ * @param aGroup Group.
*/
- void groupModified(Group aGroup);
+ void groupModified(Group aGroup);
/**
- * Gets the user for a given name.
- * @param aName User name.
- * @return User or null if not found.
+ * Gets the user for a given name.
+ *
+ * @param aName User name.
+ *
+ * @return User or null if not found.
*/
- User getUser(String aName);
-
+ User getUser(String aName);
+
/**
- * Gets the group for a given group name.
- * @param aName Group name.
- * @return Group or null if not found.
+ * Gets the group for a given group name.
+ *
+ * @param aName Group name.
+ *
+ * @return Group or null if not found.
*/
- Group getGroup(String aName);
-
+ Group getGroup(String aName);
+
/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
* Get the users.
* @return All known users.
*/
- Set<User> getUsers();
-
+ Set<User> getUsers();
+
/**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
* Gets the users for a given group.
* @param aGroup Group.
* @return Set of users (always non-null).
*/
Set<User> getUsers(Group aGroup);
-
+
/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
* Gets all known groups.
* @return Groups.
*/
Set<Group> getGroups();
-
+
/**
- * Renames a user.
- * @param aUser User object for which user name must be changed.
- * @param aUserName New user name.
- * @throws UserMgtException In case the user is not known or the new user
- * name is already in use by another user.
+ * Renames a user.
+ *
+ * @param aUser User object for which user name must be changed.
+ * @param aUserName New user name.
+ *
+ * @throws UserMgtException In case the user is not known or the new user
+ * name is already in use by another user.
*/
void renameUser(User aUser, String aUserName) throws UserMgtException;
-
+
/**
- * Renames a group.
- * @param aGroup Group to rename.
- * @param aGroupName New name for the group.
- * @throws UserMgtException In case the new group name is already used by
- * another group of if the existing group is unknown.
+ * Renames a group.
+ *
+ * @param aGroup Group to rename.
+ * @param aGroupName New name for the group.
+ *
+ * @throws UserMgtException In case the new group name is already used by
+ * another group of if the existing group is unknown.
*/
void renameGroup(Group aGroup, String aGroupName) throws UserMgtException;
-
+
/**
- * Removes the user.
- * @param aUser User to remove.
- * @throws UserMgtException In case the user does not exist.
+ * Removes the user.
+ *
+ * @param aUser User to remove.
+ *
+ * @throws UserMgtException In case the user does not exist.
*/
void removeUser(User aUser) throws UserMgtException;
-
+
/**
- * Removes the group.
- * @param aGroup Group to remove.
- * @throws UserMgtException In case there are still users that are in the given group.
+ * Removes the group.
+ *
+ * @param aGroup Group to remove.
+ *
+ * @throws UserMgtException In case there are still users that are in the
+ * given group.
*/
void removeGroup(Group aGroup) throws UserMgtException;
-
+
/**
- * Adds a user to a group.
- * @param aUser User.
- * @param aGroup Group.
- * @throws UserMgtException In case the user or group or not known or if the user
- * is already part of the group.
+ * Adds a user to a group.
+ *
+ * @param aUser User.
+ * @param aGroup Group.
+ *
+ * @throws UserMgtException In case the user or group or not known or if
+ * the user is already part of the group.
*/
void addUserToGroup(User aUser, Group aGroup) throws UserMgtException;
-
+
/**
- * Removes a user from a group.
+ * Removes a user from a group.
+ *
* @param aUser User
* @param aGroup Group
- * @throws UserMgtException In case the user or group are unknown or if the user
- * is not part of the group.
+ *
+ * @throws UserMgtException In case the user or group are unknown or if the
+ * user is not part of the group.
*/
- void removeUserFromGroup(User aUser, Group aGroup) throws UserMgtException;
+ void removeUserFromGroup(User aUser, Group aGroup)
+ throws UserMgtException;
}
-
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt;
import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_GROUP;
import java.util.Set;
+
/**
* Administration of users and groups.
*
* @author Erik Brakkee
*/
public class UserAdministrationImpl implements UserAdministration {
-
/**
* All known users.
*/
* All known groups.
*/
private GroupSet groups;
-
+
/**
- * Validator for user names.
+ * Validator for user names.
*/
private NameValidator userValidator;
-
+
/**
- * Validator for group names.
+ * Validator for group names.
*/
private NameValidator groupValidator;
-
- /**
+
+/**
* Constructs empty user administration.
*
*/
- public UserAdministrationImpl(UserSet aUsers, GroupSet aGroups, NameValidator aUserValidator,
- NameValidator aGroupValidator) {
- users = aUsers;
- groups = aGroups;
- userValidator = aUserValidator;
- groupValidator = aGroupValidator;
+ public UserAdministrationImpl(UserSet aUsers, GroupSet aGroups,
+ NameValidator aUserValidator, NameValidator aGroupValidator) {
+ users = aUsers;
+ groups = aGroups;
+ userValidator = aUserValidator;
+ groupValidator = aGroupValidator;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#createUser(java.lang.String,
* java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ * @param aPassword DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public User createUser(String aUser, String aPassword, Group aGroup)
- throws UserMgtException {
+ throws UserMgtException {
userValidator.validate(aUser);
checkGroup(aGroup);
+
User user = users.createUser(aUser, aPassword, aGroup);
+
return new User(user);
}
-
+
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#createGroup(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public Group createGroup(String aName) throws UserMgtException {
groupValidator.validate(aName);
+
Group group = new Group(aName);
+
if (groups.contains(group)) {
throw new UserMgtException(DUPLICATE_GROUP, group);
}
+
groups.add(group);
+
return new Group(group);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#userModified(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ */
public void userModified(User aUser) {
users.userModified(aUser);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#groupModified(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ */
public void groupModified(Group aGroup) {
groups.groupModified(aGroup);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getUser(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public User getUser(String aName) {
return users.find(aName);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getGroup(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Group getGroup(String aName) {
return groups.find(aName);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getUsers()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<User> getUsers() {
return users.list();
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getUsers(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<User> getUsers(Group aGroup) {
return users.list(aGroup);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#getGroups()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<Group> getGroups() {
return groups.list();
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#removeUser(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public void removeUser(User aUser) throws UserMgtException {
checkUser(aUser);
users.remove(aUser);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#removeGroup(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public void removeGroup(Group aGroup) throws UserMgtException {
checkGroup(aGroup);
+
if (getUsers(aGroup).size() > 0) {
throw new UserMgtException(GROUP_STILL_OCCUPIED, aGroup);
}
+
groups.remove(aGroup);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#renameUser(org.wamblee.usermgt.User,
* java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ * @param aUserName DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public void renameUser(User aUser, String aUserName)
- throws UserMgtException {
+ throws UserMgtException {
checkUser(aUser);
+
if (aUser.getName().equals(aUserName)) {
throw new UserMgtException(TRIVIAL_RENAME, aUser);
}
+
if (users.find(aUserName) != null) {
throw new UserMgtException(DUPLICATE_USER, aUser);
}
+
userValidator.validate(aUserName);
// we are modifying the user so we should re-insert it into the set
// after renaming it.
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#renameGroup(org.wamblee.usermgt.Group,
* java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ * @param aGroupName DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public void renameGroup(Group aGroup, String aGroupName)
- throws UserMgtException {
+ throws UserMgtException {
checkGroup(aGroup);
+
if (aGroup.getName().equals(aGroupName)) {
throw new UserMgtException(TRIVIAL_RENAME, aGroup);
}
+
if (groups.find(aGroupName) != null) {
throw new UserMgtException(DUPLICATE_GROUP, aGroup);
}
+
groupValidator.validate(aGroupName);
// we are renaming the group so we should re-insert it into the set
// after renaming it.
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#addUserToGroup(org.wamblee.usermgt.User,
* org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public void addUserToGroup(User aUser, Group aGroup)
- throws UserMgtException {
+ throws UserMgtException {
checkUser(aUser);
checkGroup(aGroup);
aUser.addGroup(aGroup);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministration#removeUserFromGroup(org.wamblee.usermgt.User,
* org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
public void removeUserFromGroup(User aUser, Group aGroup)
- throws UserMgtException {
+ throws UserMgtException {
checkUser(aUser);
checkGroup(aGroup);
aUser.removeGroup(aGroup);
}
/**
+ * DOCUMENT ME!
+ *
* @param aUser
+ *
* @throws UserMgtException
*/
private void checkUser(User aUser) throws UserMgtException {
}
/**
+ * DOCUMENT ME!
+ *
* @param aGroup
+ *
* @throws UserMgtException
*/
private void checkGroup(Group aGroup) throws UserMgtException {
throw new UserMgtException(UNKNOWN_GROUP, aGroup);
}
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.UserAdministration#getUserCount()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int getUserCount() {
- return users.size();
+ return users.size();
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.UserAdministration#getGroupCount()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int getGroupCount() {
- return groups.size();
+ return groups.size();
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.usermgt;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.TreeMap;
-
import net.sf.ehcache.Ehcache;
import org.hibernate.SessionFactory;
+
import org.wamblee.cache.EhCache;
+
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.spring.SpringComponent;
-public class UserGroupRepositoryComponent extends SpringComponent {
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TreeMap;
+
- public UserGroupRepositoryComponent(String aName) {
- super(aName, new String[] { "spring/org.wamblee.security.usermgt-repositories.xml" } ,
- createProvided(), createRequired());
-
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class UserGroupRepositoryComponent extends SpringComponent {
+/**
+ * Creates a new UserGroupRepositoryComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ */
+ public UserGroupRepositoryComponent(String aName) {
+ super(aName,
+ new String[] { "spring/org.wamblee.security.usermgt-repositories.xml" },
+ createProvided(), createRequired());
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private static Map<RequiredInterface, String> createRequired() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
- required.put(new DefaultRequiredInterface("sessionFactory", SessionFactory.class), "sessionFactory");
+ required.put(new DefaultRequiredInterface("sessionFactory",
+ SessionFactory.class), "sessionFactory");
+
return required;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private static Map<String, ProvidedInterface> createProvided() {
- Map<String,ProvidedInterface> provided = new HashMap<String,ProvidedInterface>();
- provided.put("userCache", new DefaultProvidedInterface("cache", EhCache.class));
- provided.put(UserSet.class.getName(), new DefaultProvidedInterface("userset", UserSet.class));
- provided.put(GroupSet.class.getName(), new DefaultProvidedInterface("groupset", GroupSet.class));
- return provided;
+ Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+ provided.put("userCache",
+ new DefaultProvidedInterface("cache", EhCache.class));
+ provided.put(UserSet.class.getName(),
+ new DefaultProvidedInterface("userset", UserSet.class));
+ provided.put(GroupSet.class.getName(),
+ new DefaultProvidedInterface("groupset", GroupSet.class));
+
+ return provided;
}
-
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
import java.util.EnumMap;
+
/**
- * User management exception.
+ * User management exception.
*
* @author Erik Brakkee
*/
public class UserMgtException extends Exception {
-
- static final long serialVersionUID = 5585349754997507529L;
-
/**
- * Possible causes for the exception.
- *
+ * DOCUMENT ME!
*/
- public enum Reason {
- UNKNOWN_USER,
- UNKNOWN_GROUP,
- DUPLICATE_USER,
- DUPLICATE_GROUP,
- USER_ALREADY_IN_GROUP,
- USER_NOT_IN_GROUP,
- TRIVIAL_RENAME,
- INVALID_PASSWORD,
- GROUP_STILL_OCCUPIED,
- USER_MUST_BE_IN_A_GROUP,
- INVALID_USERNAME,
- INVALID_GROUPNAME
- }
-
+ static final long serialVersionUID = 5585349754997507529L;
+
/**
- * Mapping of enum to exception message text.
+ * Mapping of enum to exception message text.
*/
- private static final EnumMap<Reason,String> MESSAGES = new EnumMap<Reason,String>(Reason.class);
-
+ private static final EnumMap<Reason, String> MESSAGES = new EnumMap<Reason, String>(Reason.class);
+
static {
MESSAGES.put(Reason.UNKNOWN_USER, "Unknown user");
MESSAGES.put(Reason.UNKNOWN_GROUP, "Unknown group");
MESSAGES.put(Reason.TRIVIAL_RENAME, "Trivial rename");
MESSAGES.put(Reason.INVALID_PASSWORD, "Invalid password");
MESSAGES.put(Reason.GROUP_STILL_OCCUPIED, "Group still occupied");
- MESSAGES.put(Reason.USER_MUST_BE_IN_A_GROUP, "User must be in at least one group");
+ MESSAGES.put(Reason.USER_MUST_BE_IN_A_GROUP,
+ "User must be in at least one group");
MESSAGES.put(Reason.INVALID_USERNAME, "Invalid user name");
MESSAGES.put(Reason.INVALID_GROUPNAME, "Invalid group name");
}
-
+
/**
- * Cause of the exception.
+ * Cause of the exception.
*/
- private Reason cause;
-
+ private Reason cause;
+
/**
- * User or null if no user is relevant for the problem.
+ * User or null if no user is relevant for the problem.
*/
- private User user;
-
+ private User user;
+
/**
- * Group or null if no group is relevant for the problem.
+ * Group or null if no group is relevant for the problem.
*/
- private Group group;
+ private Group group;
+/**
+ * Creates a new UserMgtException object.
+ *
+ * @param aCause DOCUMENT ME!
+ * @param aMessage DOCUMENT ME!
+ */
public UserMgtException(Reason aCause, String aMessage) {
super(MESSAGES.get(aCause) + ": " + aMessage);
- cause = aCause;
+ cause = aCause;
}
-
+
+/**
+ * Creates a new UserMgtException object.
+ *
+ * @param aCause DOCUMENT ME!
+ * @param aUser DOCUMENT ME!
+ */
public UserMgtException(Reason aCause, User aUser) {
this(aCause, "for user '" + aUser.getName() + "'");
- user = aUser;
+ user = aUser;
}
-
+
+/**
+ * Creates a new UserMgtException object.
+ *
+ * @param aCause DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ */
public UserMgtException(Reason aCause, Group aGroup) {
this(aCause, "for group '" + aGroup.getName() + "'");
- group = aGroup;
+ group = aGroup;
}
-
+
+/**
+ * Creates a new UserMgtException object.
+ *
+ * @param aCause DOCUMENT ME!
+ * @param aUser DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ */
public UserMgtException(Reason aCause, User aUser, Group aGroup) {
- this(aCause, "for user '" + aUser.getName() + "' and group '" + aGroup.getName() + "'");
- user = aUser;
- group = aGroup;
+ this(aCause,
+ "for user '" + aUser.getName() + "' and group '" + aGroup.getName()
+ + "'");
+ user = aUser;
+ group = aGroup;
}
/**
- * Gets the cause of the problem.
- * @return Cause.
+ * Gets the cause of the problem.
+ *
+ * @return Cause.
*/
public Reason getReason() {
- return cause;
+ return cause;
}
-
+
/**
- * Gets the user for which the problem occurred.
- * @return User or null if not applicable.
+ * Gets the user for which the problem occurred.
+ *
+ * @return User or null if not applicable.
*/
public User getUser() {
- return user;
+ return user;
}
-
+
/**
- * Gets the group for which the problem occured.
- * @return Group or null if not applicable.
+ * Gets the group for which the problem occured.
+ *
+ * @return Group or null if not applicable.
*/
public Group getGroup() {
return group;
- }
+ }
+
+/**
+ * Possible causes for the exception.
+ *
+ */
+ public enum Reason {UNKNOWN_USER,
+ UNKNOWN_GROUP,
+ DUPLICATE_USER,
+ DUPLICATE_GROUP,
+ USER_ALREADY_IN_GROUP,
+ USER_NOT_IN_GROUP,
+ TRIVIAL_RENAME,
+ INVALID_PASSWORD,
+ GROUP_STILL_OCCUPIED,
+ USER_MUST_BE_IN_A_GROUP,
+ INVALID_USERNAME,
+ INVALID_GROUPNAME;
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
import java.util.Set;
+
/**
* Represents a set of users.
* Typical implementations would be an implementation based on a static configuration file or
* @author Erik Brakkee
*/
public interface UserSet {
-
/**
- * Creates a user.
- * @param aUsername User name.
- * @param aPassword Password.
+ * Creates a user.
+ *
+ * @param aUsername User name.
+ * @param aPassword Password.
* @param aGroup Group.
- * @return New user.
- * @throws UserMgtException In case the user cannot be created.
- */
- User createUser(String aUsername, String aPassword, Group aGroup) throws UserMgtException;
-
+ *
+ * @return New user.
+ *
+ * @throws UserMgtException In case the user cannot be created.
+ */
+ User createUser(String aUsername, String aPassword, Group aGroup)
+ throws UserMgtException;
+
/**
- * Must be called whenever a user object has been modified to notify the
- * user set.
- * @param aUser Modified user.
+ * Must be called whenever a user object has been modified to
+ * notify the user set.
+ *
+ * @param aUser Modified user.
*/
- void userModified(User aUser);
-
+ void userModified(User aUser);
+
/**
- * Finds user.
- * @param aName Username.
- * @return User or null if not found.
+ * Finds user.
+ *
+ * @param aName Username.
+ *
+ * @return User or null if not found.
*/
User find(String aName);
-
+
/**
- * Checks if a user exists.
- * @param aUser User.
- * @return True iff the user exists.
+ * Checks if a user exists.
+ *
+ * @param aUser User.
+ *
+ * @return True iff the user exists.
*/
- boolean contains(User aUser);
-
+ boolean contains(User aUser);
+
/**
- * Adds a user. If the user already exists, the user details are updated with that
- * of the specified user object.
- * @param aUser User to add.
+ * Adds a user. If the user already exists, the user details are
+ * updated with that of the specified user object.
+ *
+ * @param aUser User to add.
+ *
+ * @return DOCUMENT ME!
*/
boolean add(User aUser);
-
+
/**
- * Removes a user. If the user does not exist, nothing happens.
+ * Removes a user. If the user does not exist, nothing happens.
+ *
* @param aUser
+ *
+ * @return DOCUMENT ME!
*/
boolean remove(User aUser);
-
+
/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
* Lists the current users.
* @return Users.
*/
- Set<User> list();
-
+ Set<User> list();
+
/**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
* Lists the users belonging to a particular group.
* @param aGroup Group.
* @return Groups.
Set<User> list(Group aGroup);
/**
- *
- * @return The number of users.
+ * DOCUMENT ME!
+ *
+ * @return The number of users.
*/
- int size();
+ int size();
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.usermgt.hibernate;
-import java.io.IOException;
-
-import javax.sql.DataSource;
-
import org.springframework.orm.hibernate3.HibernateTemplate;
+
import org.springframework.transaction.PlatformTransactionManager;
+
import org.wamblee.cache.EhCache;
+
import org.wamblee.security.authorization.AuthorizationService;
import org.wamblee.security.authorization.hibernate.AuthorizationMappingFiles;
+
import org.wamblee.system.adapters.DefaultContainer;
import org.wamblee.system.adapters.ObjectConfiguration;
import org.wamblee.system.components.ORMappingConfig;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.Scope;
import org.wamblee.system.spring.component.HibernateComponent;
+
import org.wamblee.usermgt.UserAccessor;
import org.wamblee.usermgt.UserAdministration;
import org.wamblee.usermgt.UserGroupRepositoryComponent;
+import java.io.IOException;
+
+import javax.sql.DataSource;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class AuthorizationComponent extends DefaultContainer {
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface("transactionManager",
+ PlatformTransactionManager.class);
+
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface("hibernateTemplate",
+ HibernateTemplate.class);
- private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface(
- "transactionManager", PlatformTransactionManager.class);
- private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface(
- "hibernateTemplate", HibernateTemplate.class);
- private ProvidedInterface AUTHORIZATION_SERVICE = new DefaultProvidedInterface(
- "authorizationService", AuthorizationService.class);
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface AUTHORIZATION_SERVICE = new DefaultProvidedInterface("authorizationService",
+ AuthorizationService.class);
+/**
+ * Creates a new AuthorizationComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aExposeInternals DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public AuthorizationComponent(String aName, boolean aExposeInternals)
- throws IOException {
+ throws IOException {
super(aName);
-
+
ObjectConfiguration authConfig = new ObjectConfiguration(AuthorizationMappingFiles.class);
authConfig.getSetterConfig().initAllSetters();
- addComponent("mappingFiles", new AuthorizationMappingFiles(), authConfig);
+ addComponent("mappingFiles", new AuthorizationMappingFiles(), authConfig);
Component<?> hibernate = new HibernateComponent("hibernate");
addComponent(hibernate);
- Component<?> authorization = new AuthorizationLightComponent("authorization");
+ Component<?> authorization = new AuthorizationLightComponent(
+ "authorization");
addComponent(authorization);
- addRequiredInterface(new DefaultRequiredInterface("datasource", DataSource.class));
+ addRequiredInterface(new DefaultRequiredInterface("datasource",
+ DataSource.class));
addRequiredInterface(new DefaultRequiredInterface("userAccessor",
UserAccessor.class));
- addRequiredInterface(new DefaultRequiredInterface("ormconfig", ORMappingConfig.class));
+ addRequiredInterface(new DefaultRequiredInterface("ormconfig",
+ ORMappingConfig.class));
if (aExposeInternals) {
addProvidedInterface(TRANSACTION_MGR);
addProvidedInterface(HIBERNATE_TEMPLATE);
}
+
addProvidedInterface(AUTHORIZATION_SERVICE);
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.usermgt.hibernate;
-import java.util.HashMap;
-import java.util.Map;
-
import org.springframework.orm.hibernate3.HibernateTemplate;
+
import org.wamblee.security.authorization.AuthorizationService;
+
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.spring.SpringComponent;
+
import org.wamblee.usermgt.GroupSet;
import org.wamblee.usermgt.UserAccessor;
import org.wamblee.usermgt.UserAdministration;
import org.wamblee.usermgt.UserSet;
+import java.util.HashMap;
+import java.util.Map;
+
+
/**
- * Light version of the user administration component that requires external
- * datasource, and userset and group set components, as well as an external
- * hibernate session factory.
- *
+ * Light version of the user administration component that requires
+ * external datasource, and userset and group set components, as well as an
+ * external hibernate session factory.
+ *
* @author Erik Brakkee
- *
*/
public class AuthorizationLightComponent extends SpringComponent {
-
+/**
+ * Creates a new AuthorizationLightComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ */
public AuthorizationLightComponent(String aName) {
- super(
- aName,
- new String[] { "spring/org.wamblee.security.authorization.xml" },
- createProvided(), createRequired());
+ super(aName,
+ new String[] { "spring/org.wamblee.security.authorization.xml" },
+ createProvided(), createRequired());
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private static Map<RequiredInterface, String> createRequired() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("userArccessor",
UserAccessor.class), UserAccessor.class.getName());
required.put(new DefaultRequiredInterface("hibernateTemplate",
HibernateTemplate.class), HibernateTemplate.class.getName());
+
return required;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private static Map<String, ProvidedInterface> createProvided() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
provided.put(AuthorizationService.class.getName(),
- new DefaultProvidedInterface(AuthorizationService.class
- .getName(), AuthorizationService.class));
+ new DefaultProvidedInterface(AuthorizationService.class.getName(),
+ AuthorizationService.class));
+
return provided;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt.hibernate;
+import org.wamblee.persistence.hibernate.HibernateSupport;
+
+import org.wamblee.usermgt.Group;
+import org.wamblee.usermgt.GroupSet;
+
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
-import org.wamblee.persistence.hibernate.HibernateSupport;
-import org.wamblee.usermgt.Group;
-import org.wamblee.usermgt.GroupSet;
/**
- * Set of groups backed by the database.
+ * Set of groups backed by the database.
*
* @author Erik Brakkee
*/
public class HibernateGroupSet extends HibernateSupport implements GroupSet {
-
-
+ /**
+ * DOCUMENT ME!
+ */
private static final String QUERY_FIND_BY_NAME = "findGroupByName";
-
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String PARAM_NAME = "name";
-
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String QUERY_COUNT_GROUPS = "countGroups";
-
+
+/**
+ * Creates a new HibernateGroupSet object.
+ */
public HibernateGroupSet() {
// Empty
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ */
public void groupModified(Group aGroup) {
- assert aGroup.getPrimaryKey() != null;
- super.merge(aGroup);
+ assert aGroup.getPrimaryKey() != null;
+ super.merge(aGroup);
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#find(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws RuntimeException DOCUMENT ME!
+ */
public Group find(String aName) {
- List list = getHibernateTemplate().findByNamedQueryAndNamedParam(QUERY_FIND_BY_NAME, PARAM_NAME, aName);
- if ( list.size() > 1 ) {
- throw new RuntimeException("More than one group with the same name '" + aName + "'");
+ List list = getHibernateTemplate()
+ .findByNamedQueryAndNamedParam(QUERY_FIND_BY_NAME, PARAM_NAME, aName);
+
+ if (list.size() > 1) {
+ throw new RuntimeException(
+ "More than one group with the same name '" + aName + "'");
}
- if ( list.size() == 0 ) {
- return null;
+
+ if (list.size() == 0) {
+ return null;
}
- return new Group((Group)list.get(0));
+
+ return new Group((Group) list.get(0));
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean contains(Group aGroup) {
- return find(aGroup.getName()) != null;
+ return find(aGroup.getName()) != null;
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean add(Group aGroup) {
- assert aGroup.getPrimaryKey() == null;
- if ( contains(aGroup) ) {
- return false;
+ assert aGroup.getPrimaryKey() == null;
+
+ if (contains(aGroup)) {
+ return false;
}
+
super.merge(aGroup);
- return true;
+
+ return true;
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean remove(Group aGroup) {
- assert aGroup.getPrimaryKey() != null;
- if ( !contains(aGroup)) {
- return false;
+ assert aGroup.getPrimaryKey() != null;
+
+ if (!contains(aGroup)) {
+ return false;
}
- Group group = (Group) getHibernateTemplate().merge(aGroup);
+
+ Group group = (Group) getHibernateTemplate().merge(aGroup);
getHibernateTemplate().delete(group);
- aGroup.setPrimaryKey(null);
+ aGroup.setPrimaryKey(null);
aGroup.setPersistedVersion(-1);
- return true;
+
+ return true;
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#list()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<Group> list() {
- Set<Group> groups = new TreeSet<Group>();
- List<Group> list = getHibernateTemplate().loadAll(Group.class);
- for (Group group: list) {
+ Set<Group> groups = new TreeSet<Group>();
+ List<Group> list = getHibernateTemplate().loadAll(Group.class);
+
+ for (Group group : list) {
groups.add(new Group(group));
}
- return groups;
+
+ return groups;
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.GroupSet#size()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int size() {
- Long result = (Long) getHibernateTemplate().findByNamedQuery(QUERY_COUNT_GROUPS).get(0);
- return result.intValue();
+ Long result = (Long) getHibernateTemplate()
+ .findByNamedQuery(QUERY_COUNT_GROUPS).get(0);
+
+ return result.intValue();
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt.hibernate;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-
import org.hibernate.SessionFactory;
+
import org.springframework.orm.hibernate3.HibernateTemplate;
+
import org.wamblee.cache.Cache;
+
import org.wamblee.persistence.hibernate.HibernateSupport;
+
import org.wamblee.security.encryption.MessageDigester;
+
import org.wamblee.usermgt.AbstractUserSet;
import org.wamblee.usermgt.Group;
import org.wamblee.usermgt.NameValidator;
import org.wamblee.usermgt.User;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+
/**
* User set backed by the database.
*
* @author Erik Brakkee
*/
public class HibernateUserSet extends AbstractUserSet {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final String QUERY_FIND_BY_NAME = "findUserByName";
+ /**
+ * DOCUMENT ME!
+ */
private static final String QUERY_FIND_BY_GROUP_NAME = "findUserByGroupName";
+ /**
+ * DOCUMENT ME!
+ */
private static final String PARAM_NAME = "name";
-
- private static final String QUERY_COUNT_USERS = "countUsers";
/**
- * Cache of users. Every user in the cache has its password validator and encoder set.
+ * DOCUMENT ME!
*/
- private Cache<String, User> cache;
-
- /**
- * Spring hibernate support.
+ private static final String QUERY_COUNT_USERS = "countUsers";
+
+ /**
+ * Cache of users. Every user in the cache has its password
+ * validator and encoder set.
*/
- private HibernateSupport hibernateSupport;
+ private Cache<String, User> cache;
/**
+ * Spring hibernate support.
+ */
+ private HibernateSupport hibernateSupport;
+
+/**
* Constructs a user set backed by the database.
* @param aCache User cache to use.
*/
- public HibernateUserSet(Cache<String,User> aCache,
- NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) {
+ public HibernateUserSet(Cache<String, User> aCache,
+ NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) {
super(aPasswordValidator, aPasswordEncoder);
- cache = aCache;
- hibernateSupport = new HibernateSupport();
+ cache = aCache;
+ hibernateSupport = new HibernateSupport();
}
-
+
/**
- * Sets the session factory.
- * @param aFactory Session factory.
+ * Sets the session factory.
+ *
+ * @param aFactory Session factory.
*/
- public void setSessionFactory(SessionFactory aFactory) {
+ public void setSessionFactory(SessionFactory aFactory) {
hibernateSupport.setSessionFactory(aFactory);
}
-
+
/**
- * Gets the hibernate template.
- * @return Hibernate template.
+ * Gets the hibernate template.
+ *
+ * @return Hibernate template.
*/
- private HibernateTemplate getHibernateTemplate() {
+ private HibernateTemplate getHibernateTemplate() {
return hibernateSupport.getHibernateTemplate();
}
-
+
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ */
public void userModified(User aUser) {
assert aUser.getPrimaryKey() != null;
hibernateSupport.merge(aUser);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#find(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws RuntimeException DOCUMENT ME!
+ */
public User find(String aName) {
User user = cache.get(aName);
+
if (user != null) {
return user;
}
- List result = getHibernateTemplate().findByNamedQueryAndNamedParam(
- QUERY_FIND_BY_NAME, PARAM_NAME, aName);
+
+ List result = getHibernateTemplate()
+ .findByNamedQueryAndNamedParam(QUERY_FIND_BY_NAME, PARAM_NAME, aName);
+
if (result.size() > 1) {
throw new RuntimeException(
- "Implementation problem, more than one user with the same name!");
+ "Implementation problem, more than one user with the same name!");
}
+
if (result.size() == 0) {
return null;
}
+
user = (User) result.get(0);
setPasswordInfo(user);
cache.put(aName, user);
+
return new User(user);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean contains(User aUser) {
return find(aUser.getName()) != null;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean add(User aUser) {
assert aUser.getPrimaryKey() == null;
+
if (contains(aUser)) {
return false;
}
+
getHibernateTemplate().saveOrUpdate(aUser);
setPasswordInfo(aUser);
cache.put(aUser.getName(), aUser);
+
return true;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean remove(User aUser) {
assert aUser.getPrimaryKey() != null;
+
if (!contains(aUser)) {
return false;
}
+
User user = (User) getHibernateTemplate().merge(aUser);
getHibernateTemplate().delete(user);
aUser.setPersistedVersion(-1);
aUser.setPrimaryKey(null);
cache.remove(aUser.getName());
+
return true;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#list()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<User> list() {
- Set<User> users = new TreeSet<User>();
- List<User> list = getHibernateTemplate().loadAll(User.class);
+ Set<User> users = new TreeSet<User>();
+ List<User> list = getHibernateTemplate().loadAll(User.class);
+
for (User user : list) {
setPasswordInfo(user);
users.add(new User(user));
}
+
return users;
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserSet#list(org.wamblee.usermgt.Group)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Set<User> list(Group aGroup) {
- Set<User> users = new TreeSet<User>();
- List<User> list = getHibernateTemplate().findByNamedQueryAndNamedParam(
- QUERY_FIND_BY_GROUP_NAME, PARAM_NAME, aGroup.getName());
+ Set<User> users = new TreeSet<User>();
+ List<User> list = getHibernateTemplate()
+ .findByNamedQueryAndNamedParam(QUERY_FIND_BY_GROUP_NAME,
+ PARAM_NAME, aGroup.getName());
+
for (User user : list) {
setPasswordInfo(user);
users.add(new User(user));
}
+
return users;
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.UserSet#size()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int size() {
- Long result = (Long)getHibernateTemplate().findByNamedQuery(QUERY_COUNT_USERS).get(0);
- return result.intValue();
+ Long result = (Long) getHibernateTemplate()
+ .findByNamedQuery(QUERY_COUNT_USERS).get(0);
+
+ return result.intValue();
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.usermgt.hibernate;
-import java.io.IOException;
-
-import javax.sql.DataSource;
-
import org.springframework.orm.hibernate3.HibernateTemplate;
+
import org.springframework.transaction.PlatformTransactionManager;
+
import org.wamblee.cache.EhCache;
+
import org.wamblee.system.adapters.DefaultContainer;
import org.wamblee.system.adapters.ObjectConfiguration;
import org.wamblee.system.components.ORMappingConfig;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.Scope;
import org.wamblee.system.spring.component.HibernateComponent;
+
import org.wamblee.usermgt.UserAdministration;
import org.wamblee.usermgt.UserGroupRepositoryComponent;
+import java.io.IOException;
+
+import javax.sql.DataSource;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class UserAdministrationComponent extends DefaultContainer {
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface("transactionManager",
+ PlatformTransactionManager.class);
- private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface(
- "transactionManager", PlatformTransactionManager.class);
- private ProvidedInterface USER_CACHE = new DefaultProvidedInterface(
- "userCache", EhCache.class);
- private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface(
- "hibernateTemplate", HibernateTemplate.class);
- private ProvidedInterface USER_MGT = new DefaultProvidedInterface(
- "usermgt", UserAdministration.class);
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface USER_CACHE = new DefaultProvidedInterface("userCache",
+ EhCache.class);
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface("hibernateTemplate",
+ HibernateTemplate.class);
+
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface USER_MGT = new DefaultProvidedInterface("usermgt",
+ UserAdministration.class);
+
+/**
+ * Creates a new UserAdministrationComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aExposeInternals DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public UserAdministrationComponent(String aName, boolean aExposeInternals)
- throws IOException {
+ throws IOException {
super(aName);
-
- ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class);
+
+ ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class);
mappingFilesConfig.getSetterConfig().initAllSetters();
- addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig);
+ addComponent("mappingFiles", new UsermgtHibernateMappingFiles(),
+ mappingFilesConfig);
Component<?> hibernate = new HibernateComponent("hibernate");
addComponent(hibernate);
- Component<?> repository = new UserGroupRepositoryComponent("usersgroups");
+ Component<?> repository = new UserGroupRepositoryComponent(
+ "usersgroups");
addComponent(repository);
- Component<?> usermgt = new UserAdministrationLightComponent("usermgtlight");
+ Component<?> usermgt = new UserAdministrationLightComponent(
+ "usermgtlight");
addComponent(usermgt);
addRequiredInterface(new DefaultRequiredInterface("datasource",
DataSource.class));
- addRequiredInterface(new DefaultRequiredInterface("ormconfig", ORMappingConfig.class));
+ addRequiredInterface(new DefaultRequiredInterface("ormconfig",
+ ORMappingConfig.class));
if (aExposeInternals) {
addProvidedInterface(TRANSACTION_MGR);
addProvidedInterface(USER_CACHE);
addProvidedInterface(HIBERNATE_TEMPLATE);
}
+
addProvidedInterface(USER_MGT);
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.usermgt.hibernate;
-import java.util.HashMap;
-import java.util.Map;
-
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.spring.SpringComponent;
+
import org.wamblee.usermgt.GroupSet;
import org.wamblee.usermgt.UserAdministration;
import org.wamblee.usermgt.UserSet;
+import java.util.HashMap;
+import java.util.Map;
+
+
/**
- * Light version of the user administration component that requires external
- * datasource, and userset and group set components, as well as an external
- * hibernate session factory.
- * @author Erik Brakkee
+ * Light version of the user administration component that requires
+ * external datasource, and userset and group set components, as well as an
+ * external hibernate session factory.
*
+ * @author Erik Brakkee
*/
public class UserAdministrationLightComponent extends SpringComponent {
-
- public UserAdministrationLightComponent(String aName) {
- super(aName, new String[] { "spring/org.wamblee.security.usermgt.xml" },
- createProvided(), createRequired() );
+/**
+ * Creates a new UserAdministrationLightComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ */
+ public UserAdministrationLightComponent(String aName) {
+ super(aName,
+ new String[] { "spring/org.wamblee.security.usermgt.xml" },
+ createProvided(), createRequired());
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private static Map<RequiredInterface, String> createRequired() {
- Map<RequiredInterface, String> required = new HashMap<RequiredInterface,String>();
- required.put(new DefaultRequiredInterface("userSet", UserSet.class), UserSet.class.getName());
- required.put(new DefaultRequiredInterface("groupSet", GroupSet.class), GroupSet.class.getName());
- return required;
+ Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
+ required.put(new DefaultRequiredInterface("userSet", UserSet.class),
+ UserSet.class.getName());
+ required.put(new DefaultRequiredInterface("groupSet", GroupSet.class),
+ GroupSet.class.getName());
+
+ return required;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private static Map<String, ProvidedInterface> createProvided() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put(UserAdministration.class.getName(), new DefaultProvidedInterface("org.wamblee.usermgt.UserAdministration",
+ provided.put(UserAdministration.class.getName(),
+ new DefaultProvidedInterface(
+ "org.wamblee.usermgt.UserAdministration",
UserAdministration.class));
+
return provided;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt.hibernate;
+import org.wamblee.persistence.hibernate.HibernateMappingFiles;
+
import java.util.Collections;
-import org.wamblee.persistence.hibernate.HibernateMappingFiles;
/**
- * Hibernate mapping files for user management.
+ * Hibernate mapping files for user management.
*
* @author Erik Brakkee
*/
public class UsermgtHibernateMappingFiles extends HibernateMappingFiles {
-
- public UsermgtHibernateMappingFiles() {
- super(new String[] {
- "hbm/Group.hbm.xml", "hbm/User.hbm.xml"
- });
+/**
+ * Creates a new UsermgtHibernateMappingFiles object.
+ */
+ public UsermgtHibernateMappingFiles() {
+ super(new String[] { "hbm/Group.hbm.xml", "hbm/User.hbm.xml" });
}
-
- public UsermgtHibernateMappingFiles(String[] aFiles) {
- this();
+
+/**
+ * Creates a new UsermgtHibernateMappingFiles object.
+ *
+ * @param aFiles DOCUMENT ME!
+ */
+ public UsermgtHibernateMappingFiles(String[] aFiles) {
+ this();
Collections.addAll(this, aFiles);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
+import junit.framework.TestCase;
import static org.wamblee.security.authorization.AuthorizationResult.DENIED;
import static org.wamblee.security.authorization.AuthorizationResult.GRANTED;
-import junit.framework.TestCase;
import org.wamblee.usermgt.UserAccessor;
+
/**
- * Tests the authorization service.
+ * Tests the authorization service.
*
* @author Erik Brakkee
*/
public class AuthorizationServiceTest extends TestCase {
-
- private AuthorizationRule rule1;
- private AuthorizationRule rule2;
- private AuthorizationRule rule3;
- private AuthorizationService service;
-
- protected AuthorizationService getService() {
- return service;
- }
-
+ /**
+ * DOCUMENT ME!
+ */
+ private AuthorizationRule rule1;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private AuthorizationRule rule2;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private AuthorizationRule rule3;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private AuthorizationService service;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected AuthorizationService getService() {
+ return service;
+ }
+
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
super.setUp();
-
- rule1 = createRule(GRANTED, "users", "/oni/", AllOperation.class);
- rule2 = createRule(DENIED, "users", "/abc/", ReadOperation.class);
- rule3 = createRule(GRANTED, "users", "/abc/", AllOperation.class);
-
- service = createService();
- service.appendRule(rule1);
+
+ rule1 = createRule(GRANTED, "users", "/oni/", AllOperation.class);
+ rule2 = createRule(DENIED, "users", "/abc/", ReadOperation.class);
+ rule3 = createRule(GRANTED, "users", "/abc/", AllOperation.class);
+
+ service = createService();
+ service.appendRule(rule1);
service.appendRule(rule2);
service.appendRule(rule3);
}
-
- protected void resetTestRules() {
- ((TestAuthorizationRule)rule1).reset();
- ((TestAuthorizationRule)rule2).reset();
- ((TestAuthorizationRule)rule3).reset();
+
+ /**
+ * DOCUMENT ME!
+ */
+ protected void resetTestRules() {
+ ((TestAuthorizationRule) rule1).reset();
+ ((TestAuthorizationRule) rule2).reset();
+ ((TestAuthorizationRule) rule3).reset();
}
-
- protected UserAccessor createUserAccessor() {
- return new TestUserAccessor();
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected UserAccessor createUserAccessor() {
+ return new TestUserAccessor();
}
/**
- * Creates an authorization service with some rules for testing. .
- * @return Authorization service.
+ * Creates an authorization service with some rules for testing. .
+ *
+ * @return Authorization service.
*/
protected AuthorizationService createService() {
- DefaultAuthorizationService service = new DefaultAuthorizationService() ;
+ DefaultAuthorizationService service = new DefaultAuthorizationService();
service.setUserAccessor(createUserAccessor());
+
return service;
}
-
- protected AuthorizationRule createRule(AuthorizationResult aResult, String aGroup, String aPath, Class<? extends Operation> aOperation) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResult DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ * @param aPath DOCUMENT ME!
+ * @param aOperation DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected AuthorizationRule createRule(AuthorizationResult aResult,
+ String aGroup, String aPath, Class<?extends Operation> aOperation) {
return new TestAuthorizationRule(aResult, aGroup, aPath, aOperation);
}
-
- protected void checkMatchCount(int aCount, AuthorizationRule aRule) {
- assertEquals( aCount, ((TestAuthorizationRule)aRule).getMatchCount());
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aCount DOCUMENT ME!
+ * @param aRule DOCUMENT ME!
+ */
+ protected void checkMatchCount(int aCount, AuthorizationRule aRule) {
+ assertEquals(aCount, ((TestAuthorizationRule) aRule).getMatchCount());
}
-
- protected Object createResource(String aPath) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPath DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected Object createResource(String aPath) {
return new TestResource(aPath);
}
-
- protected void checkRuleCount(int aCount) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aCount DOCUMENT ME!
+ */
+ protected void checkRuleCount(int aCount) {
// Empty
}
-
+
/**
- * Several checks to verify the outcome of matching against the first rule.
- *
+ * Several checks to verify the outcome of matching against the
+ * first rule.
*/
- public void testFirstRuleGrants() {
- assertTrue( service.isAllowed(createResource("/oni/xyz.jpg"), new ReadOperation()));
+ public void testFirstRuleGrants() {
+ assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"),
+ new ReadOperation()));
checkMatchCount(1, rule1);
- assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new WriteOperation()));
+ assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"),
+ new WriteOperation()));
checkMatchCount(2, rule1);
- assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new DeleteOperation()));
+ assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"),
+ new DeleteOperation()));
checkMatchCount(3, rule1);
- assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new CreateOperation()));
+ assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"),
+ new CreateOperation()));
checkMatchCount(4, rule1);
checkMatchCount(0, rule2);
checkMatchCount(0, rule3);
}
-
+
/**
- * Verify that a match with the second rule leads to a denial of authorization.
- *
+ * Verify that a match with the second rule leads to a denial of
+ * authorization.
*/
public void testSecondRuleDenies() {
- assertFalse(service.isAllowed(createResource("/abc/xyz.jpg"), new ReadOperation()));
+ assertFalse(service.isAllowed(createResource("/abc/xyz.jpg"),
+ new ReadOperation()));
checkMatchCount(0, rule1);
checkMatchCount(1, rule2);
checkMatchCount(0, rule3);
}
-
+
/**
- * Verifies that the third rule is used when appropriate and that it grants access.
- *
+ * Verifies that the third rule is used when appropriate and that
+ * it grants access.
*/
- public void testThirdRuleGrants() {
- assertTrue(service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
- checkMatchCount(0, rule1);
+ public void testThirdRuleGrants() {
+ assertTrue(service.isAllowed(createResource("/abc/xyz.jpg"),
+ new WriteOperation()));
+ checkMatchCount(0, rule1);
checkMatchCount(0, rule2);
- checkMatchCount(1, rule3);
+ checkMatchCount(1, rule3);
}
-
+
/**
- * Removes a rule and checks it is removed.
- *
+ * Removes a rule and checks it is removed.
*/
- public void testRemoveRule() {
+ public void testRemoveRule() {
checkRuleCount(3);
- assertTrue(service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
- service.removeRule(2);
- assertFalse(service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
+ assertTrue(service.isAllowed(createResource("/abc/xyz.jpg"),
+ new WriteOperation()));
+ service.removeRule(2);
+ assertFalse(service.isAllowed(createResource("/abc/xyz.jpg"),
+ new WriteOperation()));
checkRuleCount(2);
}
-
+
/**
- * Inserts a rule and checks it is inserted.
- *
+ * Inserts a rule and checks it is inserted.
*/
public void testInsertRule() {
checkRuleCount(3);
- assertFalse(service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation()));
- service.appendRule(createRule(GRANTED, "users", "/janse/", WriteOperation.class));
- assertTrue(service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation()));
+ assertFalse(service.isAllowed(createResource("/janse/xyz.jpg"),
+ new WriteOperation()));
+ service.appendRule(createRule(GRANTED, "users", "/janse/",
+ WriteOperation.class));
+ assertTrue(service.isAllowed(createResource("/janse/xyz.jpg"),
+ new WriteOperation()));
checkRuleCount(4);
-
}
-
+
/**
- * Gets the rules. Verifies that all rules are obtained.
- *
+ * Gets the rules. Verifies that all rules are obtained.
*/
- public void testGetRules() {
+ public void testGetRules() {
AuthorizationRule[] rules = service.getRules();
- assertEquals(3, rules.length);
+ assertEquals(3, rules.length);
}
-
+
/**
- * Verifies that when no rules match, access is denied.
- *
+ * Verifies that when no rules match, access is denied.
*/
- public void testNoRulesSupportResource() {
- assertFalse(service.isAllowed(createResource("/xyxyxyxy"), new ReadOperation()));
- checkMatchCount(0, rule1);
+ public void testNoRulesSupportResource() {
+ assertFalse(service.isAllowed(createResource("/xyxyxyxy"),
+ new ReadOperation()));
+ checkMatchCount(0, rule1);
checkMatchCount(0, rule2);
- checkMatchCount(0, rule3);
+ checkMatchCount(0, rule3);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import junit.framework.TestCase;
+
/**
- * Test of the operation registry.
+ * Test of the operation registry.
*
* @author Erik Brakkee
*/
public class DefaultOperationRegistryTest extends TestCase {
-
- private OperationRegistry registry;
-
+ /**
+ * DOCUMENT ME!
+ */
+ private OperationRegistry registry;
+
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
-
registry = new DefaultOperationRegistry(new Operation[] {
- new AllOperation(),
- new ReadOperation(),
- new WriteOperation(),
- new DeleteOperation(),
- new CreateOperation()
- });
+ new AllOperation(), new ReadOperation(),
+ new WriteOperation(), new DeleteOperation(),
+ new CreateOperation()
+ });
}
-
+
/**
- * Tests encoding and decoding of no operations.
- *
+ * Tests encoding and decoding of no operations.
*/
- public void testEncodeDecodeNooperations() {
+ public void testEncodeDecodeNooperations() {
assertEquals("", registry.encode(new Operation[0]));
assertEquals(0, registry.decode(Object.class, "").length);
}
-
+
/**
- * Verifies that encoding of operations into a string works.
- *
+ * Verifies that encoding of operations into a string works.
*/
- public void testEncode() {
- assertEquals("read,write", registry.encode(new Operation[] { new ReadOperation(), new WriteOperation() }));
+ public void testEncode() {
+ assertEquals("read,write",
+ registry.encode(
+ new Operation[] { new ReadOperation(), new WriteOperation() }));
}
-
+
/**
- * Verifies that decoding of operation from a string works.
- *
+ * Verifies that decoding of operation from a string works.
*/
- public void testDecode() {
+ public void testDecode() {
Operation[] operations = registry.decode(Object.class, "read,write");
- assertTrue( operations[0] instanceof ReadOperation);
- assertTrue( operations[1] instanceof WriteOperation);
+ assertTrue(operations[0] instanceof ReadOperation);
+ assertTrue(operations[1] instanceof WriteOperation);
}
-
+
/**
- * Verifies that an IllegalArgumentException occurs when attempting to decode
- * an operation that is not known.
- *
+ * Verifies that an IllegalArgumentException occurs when attempting
+ * to decode an operation that is not known.
*/
- public void testDecodeUnknownOperation() {
- try {
- registry.decode(Object.class, "bla");
- fail();
- } catch (IllegalArgumentException e) {
+ public void testDecodeUnknownOperation() {
+ try {
+ registry.decode(Object.class, "bla");
+ fail();
+ } catch (IllegalArgumentException e) {
// ok
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import junit.framework.TestCase;
+
/**
- * Test for regular expression matching.
+ * Test for regular expression matching.
*
* @author Erik Brakkee
*/
public class RegexpPathConditionTest extends TestCase {
-
/**
- * Various tests.
- *
+ * Various tests.
*/
- public void testMatch() {
- PathCondition cond = new RegexpPathCondition("abc");
- assertTrue(cond.matches("abc"));
- assertFalse(cond.matches("xabcx"));
- cond = new RegexpPathCondition("/[a-z]*/.*");
- assertTrue(cond.matches("/hallo/xyz"));
+ public void testMatch() {
+ PathCondition cond = new RegexpPathCondition("abc");
+ assertTrue(cond.matches("abc"));
+ assertFalse(cond.matches("xabcx"));
+ cond = new RegexpPathCondition("/[a-z]*/.*");
+ assertTrue(cond.matches("/hallo/xyz"));
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import junit.framework.TestCase;
+
/**
- * Tests for StartsWithPathCondition.
+ * Tests for StartsWithPathCondition.
*
* @author Erik Brakkee
*/
public class StartsWithPathConditionTest extends TestCase {
-
/**
- * Various tests.
+ * Various tests.
*/
public void testMatches() {
PathCondition cond = new StartsWithPathCondition("/hallo");
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
import static org.wamblee.security.authorization.AuthorizationResult.DENIED;
import org.wamblee.usermgt.User;
+
/**
- * Test authorization rule that also counts the number of times the rule matches.
+ * Test authorization rule that also counts the number of times the rule
+ * matches.
*
* @author Erik Brakkee
*/
public class TestAuthorizationRule extends UrlAuthorizationRule {
-
/**
- * Counts the number of matches.
+ * Counts the number of matches.
*/
- private int matches = 0;
+ private int matches = 0;
- public TestAuthorizationRule( AuthorizationResult aResult, String aGroup,
- String aPath, Class<? extends Operation> aOperation) {
- super(aResult, new GroupUserCondition(aGroup),
- new StartsWithPathCondition(aPath), TestResource.class, new IsaOperationCondition(aOperation));
+/**
+ * Creates a new TestAuthorizationRule object.
+ *
+ * @param aResult DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ * @param aPath DOCUMENT ME!
+ * @param aOperation DOCUMENT ME!
+ */
+ public TestAuthorizationRule(AuthorizationResult aResult, String aGroup,
+ String aPath, Class<?extends Operation> aOperation) {
+ super(aResult, new GroupUserCondition(aGroup),
+ new StartsWithPathCondition(aPath), TestResource.class,
+ new IsaOperationCondition(aOperation));
}
-
- protected TestAuthorizationRule() {
+
+/**
+ * Creates a new TestAuthorizationRule object.
+ */
+ protected TestAuthorizationRule() {
super();
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.UrlAuthorizationRule#getPath(java.lang.Object)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResource DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected String getResourcePath(Object aResource) {
- return ((TestResource)aResource).getPath();
+ return ((TestResource) aResource).getPath();
}
-
+
/* (non-Javadoc)
* @see org.wamblee.security.authorization.UrlAuthorizationRule#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation, org.wamblee.usermgt.UserAccessor)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResource DOCUMENT ME!
+ * @param anOperation DOCUMENT ME!
+ * @param aUser DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
- public AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser) {
-
- AuthorizationResult result = super.isAllowed(aResource, anOperation, aUser);
- if ( result.equals(GRANTED) || result.equals(DENIED)) {
- matches++;
+ public AuthorizationResult isAllowed(Object aResource,
+ Operation anOperation, User aUser) {
+ AuthorizationResult result = super.isAllowed(aResource, anOperation,
+ aUser);
+
+ if (result.equals(GRANTED) || result.equals(DENIED)) {
+ matches++;
}
- return result;
+
+ return result;
}
-
- public int getMatchCount() {
- return matches;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public int getMatchCount() {
+ return matches;
}
-
- public void reset() {
- matches = 0;
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void reset() {
+ matches = 0;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
/**
- * A test resource for authorization.
+ * A test resource for authorization.
*
* @author Erik Brakkee
*/
public class TestResource {
+ /**
+ * DOCUMENT ME!
+ */
+ private String path;
- private String path;
-
- public TestResource(String aPath) {
- path = aPath;
+/**
+ * Creates a new TestResource object.
+ *
+ * @param aPath DOCUMENT ME!
+ */
+ public TestResource(String aPath) {
+ path = aPath;
}
-
- public String getPath() {
- return path;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getPath() {
+ return path;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.security.authorization;
import junit.framework.TestCase;
import org.wamblee.security.encryption.Md5HexMessageDigester;
+
import org.wamblee.usermgt.Group;
import org.wamblee.usermgt.InMemoryGroupSet;
import org.wamblee.usermgt.InMemoryUserSet;
import org.wamblee.usermgt.UserMgtException;
import org.wamblee.usermgt.UserMgtException.Reason;
+
/**
- * User access that always returns a user that belongs to
- * a fixed group.
+ * User access that always returns a user that belongs to a fixed group.
*
* @author Erik Brakkee
*/
public class TestUserAccessor implements UserAccessor {
-
- private static final String USER = "erik";
+ /**
+ * DOCUMENT ME!
+ */
+ private static final String USER = "erik";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String PASSWORD = "abc123";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String GROUP = "users";
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws RuntimeException DOCUMENT ME!
+ */
public User getCurrentUser() {
- UserAdministration admin = new UserAdministrationImpl(
- new InMemoryUserSet( new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"),
- new Md5HexMessageDigester()), new InMemoryGroupSet(),
- new RegexpNameValidator(RegexpNameValidator.ID_PATTERN, Reason.INVALID_USERNAME, "Invalid user"),
- new RegexpNameValidator(RegexpNameValidator.ID_PATTERN, Reason.INVALID_GROUPNAME, "Invalid group")
- );
+ UserAdministration admin = new UserAdministrationImpl(new InMemoryUserSet(
+ new RegexpNameValidator(
+ RegexpNameValidator.PASSWORD_PATTERN,
+ Reason.INVALID_PASSWORD,
+ "Password must contain at least 6 characters"),
+ new Md5HexMessageDigester()), new InMemoryGroupSet(),
+ new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
+ Reason.INVALID_USERNAME, "Invalid user"),
+ new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
+ Reason.INVALID_GROUPNAME, "Invalid group"));
+
try {
Group group = admin.createGroup(GROUP);
+
return admin.createUser(USER, PASSWORD, group);
} catch (UserMgtException e) {
TestCase.fail(e.getMessage());
throw new RuntimeException(e);
}
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.authorization;
+import junit.framework.TestCase;
import static org.wamblee.security.authorization.AuthorizationResult.GRANTED;
import static org.wamblee.security.authorization.AuthorizationResult.UNDECIDED;
import static org.wamblee.security.authorization.AuthorizationResult.UNSUPPORTED_RESOURCE;
-import junit.framework.TestCase;
import org.wamblee.usermgt.User;
/**
- * Tests for the {@link org.wamblee.security.authorization.UrlAuthorizationRule}.
+ * Tests for the {@link
+ * org.wamblee.security.authorization.UrlAuthorizationRule}.
*
* @author Erik Brakkee
*/
public class UrlAuthorizationRuleTest extends TestCase {
-
/**
- * Constructs the rule with a result of UNDECIDED. Verifies that an IllegalArgumentException
- * is thrown.
- *
+ * Constructs the rule with a result of UNDECIDED. Verifies that an
+ * IllegalArgumentException is thrown.
*/
- public void testConstructWithUndecidedResult() {
- try {
- new TestAuthorizationRule(UNDECIDED, "users", "/path", ReadOperation.class);
+ public void testConstructWithUndecidedResult() {
+ try {
+ new TestAuthorizationRule(UNDECIDED, "users", "/path",
+ ReadOperation.class);
fail();
- } catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ok
}
}
-
+
/**
- * Constructs the rule with a result of UNSUPPORTED_RESOURCE. Verifies that an IllegalArgumentException
- * is thrown.
- *
+ * Constructs the rule with a result of UNSUPPORTED_RESOURCE.
+ * Verifies that an IllegalArgumentException is thrown.
*/
- public void testConstructWithUnsupportedResult() {
- try {
- new TestAuthorizationRule(UNSUPPORTED_RESOURCE, "users", "/path", ReadOperation.class);
+ public void testConstructWithUnsupportedResult() {
+ try {
+ new TestAuthorizationRule(UNSUPPORTED_RESOURCE, "users", "/path",
+ ReadOperation.class);
fail();
- } catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
// ok
}
}
-
+
/**
- * Constructs the authorization rule and applies it to an unsupported object type.
- * Verifies that the result is UNSUPPORTED_RESOURCE.
- *
+ * Constructs the authorization rule and applies it to an
+ * unsupported object type. Verifies that the result is
+ * UNSUPPORTED_RESOURCE.
*/
- public void testUnsupportedObject() {
- AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users", "/path", ReadOperation.class);
- assertEquals(UNSUPPORTED_RESOURCE, rule.isAllowed("hello", new ReadOperation(), new TestUserAccessor().getCurrentUser()));
+ public void testUnsupportedObject() {
+ AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users",
+ "/path", ReadOperation.class);
+ assertEquals(UNSUPPORTED_RESOURCE,
+ rule.isAllowed("hello", new ReadOperation(),
+ new TestUserAccessor().getCurrentUser()));
}
-
- public void testMatchingScenarios() {
- AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users", "/path/", ReadOperation.class);
- User user = new TestUserAccessor().getCurrentUser();
-
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testMatchingScenarios() {
+ AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users",
+ "/path/", ReadOperation.class);
+ User user = new TestUserAccessor().getCurrentUser();
+
// everything matches
- assertEquals(GRANTED, rule.isAllowed(new TestResource("/path/a"), new ReadOperation(), user));
- assertEquals(GRANTED, rule.isAllowed(new TestResource("/path/"), new ReadOperation(), user));
-
+ assertEquals(GRANTED,
+ rule.isAllowed(new TestResource("/path/a"), new ReadOperation(),
+ user));
+ assertEquals(GRANTED,
+ rule.isAllowed(new TestResource("/path/"), new ReadOperation(), user));
+
// path does not match.
- assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path"), new ReadOperation(), user));
-
+ assertEquals(UNDECIDED,
+ rule.isAllowed(new TestResource("/path"), new ReadOperation(), user));
+
// operation does not match.
- assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path/"), new WriteOperation(), user));
-
+ assertEquals(UNDECIDED,
+ rule.isAllowed(new TestResource("/path/"), new WriteOperation(),
+ user));
+
// group does not match.
- AuthorizationRule rule2 = new TestAuthorizationRule(GRANTED, "users2", "/path/", ReadOperation.class);
- assertEquals(UNDECIDED, rule2.isAllowed(new TestResource("/path/a"), new ReadOperation(), user));
+ AuthorizationRule rule2 = new TestAuthorizationRule(GRANTED, "users2",
+ "/path/", ReadOperation.class);
+ assertEquals(UNDECIDED,
+ rule2.isAllowed(new TestResource("/path/a"), new ReadOperation(),
+ user));
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.security.authorization.hibernate;
-import java.sql.SQLException;
-
import org.apache.log4j.Logger;
+
import org.hibernate.cfg.Configuration;
+
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.MySQL5InnoDBDialect;
+
import org.hibernate.tool.hbm2ddl.SchemaExport;
+
import org.springframework.orm.hibernate3.HibernateTemplate;
+
import org.wamblee.general.BeanKernel;
+
import org.wamblee.security.authorization.AuthorizationService;
import org.wamblee.security.authorization.AuthorizationServiceTest;
import org.wamblee.security.authorization.TestUserAccessor;
+
import org.wamblee.system.adapters.ClassConfiguration;
import org.wamblee.system.adapters.ClassConfigurationTest;
import org.wamblee.system.adapters.DefaultContainer;
import org.wamblee.system.core.Scope;
import org.wamblee.system.spring.component.DatabaseTesterComponent;
import org.wamblee.system.spring.component.DatasourceComponent;
+
import org.wamblee.usermgt.UserAccessor;
import org.wamblee.usermgt.hibernate.AuthorizationComponent;
import org.wamblee.usermgt.hibernate.HibernateUserAdministrationTest;
import org.wamblee.usermgt.hibernate.UserAdministrationComponent;
+import java.sql.SQLException;
+
+
/**
* Unit test for the persistent authorization service.
- *
+ *
* @author Erik Brakkee
*/
-public class PersistentAuthorizationServiceTest extends
- AuthorizationServiceTest {
-
- private static final Logger LOGGER = Logger
- .getLogger(PersistentAuthorizationServiceTest.class);
+public class PersistentAuthorizationServiceTest extends AuthorizationServiceTest {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final Logger LOGGER = Logger.getLogger(PersistentAuthorizationServiceTest.class);
+ /**
+ * DOCUMENT ME!
+ */
private static final String SERVICE_TABLE = "AUTHORIZATION_SERVICE";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String RULES_TABLE = "AUTHORIZATION_RULES";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String SERVICE_RULES_TABLE = "AUTHORIZATION_SERVICE_RULES";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String OPERATIONCOND_TABLE = "OPERATION_CONDITIONS";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String PATHCOND_TABLE = "PATH_CONDITIONS";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String USERCOND_TABLE = "USER_CONDITIONS";
+ /**
+ * DOCUMENT ME!
+ */
private DefaultContainer container;
+
+ /**
+ * DOCUMENT ME!
+ */
private Scope scope;
+ /**
+ * DOCUMENT ME!
+ */
private DatabaseTesterComponent databaseTester;
+
+ /**
+ * DOCUMENT ME!
+ */
private UserAccessor userAccessor;
+
+ /**
+ * DOCUMENT ME!
+ */
private HibernateTemplate hibernateTemplate;
+
+ /**
+ * DOCUMENT ME!
+ */
private AuthorizationService authorizationService;
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
-
container = new DefaultContainer("top");
DatabaseComponentFactory.addDatabaseConfig(container);
container.addComponent(new DatasourceComponent("datasource"));
- ClassConfiguration useraccessorConfig = new ClassConfiguration(
- TestUserAccessor.class);
+
+ ClassConfiguration useraccessorConfig = new ClassConfiguration(TestUserAccessor.class);
useraccessorConfig.getObjectConfig().getSetterConfig().initAllSetters();
container.addComponent("userAccessor", useraccessorConfig);
- container.addComponent(new AuthorizationComponent("authorization",
- true));
+ container.addComponent(new AuthorizationComponent("authorization", true));
- ClassConfiguration dbtesterConfig = new ClassConfiguration(
- DatabaseTesterComponent.class);
+ ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
container.addComponent("databaseTester", dbtesterConfig);
- ObjectConfiguration config = new ObjectConfiguration(
- PersistentAuthorizationServiceTest.class);
- config.getSetterConfig().clear().add("setUserAccessor").add(
- "setDatabaseTester").add("setHibernateTemplate").add(
- "setAuthorizationService");
+ ObjectConfiguration config = new ObjectConfiguration(PersistentAuthorizationServiceTest.class);
+ config.getSetterConfig().clear().add("setUserAccessor")
+ .add("setDatabaseTester").add("setHibernateTemplate")
+ .add("setAuthorizationService");
container.addComponent("testcase", this, config);
scope = container.start();
super.setUp();
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aDatabaseTester DOCUMENT ME!
+ */
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
databaseTester = aDatabaseTester;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUserAccessor DOCUMENT ME!
+ */
public void setUserAccessor(UserAccessor aUserAccessor) {
userAccessor = aUserAccessor;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aHibernateTemplate DOCUMENT ME!
+ */
public void setHibernateTemplate(HibernateTemplate aHibernateTemplate) {
hibernateTemplate = aHibernateTemplate;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aAuthorizationService DOCUMENT ME!
+ */
public void setAuthorizationService(
- AuthorizationService aAuthorizationService) {
+ AuthorizationService aAuthorizationService) {
authorizationService = aAuthorizationService;
}
/*
* (non-Javadoc)
- *
+ *
* @see
* org.wamblee.security.authorization.AuthorizationServiceTest#createService
* ()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected AuthorizationService createService() {
- PersistentAuthorizationService service = new PersistentAuthorizationService(
- "DEFAULT", hibernateTemplate, createUserAccessor(), 10000);
+ PersistentAuthorizationService service = new PersistentAuthorizationService("DEFAULT",
+ hibernateTemplate, createUserAccessor(), 10000);
+
return service;
}
/*
* (non-Javadoc)
- *
+ *
* @see
* org.wamblee.security.authorization.AuthorizationServiceTest#checkRuleCount
* (int)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aCount DOCUMENT ME!
+ *
+ * @throws RuntimeException DOCUMENT ME!
+ */
@Override
protected void checkRuleCount(int aCount) {
try {
assertEquals(1, databaseTester.getTableSize(SERVICE_TABLE));
assertEquals(aCount, databaseTester.getTableSize(RULES_TABLE));
- assertEquals(aCount, databaseTester
- .getTableSize(SERVICE_RULES_TABLE));
+ assertEquals(aCount,
+ databaseTester.getTableSize(SERVICE_RULES_TABLE));
assertEquals(aCount, databaseTester.getTableSize(USERCOND_TABLE));
assertEquals(aCount, databaseTester.getTableSize(PATHCOND_TABLE));
- assertEquals(aCount, databaseTester
- .getTableSize(OPERATIONCOND_TABLE));
+ assertEquals(aCount,
+ databaseTester.getTableSize(OPERATIONCOND_TABLE));
} catch (SQLException e) {
throw new RuntimeException(e);
}
-
}
- public void testSchemaExport() {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testSchemaExport() {
Configuration config = new Configuration();
- for (String mappingFile: new AuthorizationMappingFiles()) {
- config.addResource(mappingFile);
+
+ for (String mappingFile : new AuthorizationMappingFiles()) {
+ config.addResource(mappingFile);
}
- config.setProperty("hibernate.dialect", MySQL5InnoDBDialect.class.getName());
+
+ config.setProperty("hibernate.dialect",
+ MySQL5InnoDBDialect.class.getName());
+
SchemaExport exporter = new SchemaExport(config);
exporter.setOutputFile("target/mysql5.schema.sql");
- exporter.create(true,false);
+ exporter.create(true, false);
}
+ /**
+ * DOCUMENT ME!
+ */
public void testPerformance() {
-
PersistentAuthorizationService service = (PersistentAuthorizationService) getService();
- int n = 1000;
- long time = System.currentTimeMillis();
+ int n = 1000;
+ long time = System.currentTimeMillis();
+
for (int i = 0; i < n; i++) {
testFirstRuleGrants();
resetTestRules();
resetTestRules();
testNoRulesSupportResource();
}
- LOGGER.info("Executed " + 4 * n + " authorization checks in "
- + (float) (System.currentTimeMillis() - time) / (float) 1000
- + " seconds.");
+
+ LOGGER.info("Executed " + (4 * n) + " authorization checks in "
+ + ((float) (System.currentTimeMillis() - time) / (float) 1000)
+ + " seconds.");
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.security.encryption;
import junit.framework.TestCase;
+
/**
- * Tests for the message digester.
+ * Tests for the message digester.
*
* @author Erik Brakkee
*/
public class MessageDigesterTest extends TestCase {
-
- public void testMd5HexEncoding() {
- assertEquals("e99a18c428cb38d5f260853678922e03", new Md5HexMessageDigester().hash("abc123"));
+ /**
+ * DOCUMENT ME!
+ */
+ public void testMd5HexEncoding() {
+ assertEquals("e99a18c428cb38d5f260853678922e03",
+ new Md5HexMessageDigester().hash("abc123"));
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
+import junit.framework.TestCase;
+
import java.sql.SQLException;
+
import java.util.Set;
-import junit.framework.TestCase;
/**
* Tests the inmemory group set. Intended to be subclassed for other
- * implementations of group set.
+ * implementations of group set.
*/
public class InMemoryGroupSetTest extends TestCase {
-
- protected GroupSet groups;
-
/**
- * This method must be overriden in subclasses.
- * @return New group set object.
+ * DOCUMENT ME!
*/
- protected GroupSet createGroupSet() {
- return new InMemoryGroupSet();
+ protected GroupSet groups;
+
+ /**
+ * This method must be overriden in subclasses.
+ *
+ * @return New group set object.
+ */
+ protected GroupSet createGroupSet() {
+ return new InMemoryGroupSet();
}
-
+
/* (non-Javadoc)
* @see org.wamblee.test.SpringTestCase#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
super.setUp();
- groups = createGroupSet();
- checkGroupCount(0);
+ groups = createGroupSet();
+ checkGroupCount(0);
}
-
-
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aGroup Group to check for existence.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aGroup Group to check for existence.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkGroupExists(String aGroup) throws SQLException {
+ protected void checkGroupExists(String aGroup) throws SQLException {
// Empty
}
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aGroup Group to check for non-existence.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aGroup Group to check for non-existence.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkGroupNotExists(String aGroup) throws SQLException {
+ protected void checkGroupNotExists(String aGroup) throws SQLException {
// Empty
}
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aSize Expected number of groups.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aSize Expected number of groups.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkGroupCount(int aSize) throws SQLException {
+ protected void checkGroupCount(int aSize) throws SQLException {
assertEquals(aSize, groups.size());
}
-
+
/**
- * Adds a group and verifies that the group is added using
- * find(), list(), and contains().
+ * Adds a group and verifies that the group is added using find(),
+ * list(), and contains().
*
+ * @throws SQLException DOCUMENT ME!
*/
- public void testAdd() throws SQLException {
- Group group = new Group("group1");
- assertTrue( groups.add(group) );
- checkGroupExists(group.getName());
- checkGroupCount(1);
- Group group2 = groups.find("group1");
- assertNotNull(group2);
- assertEquals(group.getName(), group2.getName());
- Set<Group> set = groups.list();
- assertEquals(1, set.size());
- assertTrue(set.contains(group));
+ public void testAdd() throws SQLException {
+ Group group = new Group("group1");
+ assertTrue(groups.add(group));
+ checkGroupExists(group.getName());
+ checkGroupCount(1);
+
+ Group group2 = groups.find("group1");
+ assertNotNull(group2);
+ assertEquals(group.getName(), group2.getName());
+
+ Set<Group> set = groups.list();
+ assertEquals(1, set.size());
+ assertTrue(set.contains(group));
}
-
+
/**
* Tries to find a non-existing group. Verifies that null is
- * returned.
+ * returned.
*
+ * @throws SQLException DOCUMENT ME!
*/
- public void testFindUnknownGroup() throws SQLException {
- Group group1 = new Group("group1");
- Group group2 = new Group("group2");
- groups.add(group1);
- groups.add(group2);
- checkGroupExists(group1.getName());
- checkGroupExists(group2.getName());
-
- assertNull( groups.find("group3") );
- checkGroupNotExists("group3");
+ public void testFindUnknownGroup() throws SQLException {
+ Group group1 = new Group("group1");
+ Group group2 = new Group("group2");
+ groups.add(group1);
+ groups.add(group2);
+ checkGroupExists(group1.getName());
+ checkGroupExists(group2.getName());
+
+ assertNull(groups.find("group3"));
+ checkGroupNotExists("group3");
}
-
+
/**
- * Adds duplicate group. Verifies that the existing group is left untouched.
+ * Adds duplicate group. Verifies that the existing group is left
+ * untouched.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- public void testAddDuplicateGroup() throws SQLException {
- Group group1 = new Group("group1");
- groups.add(group1);
-
- assertEquals(1, groups.list().size());
- assertTrue(groups.contains(group1));
- group1 = new Group("group1");
- assertFalse(groups.add(group1));
- assertEquals(1, groups.list().size());
-
- checkGroupExists(group1.getName());
- checkGroupCount(1);
+ public void testAddDuplicateGroup() throws SQLException {
+ Group group1 = new Group("group1");
+ groups.add(group1);
+
+ assertEquals(1, groups.list().size());
+ assertTrue(groups.contains(group1));
+ group1 = new Group("group1");
+ assertFalse(groups.add(group1));
+ assertEquals(1, groups.list().size());
+
+ checkGroupExists(group1.getName());
+ checkGroupCount(1);
}
-
+
/**
- * Removes a group. Verifies that the group is
- * removed and the return value is true.
+ * Removes a group. Verifies that the group is removed and the
+ * return value is true.
*
+ * @throws SQLException DOCUMENT ME!
*/
- public void testRemoveGroup() throws SQLException {
- Group group1 = new Group("group1");
- groups.add(group1);
+ public void testRemoveGroup() throws SQLException {
+ Group group1 = new Group("group1");
+ groups.add(group1);
assertTrue(groups.contains(group1));
checkGroupCount(1);
-
- assertTrue(groups.remove(group1));
- assertFalse(groups.contains(group1));
+
+ assertTrue(groups.remove(group1));
+ assertFalse(groups.contains(group1));
assertNull(groups.find(group1.getName()));
assertEquals(0, groups.list().size());
checkGroupCount(0);
}
-
+
/**
* Removes a non-existing group. Verifies that no groups are
- * removed an that the return value is true.
+ * removed an that the return value is true.
*
+ * @throws SQLException DOCUMENT ME!
*/
- public void testRemoveNonExistingGroup() throws SQLException {
- Group group1 = new Group("group1");
- groups.add(group1);
+ public void testRemoveNonExistingGroup() throws SQLException {
+ Group group1 = new Group("group1");
+ groups.add(group1);
checkGroupCount(1);
- Group nonExistingGroup = new Group("group2");
+
+ Group nonExistingGroup = new Group("group2");
nonExistingGroup.setPrimaryKey(new Long(1000));
nonExistingGroup.setPersistedVersion(1000);
assertFalse(groups.remove(nonExistingGroup));
- assertTrue(groups.contains(group1));
+ assertTrue(groups.contains(group1));
assertEquals(1, groups.list().size());
- checkGroupCount(1);
+ checkGroupCount(1);
}
-
+
/**
- * Adds a number of groups to the set and verifies that list()
- * returns them all.
+ * Adds a number of groups to the set and verifies that list()
+ * returns them all.
*
+ * @throws SQLException DOCUMENT ME!
*/
- public void testList() throws SQLException {
- Group group1 = new Group("group1");
- Group group2 = new Group("group2");
- Group group3 = new Group("group3");
- assertTrue(groups.add(group1));
- assertTrue(groups.add(group2));
+ public void testList() throws SQLException {
+ Group group1 = new Group("group1");
+ Group group2 = new Group("group2");
+ Group group3 = new Group("group3");
+ assertTrue(groups.add(group1));
+ assertTrue(groups.add(group2));
assertTrue(groups.add(group3));
-
- checkGroupExists(group1.getName());
- checkGroupExists(group2.getName());
- checkGroupExists(group3.getName());
-
- Set<Group> set = groups.list();
- assertTrue(set.contains(group1));
- assertTrue(set.contains(group2));
+
+ checkGroupExists(group1.getName());
+ checkGroupExists(group2.getName());
+ checkGroupExists(group3.getName());
+
+ Set<Group> set = groups.list();
+ assertTrue(set.contains(group1));
+ assertTrue(set.contains(group2));
assertTrue(set.contains(group3));
-
- checkGroupCount(3);
+
+ checkGroupCount(3);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
-import java.sql.SQLException;
-import java.util.Set;
-
import junit.framework.TestCase;
import org.wamblee.security.encryption.Md5HexMessageDigester;
+
import org.wamblee.usermgt.UserMgtException.Reason;
+import java.sql.SQLException;
+
+import java.util.Set;
+
+
/**
* Tests the inmemory user set. Intended to be subclassed for other
- * implementations of user set.
+ * implementations of user set.
*/
public class InMemoryUserSetTest extends TestCase {
-
+ /**
+ * DOCUMENT ME!
+ */
protected static final String PASSWORD = "abc123";
-
+
+ /**
+ * DOCUMENT ME!
+ */
private UserSet users;
+
+ /**
+ * DOCUMENT ME!
+ */
private GroupSet groups;
-
- private Group group;
-
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Group group;
+
/**
- * This method must be overriden in subclasses.
- * @return New user set object.
+ * This method must be overriden in subclasses.
+ *
+ * @return New user set object.
*/
- protected UserSet createUserSet() {
- return new InMemoryUserSet( new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"),
- new Md5HexMessageDigester());
+ protected UserSet createUserSet() {
+ return new InMemoryUserSet(new RegexpNameValidator(
+ RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD,
+ "Password must contain at least 6 characters"),
+ new Md5HexMessageDigester());
}
-
+
/**
- * This method must be overriden in subclasses.
- * @return New group set object.
+ * This method must be overriden in subclasses.
+ *
+ * @return New group set object.
*/
- protected GroupSet createGroupSet() {
- return new InMemoryGroupSet();
+ protected GroupSet createGroupSet() {
+ return new InMemoryGroupSet();
}
-
+
/* (non-Javadoc)
* @see org.wamblee.test.SpringTestCase#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
super.setUp();
- users = createUserSet();
- groups = createGroupSet();
- group = new Group("group0");
+ users = createUserSet();
+ groups = createGroupSet();
+ group = new Group("group0");
groups.add(group);
checkUserCount(0);
-
}
-
- protected UserSet getUsers() {
- return users;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected UserSet getUsers() {
+ return users;
}
-
- protected GroupSet getGroups() {
- return groups;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected GroupSet getGroups() {
+ return groups;
}
-
- protected Group createGroup(String aName) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected Group createGroup(String aName) {
return new Group(aName);
}
-
- protected User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ * @param aPassword DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ protected User createUser(String aName, String aPassword, Group aGroup)
+ throws UserMgtException {
return UsermgtTestUtils.createUser(aName, aPassword, aGroup);
}
-
- protected void addUserToGroup(User aUser, Group aGroup) throws UserMgtException {
- aUser.addGroup(aGroup);
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ protected void addUserToGroup(User aUser, Group aGroup)
+ throws UserMgtException {
+ aUser.addGroup(aGroup);
}
-
- protected void removeUserFromGroup(User aUser, Group aGroup ) throws UserMgtException {
- aUser.removeGroup(aGroup);
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ protected void removeUserFromGroup(User aUser, Group aGroup)
+ throws UserMgtException {
+ aUser.removeGroup(aGroup);
}
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aUser User to check for existence.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aUser User to check for existence.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkUserExists(String aUser) throws SQLException {
+ protected void checkUserExists(String aUser) throws SQLException {
// Empty
}
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aUser User to check for non-existence.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aUser User to check for non-existence.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkUserNotExists(String aUser) throws SQLException {
+ protected void checkUserNotExists(String aUser) throws SQLException {
// Empty
}
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aSize Expected number of users.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aSize Expected number of users.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkUserCount(int aSize) throws SQLException {
- assertEquals(aSize, users.size());
+ protected void checkUserCount(int aSize) throws SQLException {
+ assertEquals(aSize, users.size());
}
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aUser User to check for existence.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aUser User to check for existence.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkGroupExists(String aUser) throws SQLException {
+ protected void checkGroupExists(String aUser) throws SQLException {
// Empty
}
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aUser User to check for non-existence.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aUser User to check for non-existence.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkGroupNotExists(String aUser) throws SQLException {
+ protected void checkGroupNotExists(String aUser) throws SQLException {
// Empty
}
-
+
/**
- * Additional check to be implemented by a subclass.
- * @param aSize Expected number of users.
+ * Additional check to be implemented by a subclass.
+ *
+ * @param aSize Expected number of users.
+ *
+ * @throws SQLException DOCUMENT ME!
*/
- protected void checkGroupCount(int aSize) throws SQLException {
+ protected void checkGroupCount(int aSize) throws SQLException {
// Empty
}
-
-
+
/**
- * Adds a user and verifies that the user is added using
- * find(), list(), and contains().
+ * Adds a user and verifies that the user is added using find(),
+ * list(), and contains().
*
+ * @throws SQLException DOCUMENT ME!
+ * @throws UserMgtException DOCUMENT ME!
*/
- public void testAdd() throws SQLException, UserMgtException {
- User user = createUser("user1", PASSWORD, group);
- assertTrue( users.add(user) );
- checkUserExists(user.getName());
- checkUserCount(1);
- User user2 = users.find("user1");
- assertNotNull(user2);
- assertEquals(user.getName(), user2.getName());
- Set<User> set = users.list();
- assertEquals(1, set.size());
- assertTrue(set.contains(user));
+ public void testAdd() throws SQLException, UserMgtException {
+ User user = createUser("user1", PASSWORD, group);
+ assertTrue(users.add(user));
+ checkUserExists(user.getName());
+ checkUserCount(1);
+
+ User user2 = users.find("user1");
+ assertNotNull(user2);
+ assertEquals(user.getName(), user2.getName());
+
+ Set<User> set = users.list();
+ assertEquals(1, set.size());
+ assertTrue(set.contains(user));
}
-
+
/**
* Tries to find a non-existing user. Verifies that null is
- * returned.
+ * returned.
*
+ * @throws SQLException DOCUMENT ME!
+ * @throws UserMgtException DOCUMENT ME!
*/
- public void testFindUnknownUser() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, group);
- User user2 = createUser("user2", PASSWORD, group);
- users.add(user1);
- users.add(user2);
- checkUserExists(user1.getName());
- checkUserExists(user2.getName());
-
- assertNull( users.find("user3") );
- checkUserNotExists("user3");
+ public void testFindUnknownUser() throws SQLException, UserMgtException {
+ User user1 = createUser("user1", PASSWORD, group);
+ User user2 = createUser("user2", PASSWORD, group);
+ users.add(user1);
+ users.add(user2);
+ checkUserExists(user1.getName());
+ checkUserExists(user2.getName());
+
+ assertNull(users.find("user3"));
+ checkUserNotExists("user3");
}
-
+
/**
- * Adds duplicate user. Verifies that the existing user is left untouched.
+ * Adds duplicate user. Verifies that the existing user is left
+ * untouched.
+ *
+ * @throws SQLException DOCUMENT ME!
+ * @throws UserMgtException DOCUMENT ME!
*/
- public void testAddDuplicateUser() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, group);
- users.add(user1);
-
- assertEquals(1, users.list().size());
- assertTrue(users.contains(user1));
- user1 = createUser("user1", PASSWORD, group);
- assertFalse(users.add(user1));
- assertEquals(1, users.list().size());
-
- checkUserExists(user1.getName());
- checkUserCount(1);
+ public void testAddDuplicateUser() throws SQLException, UserMgtException {
+ User user1 = createUser("user1", PASSWORD, group);
+ users.add(user1);
+
+ assertEquals(1, users.list().size());
+ assertTrue(users.contains(user1));
+ user1 = createUser("user1", PASSWORD, group);
+ assertFalse(users.add(user1));
+ assertEquals(1, users.list().size());
+
+ checkUserExists(user1.getName());
+ checkUserCount(1);
}
-
+
/**
- * Removes a user. Verifies that the user is
- * removed and the return value is true.
+ * Removes a user. Verifies that the user is removed and the
+ * return value is true.
*
+ * @throws SQLException DOCUMENT ME!
+ * @throws UserMgtException DOCUMENT ME!
*/
- public void testRemoveUser() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, group);
- users.add(user1);
+ public void testRemoveUser() throws SQLException, UserMgtException {
+ User user1 = createUser("user1", PASSWORD, group);
+ users.add(user1);
assertTrue(users.contains(user1));
checkUserCount(1);
-
- assertTrue(users.remove(user1));
- assertFalse(users.contains(user1));
+
+ assertTrue(users.remove(user1));
+ assertFalse(users.contains(user1));
assertNull(users.find(user1.getName()));
assertEquals(0, users.list().size());
checkUserCount(0);
}
-
+
/**
- * Removes a non-existing user. Verifies that no users are
- * removed an that the return value is true.
+ * Removes a non-existing user. Verifies that no users are removed
+ * an that the return value is true.
*
+ * @throws SQLException DOCUMENT ME!
+ * @throws UserMgtException DOCUMENT ME!
*/
- public void testRemoveNonExistingUser() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, group);
- users.add(user1);
+ public void testRemoveNonExistingUser()
+ throws SQLException, UserMgtException {
+ User user1 = createUser("user1", PASSWORD, group);
+ users.add(user1);
checkUserCount(1);
+
User nonExistingUser = createUser("user2", PASSWORD, group);
nonExistingUser.setPrimaryKey(new Long(1000));
nonExistingUser.setPersistedVersion(10);
assertFalse(users.remove(nonExistingUser));
- assertTrue(users.contains(user1));
+ assertTrue(users.contains(user1));
assertEquals(1, users.list().size());
- checkUserCount(1);
+ checkUserCount(1);
}
-
+
/**
- * Adds a number of users to the set and verifies that list()
- * returns them all.
+ * Adds a number of users to the set and verifies that list()
+ * returns them all.
*
+ * @throws SQLException DOCUMENT ME!
+ * @throws UserMgtException DOCUMENT ME!
*/
- public void testList() throws SQLException, UserMgtException {
- User user1 = createUser("user1", PASSWORD, group);
- User user2 = createUser("user2", PASSWORD, group);
- User user3 = createUser("user3", PASSWORD, group);
- assertTrue(users.add(user1));
- assertTrue(users.add(user2));
+ public void testList() throws SQLException, UserMgtException {
+ User user1 = createUser("user1", PASSWORD, group);
+ User user2 = createUser("user2", PASSWORD, group);
+ User user3 = createUser("user3", PASSWORD, group);
+ assertTrue(users.add(user1));
+ assertTrue(users.add(user2));
assertTrue(users.add(user3));
-
- checkUserExists(user1.getName());
- checkUserExists(user2.getName());
- checkUserExists(user3.getName());
-
- Set<User> set = users.list();
- assertTrue(set.contains(user1));
- assertTrue(set.contains(user2));
+
+ checkUserExists(user1.getName());
+ checkUserExists(user2.getName());
+ checkUserExists(user3.getName());
+
+ Set<User> set = users.list();
+ assertTrue(set.contains(user1));
+ assertTrue(set.contains(user2));
assertTrue(set.contains(user3));
-
- checkUserCount(3);
+
+ checkUserCount(3);
}
-
+
/**
- * Adds several users to different groups and verifies that
- * the correct users are returned when looking for users in
- * different groups.
+ * Adds several users to different groups and verifies that the
+ * correct users are returned when looking for users in different groups.
+ *
* @throws SQLException
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testListByGroup() throws SQLException, UserMgtException {
- Group group1 = new Group("group1");
+ Group group1 = new Group("group1");
Group group2 = new Group("group2");
Group group3 = new Group("group3");
- groups.add(group1);
- groups.add(group2);
+ groups.add(group1);
+ groups.add(group2);
groups.add(group3);
-
+
// user1 user2 user3
// group1 y
// group2 y y
// group3 y y y
-
User user1 = createUser("user1", PASSWORD, group1);
- user1.addGroup(group2);
+ user1.addGroup(group2);
user1.addGroup(group3);
- User user2 = createUser("user2", PASSWORD, group2);
- user2.addGroup(group3);
+
+ User user2 = createUser("user2", PASSWORD, group2);
+ user2.addGroup(group3);
+
User user3 = createUser("user3", PASSWORD, group3);
- users.add(user1);
- users.add(user2);
+ users.add(user1);
+ users.add(user2);
users.add(user3);
-
+
checkUserExists(user1.getName());
- checkUserExists(user2.getName());
- checkUserExists(user3.getName());
-
+ checkUserExists(user2.getName());
+ checkUserExists(user3.getName());
+
checkGroupExists(group1.getName());
- checkGroupExists(group2.getName());
- checkGroupExists(group3.getName());
-
- checkUserCount(3);
- checkGroupCount(3+1); // also count the group that was created in the setUp().
-
+ checkGroupExists(group2.getName());
+ checkGroupExists(group3.getName());
+
+ checkUserCount(3);
+ checkGroupCount(3 + 1); // also count the group that was created in the setUp().
+
Set<User> list = users.list(group1);
- assertTrue(list.contains(user1));
+ assertTrue(list.contains(user1));
assertEquals(1, list.size());
-
- list = users.list(group2);
+
+ list = users.list(group2);
assertTrue(list.contains(user1));
assertTrue(list.contains(user2));
assertEquals(2, list.size());
-
- list = users.list(group3);
+
+ list = users.list(group3);
assertTrue(list.contains(user1));
assertTrue(list.contains(user2));
assertTrue(list.contains(user3));
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt;
-import java.util.Set;
-
import junit.framework.TestCase;
import org.apache.log4j.Logger;
+
import org.wamblee.security.encryption.Md5HexMessageDigester;
+
import org.wamblee.usermgt.UserMgtException.Reason;
+import java.util.Set;
+
+
/**
* Test of user administration implementation.
*
* @author Erik Brakkee
*/
public class UserAdministrationImplTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final Logger LOGGER = Logger.getLogger(UserAdministrationImplTest.class);
- private static final Logger LOGGER = Logger
- .getLogger(UserAdministrationImplTest.class);
-
+ /**
+ * DOCUMENT ME!
+ */
private static final String USER1 = "piet";
+ /**
+ * DOCUMENT ME!
+ */
private static final String PASS1 = "passpiet";
+ /**
+ * DOCUMENT ME!
+ */
private static final String USER2 = "kees";
+ /**
+ * DOCUMENT ME!
+ */
private static final String PASS2 = "passkees";
+ /**
+ * DOCUMENT ME!
+ */
private static final String GROUP1 = "cyclists";
+ /**
+ * DOCUMENT ME!
+ */
private static final String GROUP2 = "runners";
+ /**
+ * DOCUMENT ME!
+ */
private UserAdministration admin;
-
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
super.setUp();
admin = createAdmin();
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
protected UserAdministration createAdmin() {
- UserSet users = new InMemoryUserSet( new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"),
+ UserSet users = new InMemoryUserSet(new RegexpNameValidator(
+ RegexpNameValidator.PASSWORD_PATTERN,
+ Reason.INVALID_PASSWORD,
+ "Password must contain at least 6 characters"),
new Md5HexMessageDigester());
GroupSet groups = new InMemoryGroupSet();
+
return new UserAdministrationImpl(users, groups,
- new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
- Reason.INVALID_USERNAME, "Invalid user"),
- new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
- Reason.INVALID_GROUPNAME, "Invalid group"));
+ new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
+ Reason.INVALID_USERNAME, "Invalid user"),
+ new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
+ Reason.INVALID_GROUPNAME, "Invalid group"));
}
-
- protected User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ * @param aPassword DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ protected User createUser(String aName, String aPassword, Group aGroup)
+ throws UserMgtException {
return UsermgtTestUtils.createUser(aName, aPassword, aGroup);
}
}
/**
- * Creates a new group. Verifies the group is created correctly and that the
- * user is added.
- *
+ * Creates a new group. Verifies the group is created correctly and
+ * that the user is added.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testCreateGroup() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
assertTrue(groups.contains(group));
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUsername DOCUMENT ME!
+ */
private void createInvalidGroup(String aUsername) {
try {
admin.createGroup(aUsername);
fail();
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.INVALID_GROUPNAME, e
- .getReason());
+ assertEquals(UserMgtException.Reason.INVALID_GROUPNAME,
+ e.getReason());
assertEquals(0, admin.getGroupCount());
}
}
/**
- * Creates a new group with an invalid name. Verifies that the appropriate
- * exception is thrown.
- *
+ * Creates a new group with an invalid name. Verifies that the
+ * appropriate exception is thrown.
+ *
* @throws UserMgtException
*/
public void testCreateInvalidGroupName() throws UserMgtException {
}
/**
- * Creates a new group which conflicts with an existing one. Verifies that
- * the UserMgtException is thrown and that no group is added.
- *
+ * Creates a new group which conflicts with an existing one.
+ * Verifies that the UserMgtException is thrown and that no group is
+ * added.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testCreateDuplicateGroup() throws UserMgtException {
admin.createGroup(GROUP1);
+
try {
admin.createGroup(GROUP1);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.DUPLICATE_GROUP, e.getReason());
assertEquals(1, admin.getGroupCount());
+
return;
}
+
fail();
}
/**
- * Creates a new user. Verifies the user is created correctly and that the
- * user is added.
- *
+ * Creates a new user. Verifies the user is created correctly and
+ * that the user is added.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testCreateUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
assertNotNull(user);
assertEquals(USER1, user.getName());
user.checkPassword(PASS1);
assertTrue(users.contains(user));
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUsername DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ */
private void createInvalidUser(String aUsername, Group aGroup) {
try {
admin.createUser(aUsername, "pass", aGroup);
fail();
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.INVALID_USERNAME, e
- .getReason());
+ assertEquals(UserMgtException.Reason.INVALID_USERNAME, e.getReason());
assertEquals(0, admin.getUserCount());
}
}
/**
- * Constructs users with invalid names. Verifies that the appropriate
- * exception is thrown.
- *
+ * Constructs users with invalid names. Verifies that the
+ * appropriate exception is thrown.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testCreateInvalidUserName() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
}
/**
- * Creates a new user which conflicts with an existing one. Verifies that
- * the UserMgtException is thrown and that no user is added.
- *
+ * Creates a new user which conflicts with an existing one.
+ * Verifies that the UserMgtException is thrown and that no user is added.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testCreateDuplicateUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
admin.createUser(USER1, PASS1, group);
+
try {
admin.createUser(USER1, PASS2, group);
fail();
}
/**
- * Gets a known user by name. Verifies the correct user is obtained.
- * Verifies that null is returned when trying to obtain an unknown user.
- *
+ * Gets a known user by name. Verifies the correct user is
+ * obtained. Verifies that null is returned when trying to obtain an
+ * unknown user.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testGetUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
- User user2 = admin.getUser(USER1);
+ User user = admin.createUser(USER1, PASS1, group);
+ User user2 = admin.getUser(USER1);
assertTrue(user.equals(user2));
assertNull(admin.getUser(USER2));
}
/**
- * Gets a known group by name. Verifies the correct group is obtained.
- * Verifies that null is returned when the group is not known.
- *
+ * Gets a known group by name. Verifies the correct group is
+ * obtained. Verifies that null is returned when the group is not known.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testGetGroup() throws UserMgtException {
- Group group = admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
Group group2 = admin.getGroup(GROUP1);
assertTrue(group.equals(group2));
assertNull(admin.getGroup(GROUP2));
}
/**
- * Adds a user to a group. Verifies that the user is added using several API
- * calls. Verifies that an exception occurs if the user is not already part
- * of the group.
- *
+ * Adds a user to a group. Verifies that the user is added using
+ * several API calls. Verifies that an exception occurs if the user is not
+ * already part of the group.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testAddUserToGroup() throws UserMgtException {
-
- Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
Group group2 = admin.createGroup(GROUP2);
assertTrue(user.isInGroup(group));
assertFalse(user.isInGroup(group2));
admin.addUserToGroup(user, group2);
assertTrue(user.isInGroup(group));
assertTrue(user.isInGroup(group2));
+
Set<User> users = admin.getUsers(group2);
assertNotNull(users);
assertEquals(1, users.size());
try {
admin.addUserToGroup(user, group);
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.USER_ALREADY_IN_GROUP, e
- .getReason());
+ assertEquals(UserMgtException.Reason.USER_ALREADY_IN_GROUP,
+ e.getReason());
+
return;
}
+
fail();
}
/**
- * Adds a user to a group where the user does not exist. Verifies that an
- * exception occurs.
- *
+ * Adds a user to a group where the user does not exist. Verifies
+ * that an exception occurs.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testAddUserToGroupUnknownUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = createUser(USER1, PASS1, group);
+ User user = createUser(USER1, PASS1, group);
+
try {
admin.addUserToGroup(user, group);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason());
+
return;
}
+
fail();
}
/**
- * Adds a user to a group where the user does not exist. Verifies that an
- * exception occurs.
- *
+ * Adds a user to a group where the user does not exist. Verifies
+ * that an exception occurs.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testAddUserToGroupUnknownGroup() throws UserMgtException {
- Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
Group group2 = new Group(GROUP2);
+
try {
admin.addUserToGroup(user, group2);
} catch (UserMgtException e) {
assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason());
+
return;
}
+
fail();
}
/**
- * Removes a user from a group. Verifies that the user is removed from the
- * group using several API calls. Verifies that an exception occurs if the
- * user not part of the group or if the user is only part of one group.
+ * Removes a user from a group. Verifies that the user is removed
+ * from the group using several API calls. Verifies that an exception
+ * occurs if the user not part of the group or if the user is only part of
+ * one group.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRemoveUserFromGroup() throws UserMgtException {
- Group group = admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
Group group2 = admin.createGroup(GROUP2);
admin.addUserToGroup(user, group2);
+
Set<Group> groups = user.getGroups();
assertEquals(2, groups.size());
assertTrue(groups.contains(group));
}
/**
- * Removes a user from a group where the user is not known. Verifies that an
- * exception is thrown.
- *
+ * Removes a user from a group where the user is not known.
+ * Verifies that an exception is thrown.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRemoveUserFromGroupUnknownUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = createUser(USER1, GROUP1, group);
+ User user = createUser(USER1, GROUP1, group);
+
try {
admin.removeUserFromGroup(user, group);
} catch (UserMgtException e) {
}
/**
- * Removes a user from a group where the group is not known. Verifies that
- * an exception is thrown.
- *
+ * Removes a user from a group where the group is not known.
+ * Verifies that an exception is thrown.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRemoveUserFromGroupUnknownGroup() throws UserMgtException {
- Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ Group group = admin.createGroup(GROUP1);
+ User user = admin.createUser(USER1, PASS1, group);
Group group2 = new Group(GROUP2);
+
try {
admin.removeUserFromGroup(user, group2);
} catch (UserMgtException e) {
}
/**
- * Removes a user from a group where the user is only part of one group.
- * Verifies that an exception is thrown.
+ * Removes a user from a group where the user is only part of one
+ * group. Verifies that an exception is thrown.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRemoveUserFromGroupOnlyGroup() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
+
try {
admin.removeUserFromGroup(user, group);
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.USER_MUST_BE_IN_A_GROUP, e
- .getReason());
+ assertEquals(UserMgtException.Reason.USER_MUST_BE_IN_A_GROUP,
+ e.getReason());
}
}
/**
- * Gets the list of users and groups. Verifies that the correct suers and
- * groups are returned. Verifies also that the relations from user to group
- * are correct.
- *
+ * Gets the list of users and groups. Verifies that the correct
+ * suers and groups are returned. Verifies also that the relations from
+ * user to group are correct.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testGetUsersAndGroups() throws UserMgtException {
Group group1 = admin.createGroup(GROUP1);
Group group2 = admin.createGroup(GROUP2);
- User user1 = admin.createUser(USER1, PASS1, group1);
+ User user1 = admin.createUser(USER1, PASS1, group1);
admin.addUserToGroup(user1, group2);
- User user2 = admin.createUser(USER2, PASS2, group2);
+
+ User user2 = admin.createUser(USER2, PASS2, group2);
Set<User> users = admin.getUsers();
assertEquals(2, users.size());
* Renames a user. Verifies that the user is renamed. Verifies that
* exceptions are thrown when an attempt is made to rename the user to
* itself or to another existing user, or when the group does not exist.
- *
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRenameUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user1 = admin.createUser(USER1, PASS1, group);
+ User user1 = admin.createUser(USER1, PASS1, group);
admin.renameUser(user1, USER2);
assertEquals(USER2, user1.getName());
assertEquals(user1, admin.getUser(USER2));
try {
admin.renameUser(user1, user1.getName());
} catch (UserMgtException e2) {
- assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2
- .getReason());
+ assertEquals(UserMgtException.Reason.TRIVIAL_RENAME,
+ e2.getReason());
+
return;
}
+
fail();
}
+
fail();
}
/**
- * Renames a user to a user with an invalid username. Verifies that the
- * appropriate exception is thrown.
- *
+ * Renames a user to a user with an invalid username. Verifies that
+ * the appropriate exception is thrown.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRenameUserInvalidUsername() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user1 = admin.createUser(USER1, PASS1, group);
+ User user1 = admin.createUser(USER1, PASS1, group);
+
try {
admin.renameUser(user1, USER2);
} catch (UserMgtException e) {
}
/**
- * Renames a group. Verifies that the group is renamed. Verifies that
- * exceptions are thrown when an attempt is made to rename the group to
- * itself or to another existing group or when the group does not exist.
- *
+ * Renames a group. Verifies that the group is renamed. Verifies
+ * that exceptions are thrown when an attempt is made to rename the group
+ * to itself or to another existing group or when the group does not
+ * exist.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRenameGroup() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
assertEquals(group, admin.getGroup(GROUP2));
admin.createGroup(GROUP1);
+
try {
admin.renameGroup(group, GROUP1);
} catch (UserMgtException e) {
try {
admin.renameGroup(group, group.getName());
} catch (UserMgtException e2) {
- assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2
- .getReason());
+ assertEquals(UserMgtException.Reason.TRIVIAL_RENAME,
+ e2.getReason());
+
return;
}
+
fail();
+
return;
}
+
fail();
}
/**
- * Renames a group to a group with an invalid name. Verifies that the
- * appropriate exception is thrown.
- *
+ * Renames a group to a group with an invalid name. Verifies that
+ * the appropriate exception is thrown.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRenameGroupInvalidGroupname() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
+
try {
admin.renameGroup(group, "a b");
} catch (UserMgtException e) {
}
/**
- * Removes a user. Verifies that the user is removed. Verifies that the an
- * exception is thrown when the user does not exist.
- *
+ * Removes a user. Verifies that the user is removed. Verifies that
+ * the an exception is thrown when the user does not exist.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRemoveUser() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
assertEquals(1, admin.getUserCount());
admin.removeUser(user);
}
/**
- * Removes a group. Verifies that the group is removed. Verifies that the an
- * exception is thrown when the group does not exist or if there are still
- * users in the group.
- *
+ * Removes a group. Verifies that the group is removed. Verifies
+ * that the an exception is thrown when the group does not exist or if
+ * there are still users in the group.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRemoveGroup() throws UserMgtException {
Group group1 = admin.createGroup(GROUP1);
group1 = admin.createGroup(GROUP1);
admin.createUser(USER1, PASS1, group1);
+
try {
admin.removeGroup(group1);
} catch (UserMgtException e) {
- assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED, e
- .getReason());
+ assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED,
+ e.getReason());
+
return;
}
+
fail();
}
/**
- * Tries to remove an unknown group. Verifies that an exception is thrown.
- *
+ * Tries to remove an unknown group. Verifies that an exception is
+ * thrown.
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testRemoveGroupUnknownGroup() throws UserMgtException {
- Group group = admin.createGroup(GROUP1);
+ Group group = admin.createGroup(GROUP1);
Group group2 = new Group(GROUP2);
+
try {
admin.removeGroup(group2);
} catch (UserMgtException e) {
/**
* Changes the password, verifies that this succeeds.
- *
+ *
* @throws UserMgtException
*/
public void testChangePassword() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
- User user = admin.createUser(USER1, PASS1, group);
+ User user = admin.createUser(USER1, PASS1, group);
user.changePassword(PASS1, PASS2);
// retrieve the user and verifies the password hasn't changed.
User user2 = admin.getUser(USER1);
+
try {
user2.checkPassword(PASS2);
fail(); // password should not have changed already.
user2 = admin.getUser(USER1);
user2.checkPassword(PASS2); // this time it should succeed.
-
}
/**
* Performance test. Finds a user by name.
- *
+ *
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testPerformanceFindUserByName() throws UserMgtException {
Group group = admin.createGroup(GROUP1);
admin.createUser(USER1, PASS1, group);
- int n = 1000;
+ int n = 1000;
long time = System.currentTimeMillis();
+
for (int i = 0; i < n; i++) {
admin.getUser(USER1);
}
+
LOGGER.info("Looked up a user " + n + " times in "
- + (float) (System.currentTimeMillis() - time) / 1000.0);
+ + ((float) (System.currentTimeMillis() - time) / 1000.0));
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt;
import org.wamblee.security.encryption.Md5HexMessageDigester;
+
import org.wamblee.usermgt.UserMgtException.Reason;
+
/**
- * User management test utilities.
+ * User management test utilities.
*
* @author Erik Brakkee
*/
public class UsermgtTestUtils {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final String DUMMY_GROUP = "dummygroup";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String DUMMY_PASSWD = "dummypasswd";
- public static Group createGroup(String aName) {
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public static Group createGroup(String aName) {
return new Group(aName);
}
-
- public static User createUser(String aUsername) throws UserMgtException {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUsername DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ public static User createUser(String aUsername) throws UserMgtException {
return createUser(aUsername, DUMMY_GROUP);
}
-
- public static User createUser(String aUsername, String aGroup) throws UserMgtException {
- return createUser(aUsername, createGroup(aGroup));
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUsername DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ public static User createUser(String aUsername, String aGroup)
+ throws UserMgtException {
+ return createUser(aUsername, createGroup(aGroup));
}
-
- public static User createUser(String aUsername, Group aGroup) throws UserMgtException {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUsername DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ public static User createUser(String aUsername, Group aGroup)
+ throws UserMgtException {
return createUser(aUsername, DUMMY_PASSWD, aGroup);
}
-
- public static User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException {
- return new User(aName, aPassword, aGroup,
- new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN,
- Reason.INVALID_PASSWORD, "Password must be at least 6 chars"),
- new Md5HexMessageDigester());
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ * @param aPassword DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ public static User createUser(String aName, String aPassword, Group aGroup)
+ throws UserMgtException {
+ return new User(aName, aPassword, aGroup,
+ new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN,
+ Reason.INVALID_PASSWORD, "Password must be at least 6 chars"),
+ new Md5HexMessageDigester());
}
-
- public static void addUserToGroup(User aUser, Group aGroup) throws UserMgtException {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ public static void addUserToGroup(User aUser, Group aGroup)
+ throws UserMgtException {
aUser.addGroup(aGroup);
}
-
- public static void removeUserFromGroup(User aUser, Group aGroup) throws UserMgtException {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws UserMgtException DOCUMENT ME!
+ */
+ public static void removeUserFromGroup(User aUser, Group aGroup)
+ throws UserMgtException {
aUser.removeGroup(aGroup);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.usermgt.hibernate;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.HashMap;
-import java.util.Map;
-
import org.wamblee.system.adapters.DefaultContainer;
import org.wamblee.system.adapters.ObjectConfiguration;
import org.wamblee.system.core.Scope;
import org.wamblee.system.spring.component.DatabaseTesterComponent;
+
import org.wamblee.test.spring.TestTransactionCallback;
+
import org.wamblee.usermgt.GroupSet;
import org.wamblee.usermgt.InMemoryGroupSetTest;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
/**
- * Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet}
+ * Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet}
*
* @author Erik Brakkee
*/
public class HibernateGroupSetTest extends InMemoryGroupSetTest {
-
- private static final String GROUP_TABLE = "GROUPS";
-
- private static final String GROUP_QUERY = "select * from " + GROUP_TABLE + " where name = ?";
-
+ /**
+ * DOCUMENT ME!
+ */
+ private static final String GROUP_TABLE = "GROUPS";
+
+ /**
+ * DOCUMENT ME!
+ */
+ private static final String GROUP_QUERY = "select * from " + GROUP_TABLE
+ + " where name = ?";
+
+ /**
+ * DOCUMENT ME!
+ */
private DefaultContainer container;
+
+ /**
+ * DOCUMENT ME!
+ */
private Scope scope;
-
+
+ /**
+ * DOCUMENT ME!
+ */
private DatabaseTesterComponent databaseTester;
- private GroupSet groupSet;
-
+
+ /**
+ * DOCUMENT ME!
+ */
+ private GroupSet groupSet;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
-
container = new UserMgtRepositoryTestContainer("top");
-
- ObjectConfiguration config = new ObjectConfiguration(
- HibernateGroupSetTest.class);
- config.getSetterConfig().clear().add(
- "setGroupSet").add("setDatabaseTester");
+
+ ObjectConfiguration config = new ObjectConfiguration(HibernateGroupSetTest.class);
+ config.getSetterConfig().clear().add("setGroupSet")
+ .add("setDatabaseTester");
container.addComponent("testcase", this, config);
scope = container.start();
super.setUp();
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
- protected void tearDown() throws Exception {
+ protected void tearDown() throws Exception {
container.stop(scope);
- super.tearDown();
+ super.tearDown();
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aDatabaseTester DOCUMENT ME!
+ */
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
databaseTester = aDatabaseTester;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroupSet DOCUMENT ME!
+ */
public void setGroupSet(GroupSet aGroupSet) {
groupSet = aGroupSet;
}
/* (non-Javadoc)
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aSize DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
protected void checkGroupCount(int aSize) throws SQLException {
- databaseTester.flush();
+ databaseTester.flush();
super.checkGroupCount(aSize);
assertEquals(aSize, databaseTester.getTableSize(GROUP_TABLE));
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
- protected void checkGroupExists(final String aGroup) throws SQLException {
+ protected void checkGroupExists(final String aGroup)
+ throws SQLException {
databaseTester.flush();
- Map<String,Integer> result =
- databaseTester.executeTransaction(new TestTransactionCallback() {
- /* (non-Javadoc)
- * @see org.wamblee.test.TestTransactionCallback#execute()
- */
- @Override
- public Map execute() throws Exception {
- ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup);
- Map<String,Integer> res = new HashMap<String,Integer>();
- res.put("result", databaseTester.countResultSet(result));
- return res;
- }
- });
-
+
+ Map<String, Integer> result = databaseTester.executeTransaction(new TestTransactionCallback() {
+ /* (non-Javadoc)
+ * @see org.wamblee.test.TestTransactionCallback#execute()
+ */
+ @Override
+ public Map execute() throws Exception {
+ ResultSet result = databaseTester
+ .executeQuery(GROUP_QUERY, aGroup);
+ Map<String, Integer> res = new HashMap<String, Integer>();
+ res.put("result", databaseTester.countResultSet(result));
+
+ return res;
+ }
+ });
+
int count = result.get("result");
assertEquals(1, count);
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
protected void checkGroupNotExists(String aGroup) throws SQLException {
- databaseTester.flush();
- ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup);
- assertEquals(0, databaseTester.countResultSet(result));
+ databaseTester.flush();
+
+ ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup);
+ assertEquals(0, databaseTester.countResultSet(result));
}
-
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected GroupSet createGroupSet() {
- return groupSet;
+ return groupSet;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt.hibernate;
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.sql.SQLException;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.wamblee.cache.EhCache;
+
import org.wamblee.system.adapters.ClassConfiguration;
import org.wamblee.system.adapters.DefaultContainer;
import org.wamblee.system.adapters.ObjectConfiguration;
import org.wamblee.system.core.Scope;
import org.wamblee.system.spring.component.DatabaseTesterComponent;
import org.wamblee.system.spring.component.DatasourceComponent;
+
import org.wamblee.test.spring.TestTransactionCallbackWithoutResult;
+
import org.wamblee.usermgt.UserAdministration;
import org.wamblee.usermgt.UserAdministrationImplTest;
+import java.io.Serializable;
+
+import java.lang.reflect.Method;
+
+import java.sql.SQLException;
+
+
/**
- * User administration tests with persistence based on Hibernate. This executes
- * the same test cases as {@link org.wamblee.usermgt.UserAdministrationImplTest}
- * with in addition, one test case that executes all Hibernate test cases
- * separately with each test case in its own transaction.
+ * User administration tests with persistence based on Hibernate. This
+ * executes the same test cases as {@link
+ * org.wamblee.usermgt.UserAdministrationImplTest} with in addition, one test
+ * case that executes all Hibernate test cases separately with each test case
+ * in its own transaction.
*
* @author Erik Brakkee
*/
public class HibernateUserAdministrationTest extends UserAdministrationImplTest {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final Log LOG = LogFactory.getLog(HibernateUserAdministrationTest.class);
+ /**
+ * DOCUMENT ME!
+ */
private DefaultContainer container;
+
+ /**
+ * DOCUMENT ME!
+ */
private Scope scope;
-
+
+ /**
+ * DOCUMENT ME!
+ */
private DatabaseTesterComponent databaseTester;
+
+ /**
+ * DOCUMENT ME!
+ */
private EhCache<Serializable, Serializable> userCache;
- private UserAdministration userAdmin;
-
-
+
+ /**
+ * DOCUMENT ME!
+ */
+ private UserAdministration userAdmin;
+
/* (non-Javadoc)
* @see org.wamblee.usermgt.UserAdministrationImplTest#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
-
container = new DefaultContainer("top");
DatabaseComponentFactory.addDatabaseConfig(container);
container.addComponent(new DatasourceComponent("datasource"));
container.addComponent(new UserAdministrationComponent("admin", true));
-
- ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
+
+ ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
container.addComponent("databaseTester", dbtesterConfig);
-
- ObjectConfiguration config = new ObjectConfiguration(
- HibernateUserAdministrationTest.class);
- config.getSetterConfig().clear().add(
- "setUserCache").add("setDatabaseTester").add("setUserAdmin");
+
+ ObjectConfiguration config = new ObjectConfiguration(HibernateUserAdministrationTest.class);
+ config.getSetterConfig().clear().add("setUserCache")
+ .add("setDatabaseTester").add("setUserAdmin");
container.addComponent("testcase", this, config);
scope = container.start();
databaseTester.cleanDatabase();
-
+
super.setUp();
clearUserCache();
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUserCache DOCUMENT ME!
+ */
public void setUserCache(EhCache<Serializable, Serializable> aUserCache) {
userCache = aUserCache;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aDatabaseTester DOCUMENT ME!
+ */
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
databaseTester = aDatabaseTester;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUserAdmin DOCUMENT ME!
+ */
public void setUserAdmin(UserAdministration aUserAdmin) {
userAdmin = aUserAdmin;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
- protected void tearDown() throws Exception {
+ protected void tearDown() throws Exception {
container.stop(scope);
super.tearDown();
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.UserAdministrationImplTest#createAdmin()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected UserAdministration createAdmin() {
return userAdmin;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ * @throws RuntimeException DOCUMENT ME!
+ */
public void testAllTestsInASeparateTransaction() throws SQLException {
-
Method[] methods = UserAdministrationImplTest.class.getMethods();
+
for (final Method method : methods) {
if (method.getName().startsWith("test")) {
databaseTester.cleanDatabase();
clearUserCache();
databaseTester.executeTransaction(new TestTransactionCallbackWithoutResult() {
- public void execute() throws Exception {
- LOG.info("Running test " + method.getName());
- try {
- method.invoke(HibernateUserAdministrationTest.this);
- } catch (Throwable t) {
- LOG.error("Test " + method.getName() + " failed");
- throw new RuntimeException(t.getMessage(), t);
- }
- finally {
- LOG.info("Test " + method.getName() + " finished");
- }
+ public void execute() throws Exception {
+ LOG.info("Running test " + method.getName());
- }
- });
+ try {
+ method.invoke(HibernateUserAdministrationTest.this);
+ } catch (Throwable t) {
+ LOG.error("Test " + method.getName()
+ + " failed");
+ throw new RuntimeException(t.getMessage(), t);
+ } finally {
+ LOG.info("Test " + method.getName()
+ + " finished");
+ }
+ }
+ });
}
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.usermgt.hibernate;
-import java.io.Serializable;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.Set;
-
import org.wamblee.cache.EhCache;
+
import org.wamblee.system.adapters.DefaultContainer;
import org.wamblee.system.adapters.ObjectConfiguration;
import org.wamblee.system.core.Scope;
import org.wamblee.system.spring.component.DatabaseTesterComponent;
+
import org.wamblee.usermgt.Group;
import org.wamblee.usermgt.GroupSet;
import org.wamblee.usermgt.InMemoryUserSetTest;
import org.wamblee.usermgt.UserMgtException;
import org.wamblee.usermgt.UserSet;
+import java.io.Serializable;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import java.util.Set;
+
+
/**
* Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet}
- *
+ *
* @author Erik Brakkee
*/
public class HibernateUserSetTest extends InMemoryUserSetTest {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final String USER_TABLE = "USERS";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String GROUP_TABLE = "GROUPS";
+ /**
+ * DOCUMENT ME!
+ */
private static final String USER_QUERY = "select * from " + USER_TABLE
- + " where name = ?";
+ + " where name = ?";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String GROUP_QUERY = "select * from " + GROUP_TABLE
- + " where name = ?";
+ + " where name = ?";
+ /**
+ * DOCUMENT ME!
+ */
private DefaultContainer container;
+
+ /**
+ * DOCUMENT ME!
+ */
private Scope scope;
-
+
+ /**
+ * DOCUMENT ME!
+ */
private UserSet userset;
+
+ /**
+ * DOCUMENT ME!
+ */
private GroupSet groupset;
+
+ /**
+ * DOCUMENT ME!
+ */
private EhCache<Serializable, Serializable> userCache;
+
+ /**
+ * DOCUMENT ME!
+ */
private DatabaseTesterComponent databaseTester;
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryUserSetTest#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
-
container = new UserMgtRepositoryTestContainer("top");
-
- ObjectConfiguration config = new ObjectConfiguration(
- HibernateUserSetTest.class);
- config.getSetterConfig().clear().add("setUserset").add(
- "setGroupset").add("setDatabaseTester").add("setUserCache");
+
+ ObjectConfiguration config = new ObjectConfiguration(HibernateUserSetTest.class);
+ config.getSetterConfig().clear().add("setUserset").add("setGroupset")
+ .add("setDatabaseTester").add("setUserCache");
container.addComponent("testcase", this, config);
scope = container.start();
clearUserCache();
databaseTester.cleanDatabase();
-
+
super.setUp();
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUserset DOCUMENT ME!
+ */
public void setUserset(UserSet aUserset) {
userset = aUserset;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroupset DOCUMENT ME!
+ */
public void setGroupset(GroupSet aGroupset) {
groupset = aGroupset;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUserCache DOCUMENT ME!
+ */
public void setUserCache(EhCache<Serializable, Serializable> aUserCache) {
userCache = aUserCache;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aDatabaseTester DOCUMENT ME!
+ */
public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
databaseTester = aDatabaseTester;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void tearDown() throws Exception {
container.stop(scope);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aSize DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
protected void checkUserCount(int aSize) throws SQLException {
databaseTester.flush();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
protected void checkUserExists(String aUser) throws SQLException {
databaseTester.flush();
+
ResultSet result = databaseTester.executeQuery(USER_QUERY, aUser);
assertEquals(1, databaseTester.countResultSet(result));
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aUser DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
protected void checkUserNotExists(String aUser) throws SQLException {
databaseTester.flush();
+
ResultSet result = databaseTester.executeQuery(USER_QUERY, aUser);
assertEquals(0, databaseTester.countResultSet(result));
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aSize DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
protected void checkGroupCount(int aSize) throws SQLException {
databaseTester.flush();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
protected void checkGroupExists(String aGroup) throws SQLException {
databaseTester.flush();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGroup DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
@Override
protected void checkGroupNotExists(String aGroup) throws SQLException {
databaseTester.flush();
+
ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup);
assertEquals(0, databaseTester.countResultSet(result));
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected UserSet createUserSet() {
return userset;
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.usermgt.InMemoryUserSetTest#createGroupSet()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected GroupSet createGroupSet() {
return groupset;
}
/**
- * Reproduction of a bug. Create a user which is in group1 Add it to a
- * second group group2. Remove the user from group1. Verify the user is in
- * group2.
+ * Reproduction of a bug. Create a user which is in group1 Add it
+ * to a second group group2. Remove the user from group1. Verify the user
+ * is in group2.
+ *
+ * @throws SQLException DOCUMENT ME!
+ * @throws UserMgtException DOCUMENT ME!
*/
public void testVerifyAddRemove() throws SQLException, UserMgtException {
databaseTester.cleanDatabase(); // just to be sure.
+
GroupSet groups = getGroups();
assertEquals(0, groups.size());
+
Group group1 = createGroup("group1");
Group group2 = createGroup("group2");
groups.add(group1);
addUserToGroup(user, group2);
getUsers().userModified(user);
clearUserCache();
- User user2 = getUsers().find("user");
+
+ User user2 = getUsers().find("user");
Set<Group> userGroups = user2.getGroups();
assertTrue(user2.isInGroup("group1"));
assertTrue(user2.isInGroup("group2"));
removeUserFromGroup(user, group1);
getUsers().userModified(user);
clearUserCache();
- user2 = getUsers().find("user");
- userGroups = user2.getGroups();
+ user2 = getUsers().find("user");
+ userGroups = user2.getGroups();
assertFalse(user2.isInGroup("group1"));
assertTrue(user2.isInGroup("group2"));
assertEquals(1, userGroups.size());
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.usermgt.hibernate;
-import java.io.IOException;
-
import org.wamblee.system.adapters.ClassConfiguration;
import org.wamblee.system.adapters.DefaultContainer;
import org.wamblee.system.adapters.ObjectConfiguration;
import org.wamblee.system.spring.component.DatabaseTesterComponent;
import org.wamblee.system.spring.component.DatasourceComponent;
import org.wamblee.system.spring.component.HibernateComponent;
+
import org.wamblee.usermgt.UserGroupRepositoryComponent;
+import java.io.IOException;
+
+
/**
- *
* Test container for repository tests of user management.
- *
+ *
* @author Erik Brakkee
*/
public class UserMgtRepositoryTestContainer extends DefaultContainer {
-
- public UserMgtRepositoryTestContainer(String aName) throws IOException {
+/**
+ * Creates a new UserMgtRepositoryTestContainer object.
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ public UserMgtRepositoryTestContainer(String aName)
+ throws IOException {
super(aName);
DatabaseComponentFactory.addDatabaseConfig(this);
addComponent(new DatasourceComponent("datasource"));
-
- ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class);
+
+ ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class);
mappingFilesConfig.getSetterConfig().initAllSetters();
- addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig);
+ addComponent("mappingFiles", new UsermgtHibernateMappingFiles(),
+ mappingFilesConfig);
addComponent(new HibernateComponent("hibernate"));
addComponent(new UserGroupRepositoryComponent("usersgroups"));
- ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
+
+ ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class);
dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
addComponent("databaseTester", dbtesterConfig);
-
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.cache;
import java.io.Serializable;
+
/**
- * The <code>Cache</code> interface represents... a cache.
- * In some circumstances it is more optimal to implement caching directly in
+ * The <code>Cache</code> interface represents... a cache.
+ * In some circumstances it is more optimal to implement caching directly in
* the code instead of relying on Hibernate caching methods. This interface abstracts
- * from the used cache implementation.
- * Cache implementations must be thread-safe.
+ * from the used cache implementation.
+ * Cache implementations must be thread-safe.
*/
public interface Cache<KeyType extends Serializable, ValueType extends Serializable> {
-
/**
- * Adds a key-value pair to the cache.
- * @param aKey Key.
- * @param aValue Value.
+ * Adds a key-value pair to the cache.
+ *
+ * @param aKey Key.
+ * @param aValue Value.
*/
- void put(KeyType aKey, ValueType aValue);
-
+ void put(KeyType aKey, ValueType aValue);
+
/**
- * Retrieves a value from the cache.
- * @param aKey Key to retrieve.
- * @return Key.
+ * Retrieves a value from the cache.
+ *
+ * @param aKey Key to retrieve.
+ *
+ * @return Key.
*/
ValueType get(KeyType aKey);
-
+
/**
- * Removes an entry from the cache.
- * @param aKey Key to remove the entry for.
+ * Removes an entry from the cache.
+ *
+ * @param aKey Key to remove the entry for.
*/
- void remove(KeyType aKey);
-
+ void remove(KeyType aKey);
+
/**
- * Removes all entries from the cache.
- *
+ * Removes all entries from the cache.
*/
- void clear();
+ void clear();
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.cache;
+import org.apache.log4j.Logger;
+
import java.io.Serializable;
-import org.apache.log4j.Logger;
/**
- * Represents a cached object. The object is either retrieved from the cache if
- * the cache has it, or a call back is invoked to get the object (and put it in
- * the cache).
+ * Represents a cached object. The object is either retrieved from the
+ * cache if the cache has it, or a call back is invoked to get the object (and
+ * put it in the cache).
*
* @author Erik Brakkee
+ *
+ * @param <KeyType> DOCUMENT ME!
+ * @param <ValueType> DOCUMENT ME!
*/
public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
-
- private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
-
/**
- * Callback invoked to compute an object if it was not found in the cache.
- *
- * @param <T>
- * Type of the object
+ * DOCUMENT ME!
*/
- public static interface Computation<Key extends Serializable, Value extends Serializable> {
- /**
- * Gets the object. Called when the object is not in the cache.
- *
- * @param aObjectKey
- * Id of the object in the cache.
- * @return Object, must be non-null.
- */
- Value getObject(Key aObjectKey);
- }
+ private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
/**
* Cache to use.
private KeyType objectKey;
/**
- * Computation used to obtain the object if it is not found in the cache.
+ * Computation used to obtain the object if it is not found in the
+ * cache.
*/
private Computation<KeyType, ValueType> computation;
- /**
+/**
* Constructs the cached object.
- *
+ *
* @param aCache
* Cache to use.
* @param aObjectKey
* cache.
*/
public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
- Computation<KeyType, ValueType> aComputation) {
- cache = aCache;
- objectKey = aObjectKey;
- computation = aComputation;
+ Computation<KeyType, ValueType> aComputation) {
+ cache = aCache;
+ objectKey = aObjectKey;
+ computation = aComputation;
}
/**
- * Gets the object. Since the object is cached, different calls to this
- * method may return different objects.
- *
+ * Gets the object. Since the object is cached, different calls to
+ * this method may return different objects.
+ *
* @return Object.
*/
public ValueType get() {
ValueType object = (ValueType) cache.get(objectKey); // the used
- // cache is
- // thread safe.
+ // cache is
+ // thread safe.
+
if (object == null) {
// synchronize the computation to make sure that the object is only
// computed
// recomputed.
synchronized (this) {
object = (ValueType) cache.get(objectKey);
+
if (object == null) {
// No other thread did a recomputation so we must do this
// now.
}
}
}
+
return object;
}
/**
- * Invalidates the cache for the object so that it is recomputed the next
- * time it is requested.
- *
+ * Invalidates the cache for the object so that it is recomputed
+ * the next time it is requested.
*/
public void invalidate() {
cache.remove(objectKey);
/**
* Gets the cache.
- *
+ *
* @return Cache.
*/
public Cache getCache() {
return cache;
}
+
+/**
+ * Callback invoked to compute an object if it was not found in the cache.
+ *
+ * @param <T>
+ * Type of the object
+ */
+ public static interface Computation<Key extends Serializable, Value extends Serializable> {
+ /**
+ * Gets the object. Called when the object is not in the
+ * cache.
+ *
+ * @param aObjectKey Id of the object in the cache.
+ *
+ * @return Object, must be non-null.
+ */
+ Value getObject(Key aObjectKey);
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.cache;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Serializable;
-
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.log4j.Logger;
+
import org.wamblee.io.InputResource;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Serializable;
+
+
/**
* Cache implemented on top of EhCache.
*
* @author Erik Brakkee
+ *
+ * @param <KeyType> DOCUMENT ME!
+ * @param <ValueType> DOCUMENT ME!
*/
public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
- implements org.wamblee.cache.Cache<KeyType, ValueType> {
-
+ implements org.wamblee.cache.Cache<KeyType, ValueType> {
+ /**
+ * DOCUMENT ME!
+ */
private static final Logger LOGGER = Logger.getLogger(EhCache.class);
/**
*/
private Cache cache;
- /**
+/**
* Constructs a cache based on EHCache.
- *
+ *
* @param aResource
* Resource containing the configuration file for EHCache.
* @param aCacheName
* @throws CacheException
*/
public EhCache(InputResource aResource, String aCacheName)
- throws IOException, CacheException {
+ throws IOException, CacheException {
InputStream is = aResource.getInputStream();
+
try {
- manager = new CacheManager(is);
- cache = manager.getCache(aCacheName);
+ manager = new CacheManager(is);
+ cache = manager.getCache(aCacheName);
+
if (cache == null) {
LOGGER.warn("Creating cache '" + aCacheName
- + "' because it is not configured");
+ + "' because it is not configured");
manager.addCache(aCacheName);
cache = manager.getCache(aCacheName);
}
} finally {
is.close();
}
-
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#put(KeyType, ValueType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ * @param aValue DOCUMENT ME!
+ */
public void put(KeyType aKey, ValueType aValue) {
cache.put(new Element(aKey, aValue));
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#get(KeyType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public ValueType get(KeyType aKey) {
try {
Element element = cache.get(aKey);
+
if (element == null) {
return null;
}
+
return (ValueType) element.getValue();
} catch (CacheException e) {
throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#remove(KeyType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ */
public void remove(KeyType aKey) {
cache.remove(aKey);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#clear()
*/
+ /**
+ * DOCUMENT ME!
+ */
public void clear() {
cache.removeAll();
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.cache;
import java.io.Serializable;
+
import java.util.HashMap;
+
/**
- * A very simple cache based on a HashMap, It never expires any entries, and has
- * no bounds on its size.
+ * A very simple cache based on a HashMap, It never expires any entries,
+ * and has no bounds on its size.
*
* @author Erik Brakkee
+ *
+ * @param <KeyType> DOCUMENT ME!
+ * @param <ValueType> DOCUMENT ME!
*/
public class ForeverCache<KeyType extends Serializable, ValueType extends Serializable>
- implements Cache<KeyType, ValueType> {
-
+ implements Cache<KeyType, ValueType> {
/**
* Cached entries.
*/
private HashMap<KeyType, ValueType> map;
- /**
+/**
* Constructs the cache.
- *
+ *
*/
public ForeverCache() {
map = new HashMap<KeyType, ValueType>();
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#put(KeyType, ValueType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ * @param aValue DOCUMENT ME!
+ */
public synchronized void put(KeyType aKey, ValueType aValue) {
map.put(aKey, aValue);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#get(KeyType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public synchronized ValueType get(KeyType aKey) {
return map.get(aKey);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#remove(KeyType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ */
public synchronized void remove(KeyType aKey) {
map.remove(aKey);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.cache.Cache#clear()
*/
+ /**
+ * DOCUMENT ME!
+ */
public synchronized void clear() {
map.clear();
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.cache;
import java.io.Serializable;
+
/**
- * A cache that does not cache. This implementation is useful for disabling caching.
- * Because of this implementation, application code does not need to distinguish
- * between the situation where it a cache is used and where it isn't.
+ * A cache that does not cache. This implementation is useful for disabling
+ * caching. Because of this implementation, application code does not need to
+ * distinguish between the situation where it a cache is used and where it
+ * isn't.
*
* @author Erik Brakkee
+ *
+ * @param <KeyType> DOCUMENT ME!
+ * @param <ValueType> DOCUMENT ME!
*/
-public class ZeroCache<KeyType extends Serializable, ValueType extends Serializable>
- implements Cache<KeyType, ValueType> {
-
- public ZeroCache() {
+public class ZeroCache<KeyType extends Serializable, ValueType extends Serializable>
+ implements Cache<KeyType, ValueType> {
+ /**
+ * Creates a new ZeroCache object.
+ */
+ public ZeroCache() {
// Empty.
}
-
+
/* (non-Javadoc)
* @see org.wamblee.cache.Cache#put(KeyType, ValueType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ * @param aValue DOCUMENT ME!
+ */
public void put(KeyType aKey, ValueType aValue) {
// Empty.
}
-
+
/* (non-Javadoc)
* @see org.wamblee.cache.Cache#get(KeyType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public ValueType get(KeyType aKey) {
return null;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.cache.Cache#remove(KeyType)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ */
public void remove(KeyType aKey) {
// Empty
}
-
+
/* (non-Javadoc)
* @see org.wamblee.cache.Cache#clear()
*/
+ /**
+ * DOCUMENT ME!
+ */
public void clear() {
// Empty
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.collections;
+import org.wamblee.conditions.Condition;
+
import java.util.Collection;
-import org.wamblee.conditions.Condition;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class CollectionFilter {
-
/**
- * Filters a collection by adding all elements in the from collection
- * that satisfy a given condition to the to collection.
- * @param <T> Type of contained element.
- * @param aFrom From container to which the condition is applied.
- * @param aTo To container to which matching elements are added.
- * @param aCondition Condition by which elements are matched.
+ * Filters a collection by adding all elements in the from
+ * collection that satisfy a given condition to the to collection.
+ *
+ * @param <T> Type of contained element.
+ * @param aFrom From container to which the condition is applied.
+ * @param aTo To container to which matching elements are added.
+ * @param aCondition Condition by which elements are matched.
*/
- public static <T> void filter(Collection<T> aFrom, Collection<T> aTo, Condition<T> aCondition) {
- for (T t: aFrom) {
- if ( aCondition.matches(t)) {
- aTo.add(t);
- }
- }
- }
-
+ public static <T> void filter(Collection<T> aFrom, Collection<T> aTo,
+ Condition<T> aCondition) {
+ for (T t : aFrom) {
+ if (aCondition.matches(t)) {
+ aTo.add(t);
+ }
+ }
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.concurrency;
import java.util.concurrent.locks.ReentrantLock;
+
/**
- * In memory JVM lock.
+ * In memory JVM lock.
*
* @author Erik Brakkee
- */
+ */
public class JvmLock implements Lock {
-
/**
- * Reentrant lock to use.
+ * Reentrant lock to use.
*/
- private ReentrantLock lock;
-
+ private ReentrantLock lock;
+
/**
- * In-memory lock.
+ * In-memory lock.
*/
- public JvmLock() {
- lock = new ReentrantLock(true);
+ public JvmLock() {
+ lock = new ReentrantLock(true);
}
/* (non-Javadoc)
public void acquire() {
lock.lock();
}
-
+
/* (non-Javadoc)
* @see org.wamblee.concurrency.Lock#release()
*/
public void release() {
- lock.unlock();
+ lock.unlock();
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.concurrency;
+
/**
- * Represents a re-entrant lock.
- * Implementations can provide inmemory JVM locking or full cluster safe locking
- * mechanisms.
+ * Represents a re-entrant lock.
+ * Implementations can provide inmemory JVM locking or full cluster safe locking
+ * mechanisms.
*
* @author Erik Brakkee
*/
public interface Lock {
-
/**
- * Acquires the lock.
+ * Acquires the lock.
*/
- void acquire();
-
+ void acquire();
+
/**
- * Releases the lock.
+ * Releases the lock.
*/
- void release();
+ void release();
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.concurrency;
import java.util.HashSet;
* Constructs read-write lock.
*/
public ReadWriteLock() {
- readers = new HashSet<Thread>();
- writer = null;
+ readers = new HashSet<Thread>();
+ writer = null;
}
/**
public synchronized void acquireRead() {
if (readers.contains(Thread.currentThread())) {
throw new IllegalStateException(
- "Read lock already acquired by current thread: "
- + Thread.currentThread());
+ "Read lock already acquired by current thread: " +
+ Thread.currentThread());
}
if (writer == Thread.currentThread()) {
throw new IllegalStateException(
- "Trying to acquire the read lock while already holding a write lock: "
- + Thread.currentThread());
+ "Trying to acquire the read lock while already holding a write lock: " +
+ Thread.currentThread());
}
while (writer != null) {
public synchronized void acquireWrite() {
if (writer == Thread.currentThread()) {
throw new IllegalStateException(
- "Trying to acquire a write lock while already holding the write lock: "
- + Thread.currentThread());
+ "Trying to acquire a write lock while already holding the write lock: " +
+ Thread.currentThread());
}
if (readers.contains(Thread.currentThread())) {
throw new IllegalStateException(
- "Trying to acquire a write lock while already holding the read lock: "
- + Thread.currentThread());
+ "Trying to acquire a write lock while already holding the read lock: " +
+ Thread.currentThread());
}
// wait until there are no more writers and no more
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.conditions;
import java.util.ArrayList;
import java.util.List;
+
/**
* Represents a logical and of different boolean conditions.
*
* @author Erik Brakkee
+ *
+ * @param <T> DOCUMENT ME!
*/
public class AndCondition<T> implements Condition<T> {
-
+ /**
+ * DOCUMENT ME!
+ */
private List<Condition<T>> conditions;
- /**
+/**
* Constructs the condition.
- *
+ *
* @param aCondition1
* First condition.
* @param aCondition2
conditions.add(aCondition2);
}
- /**
+/**
* Constructs the and condition.
- *
+ *
* @param aConditions
* List of conditions to use in the logical and.
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aObject DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean matches(T aObject) {
for (Condition<T> condition : conditions) {
if (!condition.matches(aObject)) {
return false;
}
}
+
return true;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
-
/**
* Determines if an object matches a certain condition.
*
* @author Erik Brakkee
*/
public interface Condition<T> {
-
/**
- * Determines if an object matches a condition.
- * @param aObject object to match.
- * @return True iff the object matches.
+ * Determines if an object matches a condition.
+ *
+ * @param aObject object to match.
+ *
+ * @return True iff the object matches.
*/
- boolean matches(T aObject);
+ boolean matches(T aObject);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
/**
- * Condition which always returns a fixed value.
+ * Condition which always returns a fixed value.
*
* @author Erik Brakkee
+ *
+ * @param <T> DOCUMENT ME!
*/
public class FixedCondition<T> implements Condition<T> {
-
- private boolean value;
-
/**
- * Constructs the condition.
- * @param aValue Fixed value of the condition.
+ * DOCUMENT ME!
*/
- public FixedCondition(boolean aValue) {
- value = aValue;
+ private boolean value;
+
+/**
+ * Constructs the condition.
+ * @param aValue Fixed value of the condition.
+ */
+ public FixedCondition(boolean aValue) {
+ value = aValue;
}
/* (non-Javadoc)
* @see org.wamblee.conditions.Condition#matches(T)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aObject DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean matches(T aObject) {
- return value;
+ return value;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.conditions;
import java.util.ArrayList;
import java.util.List;
+
/**
* Represents a logical or of different boolean conditions.
*
* @author Erik Brakkee
+ *
+ * @param <T> DOCUMENT ME!
*/
public class OrCondition<T> implements Condition<T> {
-
+ /**
+ * DOCUMENT ME!
+ */
private List<Condition<T>> conditions;
- /**
+/**
* Constructs the condition.
- *
+ *
* @param aCondition1
* First condition.
* @param aCondition2
conditions.add(aCondition2);
}
- /**
+/**
* Constructs the or condition.
- *
+ *
* @param aConditions
* List of conditions to use in the logical or.
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aObject DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean matches(T aObject) {
for (Condition<T> condition : conditions) {
if (condition.matches(aObject)) {
return true;
}
}
+
return false;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
+import org.apache.commons.beanutils.PropertyUtils;
+
import java.lang.reflect.InvocationTargetException;
+
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.apache.commons.beanutils.PropertyUtils;
/**
- * Condition to check whether a given property value matches a certain
+ * Condition to check whether a given property value matches a certain
* regular expression.
*
* @author Erik Brakkee
+ *
+ * @param <T> DOCUMENT ME!
*/
public class PropertyRegexCondition<T> implements Condition<T> {
-
/**
- * Property name.
+ * Property name.
*/
private String property;
-
+
/**
- * Regular expression.
+ * Regular expression.
*/
private Pattern regex;
-
+
/**
- * Whether or not to convert the value to lowercase before matching.
+ * Whether or not to convert the value to lowercase before
+ * matching.
*/
- private boolean tolower;
-
- /**
- * Constructs the condition.
- * @param aProperty Name of the property to examine.
- * @param aRegex Regular expression to use.
- * @param aTolower Whether or not to convert the value to lowercase before matching.
+ private boolean tolower;
+
+/**
+ * Constructs the condition.
+ * @param aProperty Name of the property to examine.
+ * @param aRegex Regular expression to use.
+ * @param aTolower Whether or not to convert the value to lowercase before matching.
*/
- public PropertyRegexCondition(String aProperty, String aRegex, boolean aTolower) {
- property = aProperty;
- regex = Pattern.compile(aRegex);
- tolower = aTolower;
+ public PropertyRegexCondition(String aProperty, String aRegex,
+ boolean aTolower) {
+ property = aProperty;
+ regex = Pattern.compile(aRegex);
+ tolower = aTolower;
}
/* (non-Javadoc)
* @see org.wamblee.conditions.Condition#matches(T)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aObject DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean matches(T aObject) {
try {
String value = PropertyUtils.getProperty(aObject, property) + "";
- if ( tolower ) {
- value = value.toLowerCase();
+
+ if (tolower) {
+ value = value.toLowerCase();
}
- Matcher matcher = regex.matcher(value);
- return matcher.matches();
+
+ Matcher matcher = regex.matcher(value);
+
+ return matcher.matches();
} catch (IllegalAccessException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (InvocationTargetException e) {
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.general;
+
/**
- * Bean factory used to obtain objects in a transparent way.
+ * Bean factory used to obtain objects in a transparent way.
*
* @author Erik Brakkee
*/
public interface BeanFactory {
-
- /**
- * Finds a bean based on id.
- * @param aId Id of the bean.
- * @return Object (always non-null).
- * @throws BeanFactoryException In case the object could not be found.
- */
- Object find(String aId);
-
/**
- * Finds a bean of the given class and which can be cast to the
- * specified class. This is typically used by specifying the interface
- * class for retrieving an implementation of that class. This
- * means that the bean implementing the class is configured in the bean factory
- * with id equal to the class name of the interface.
- * @param aClass Class of the object to find.
- * @return Object (always non-null).
- * @throws BeanFactoryException In case the object could not be found.
+ * Finds a bean based on id.
+ * @param aId Id of the bean.
+ * @return Object (always non-null).
+ * @throws BeanFactoryException In case the object could not be found.
*/
- <T> T find(Class<T> aClass);
-
- /**
- * Finds a bean with the given id which can be cast to the specified
- * class.
- * @param <T> Type of the object to get.
- * @param aId Id of the object to lookup.
- * @param aClass Class that the object must extends.
- * @return Object, always non-null.
- * @throws BeanFactoryException In case the object could not be found.
- */
- <T> T find(String aId, Class<T> aClass);
+ Object find(String aId);
+
+ <T> T find(Class<T> aClass);
+
+ <T> T find(String aId, Class<T> aClass);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.general;
/**
- * Exception thrown by the BeanFactory if an object could not be found.
+ * Exception thrown by the BeanFactory if an object could not be found.
*
* @author Erik Brakkee
*/
public class BeanFactoryException extends RuntimeException {
+ /**
+ * DOCUMENT ME!
+ */
static final long serialVersionUID = -1215992188624874902L;
- /**
- * Constructs the exception.
- * @param aMsg Message.
+/**
+ * Constructs the exception.
+ * @param aMsg Message.
*/
- public BeanFactoryException(String aMsg) {
- super(aMsg);
+ public BeanFactoryException(String aMsg) {
+ super(aMsg);
}
-
- /**
- * Constructs the exception.
+
+/**
+ * Constructs the exception.
* @param aMsg Message.
* @param aThrowable Cause of the exception.
*/
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.general;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.wamblee.io.ClassPathResource;
import org.wamblee.io.InputResource;
+import java.io.IOException;
+import java.io.InputStream;
+
+import java.util.Properties;
+
+
/**
* The standard means to obtain the bean factory. This works by reading a
- * property {@value #BEAN_FACTORY_CLASS} from a property file named
- * {@value #BEAN_KERNEL_PROP_FILE} from the class path. This property identifies
- * the bean factory implementation to use. The configured bean factory must have
- * a no-arg constructor.
+ * property {@value #BEAN_FACTORY_CLASS} from a property file named {@value
+ * #BEAN_KERNEL_PROP_FILE} from the class path. This property identifies the
+ * bean factory implementation to use. The configured bean factory must have a
+ * no-arg constructor.
*/
public final class BeanKernel {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final Log LOG = LogFactory.getLog(BeanKernel.class);
/**
private static final String BEAN_KERNEL_PROP_FILE = "org.wamblee.beanfactory.properties";
/**
- * Name of the property to define the name of the bean factory class to use.
- * THis class must have a public default constructor.
+ * Name of the property to define the name of the bean factory
+ * class to use. THis class must have a public default constructor.
*/
private static final String BEAN_FACTORY_CLASS = "org.wamblee.beanfactory.class";
*/
private static BeanFactory BEAN_FACTORY;
- /**
+/**
* Disabled constructor.
- *
+ *
*/
private BeanKernel() {
// Empty
}
/**
- * Overrides the default mechanism for looking up the bean factory by
- * specifying it yourself.
- *
- * @param aOverride
- * Override bean factory.
+ * Overrides the default mechanism for looking up the bean factory
+ * by specifying it yourself.
+ *
+ * @param aOverride Override bean factory.
*/
public static void overrideBeanFactory(BeanFactory aOverride) {
BEAN_FACTORY = aOverride;
/**
* Gets the bean factory.
- *
+ *
* @return Bean factory.
*/
public static BeanFactory getBeanFactory() {
BEAN_FACTORY = lookupBeanFactory(BEAN_KERNEL_PROP_FILE);
}
}
+
return BEAN_FACTORY;
}
/**
* Lookup the bean factory based on the properties file.
- *
+ *
+ * @param aPropertyFilename DOCUMENT ME!
+ *
* @return Bean factory.
+ *
+ * @throws BeanFactoryException DOCUMENT ME!
*/
static BeanFactory lookupBeanFactory(String aPropertyFilename) {
InputResource resource = new ClassPathResource(aPropertyFilename);
- InputStream is;
+ InputStream is;
+
try {
- is = resource.getInputStream();
+ is = resource.getInputStream();
} catch (IOException e) {
- throw new BeanFactoryException("Cannot open resource " + resource,
- e);
+ throw new BeanFactoryException("Cannot open resource " + resource, e);
}
+
try {
Properties props = new Properties();
props.load(is);
- String className = props.getProperty(BEAN_FACTORY_CLASS);
- Class beanFactory = Class.forName(className);
+
+ String className = props.getProperty(BEAN_FACTORY_CLASS);
+ Class beanFactory = Class.forName(className);
+
return (BeanFactory) beanFactory.newInstance();
} catch (Exception e) {
throw new BeanFactoryException("Cannot read from resource "
- + resource, e);
+ + resource, e);
} finally {
try {
is.close();
/*
* Copyright 2006 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.general;
-import java.io.IOException;
import java.io.File;
-import java.net.URLClassLoader;
-import java.net.URL;
+import java.io.IOException;
+
import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+
+
/**
* Utility for working with the class loader. Based on the ClassPathHacker
- * example found on the internet.
+ * example found on the internet.
*/
public class ClassLoaderUtils {
-
// No logging in this class to keep the required class libraries
// limited to the standard java classes. This allows use of the
// utilities in an environment with a very limited classpath.
-
private static final String JAR_SUFFIX = ".jar";
/**
- * Adds all jars in the given directory to the class path.
- * @param aDirectory Directory.
+ * Adds all jars in the given directory to the class path.
+ * @param aDirectory Directory.
* @throws IOException
*/
- public static void addJarsInDirectory(File aDirectory) throws IOException {
+ public static void addJarsInDirectory(File aDirectory)
+ throws IOException {
System.out.println("directory '" + aDirectory + "'");
for (File aFile : aDirectory.listFiles()) {
- System.out
- .println("Considering '" + aFile.getCanonicalPath() + "'");
+ System.out.println("Considering '" + aFile.getCanonicalPath() +
+ "'");
+
if (aFile.getName().toLowerCase().endsWith(JAR_SUFFIX)) {
- System.out.println("Adding '" + aFile.getCanonicalPath()
- + "' to classpath.");
+ System.out.println("Adding '" + aFile.getCanonicalPath() +
+ "' to classpath.");
addFile(aFile);
}
}
/**
* Adds a file to the classpath.
- * @param aFilename Filename to add.
+ * @param aFilename Filename to add.
* @throws IOException
*/
public static void addFile(String aFilename) throws IOException {
}
/**
- * Adds a file to the classpath.
- * @param aFile File to add.
+ * Adds a file to the classpath.
+ * @param aFile File to add.
* @throws IOException
*/
public static void addFile(File aFile) throws IOException {
/**
* Adds a url to the classpath.
- * @param aUrl Url to add.
+ * @param aUrl Url to add.
* @throws IOException
*/
public static void addURL(URL aUrl) throws IOException {
-
- URLClassLoader sysloader = (URLClassLoader) ClassLoader
- .getSystemClassLoader();
+ URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
- Method method = sysclass.getDeclaredMethod("addURL", new Class[]{ URL.class } );
+ Method method = sysclass.getDeclaredMethod("addURL",
+ new Class[] { URL.class });
method.setAccessible(true);
method.invoke(sysloader, new Object[] { aUrl });
} catch (Throwable t) {
t.printStackTrace();
throw new IOException(
- "Error, could not add URL to system classloader");
+ "Error, could not add URL to system classloader");
}
-
}
-
}
-
-
-
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.general;
+
/**
* Represents a pair of objects. This is inspired on the C++ Standard Template
* Library pair template.
- *
+ *
* @param <T>
* Type of the first object.
* @param <U>
* @author Erik Brakkee
*/
public class Pair<T, U> {
-
private T t;
-
private U u;
/**
* Constructs the pair.
- *
+ *
* @param aT
* First object.
* @param aU
/**
* Copies a pair.
- *
+ *
* @param aPair
* Pair to copy.
*/
/**
* Gets the first object of the pair.
- *
+ *
* @return First object.
*/
public T getFirst() {
/**
* Gets the second object of the pair.
- *
+ *
* @return Second object.
*/
public U getSecond() {
return u;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import java.io.IOException;
import java.io.InputStream;
+
/**
* Represents an input resource in the classpath.
*/
*/
private String resource;
- /**
+/**
* Construct the class path resource.
- *
+ *
* @param aResource
* Resource
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.io.InputResource#getInputStream()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public InputStream getInputStream() throws IOException {
InputStream stream = Thread.currentThread().getContextClassLoader()
- .getResourceAsStream(resource);
+ .getResourceAsStream(resource);
+
if (stream == null) {
throw new IOException("Class path resource '" + resource
- + "' not found.");
+ + "' not found.");
}
+
return stream;
}
/*
* (non-Javadoc)
- *
+ *
* @see java.lang.Object#toString()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public String toString() {
return "ClassPathResource(" + resource + ")";
}
/*
* Copyright 2006 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.io;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.io.File;
import java.io.FileFilter;
+
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
/**
* Monitors a directory for changes.
- *
+ *
* @author Erik Brakkee
*/
public class DirectoryMonitor {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
+
+ /**
+ * DOCUMENT ME!
+ */
+ private File directory;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private FileFilter filter;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Listener listener;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<File, Date> contents;
+
+/**
+ * Creates a new DirectoryMonitor object.
+ *
+ * @param aDirectory DOCUMENT ME!
+ * @param aFilefilter DOCUMENT ME!
+ * @param aListener DOCUMENT ME!
+ */
+ public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
+ Listener aListener) {
+ directory = aDirectory;
+
+ if (!directory.isDirectory()) {
+ throw new IllegalArgumentException("Directory '" + directory
+ + "' does not exist");
+ }
+
+ filter = aFilefilter;
+ listener = aListener;
+ contents = new HashMap<File, Date>();
+ }
+
+ /**
+ * Polls the directory for changes and notifies the listener of any
+ * changes. In case of any exceptions thrown by the listener while
+ * handling the changes, the next call to this method will invoked the
+ * listeners again for the same changes.
+ */
+ public void poll() {
+ LOG.debug("Polling " + directory);
+
+ Map<File, Date> newContents = new HashMap<File, Date>();
+ File[] files = directory.listFiles(filter);
+
+ // Check deleted files.
+ Set<File> deletedFiles = new HashSet<File>(contents.keySet());
+
+ for (File file : files) {
+ if (file.isFile()) {
+ if (contents.containsKey(file)) {
+ deletedFiles.remove(file);
+ }
+ }
+ }
+
+ for (File file : deletedFiles) {
+ listener.fileDeleted(file);
+ }
+
+ for (File file : files) {
+ if (file.isFile()) {
+ if (contents.containsKey(file)) {
+ Date oldDate = contents.get(file);
+
+ if (file.lastModified() != oldDate.getTime()) {
+ listener.fileChanged(file);
+ } else {
+ // No change.
+ }
+
+ newContents.put(file, new Date(file.lastModified()));
+ } else {
+ listener.fileCreated(file);
+ newContents.put(file, new Date(file.lastModified()));
+ }
+ }
+ }
+
+ contents = newContents;
+ }
+
+ public static interface Listener {
+ void fileChanged(File aFile);
- private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
-
- public static interface Listener {
-
- void fileChanged(File aFile);
-
- void fileCreated(File aFile);
-
- void fileDeleted(File aFile);
- };
-
- private File directory;
- private FileFilter filter;
- private Listener listener;
- private Map<File, Date> contents;
-
- public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
- Listener aListener) {
- directory = aDirectory;
- if (!directory.isDirectory()) {
- throw new IllegalArgumentException("Directory '" + directory
- + "' does not exist");
- }
- filter = aFilefilter;
- listener = aListener;
- contents = new HashMap<File, Date>();
- }
-
- /**
- * Polls the directory for changes and notifies the listener of any changes.
- * In case of any exceptions thrown by the listener while handling the changes,
- * the next call to this method will invoked the listeners again for the same changes.
- */
- public void poll() {
- LOG.debug("Polling " + directory);
- Map<File, Date> newContents = new HashMap<File, Date>();
- File[] files = directory.listFiles(filter);
-
- // Check deleted files.
- Set<File> deletedFiles = new HashSet<File>(contents.keySet());
- for (File file : files) {
- if (file.isFile()) {
- if (contents.containsKey(file)) {
- deletedFiles.remove(file);
- }
- }
- }
- for (File file : deletedFiles) {
- listener.fileDeleted(file);
- }
-
- for (File file : files) {
- if (file.isFile()) {
- if (contents.containsKey(file)) {
- Date oldDate = contents.get(file);
- if (file.lastModified() != oldDate.getTime()) {
- listener.fileChanged(file);
- } else {
- // No change.
- }
- newContents.put(file, new Date(file.lastModified()));
- } else {
- listener.fileCreated(file);
- newContents.put(file, new Date(file.lastModified()));
- }
- }
- }
-
- contents = newContents;
- }
+ void fileCreated(File aFile);
+ void fileDeleted(File aFile);
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import java.io.IOException;
import java.io.InputStream;
+
/**
* Resource implemention for reading from a file.
*
*/
private File file;
- /**
+/**
* Constructs the resource.
- *
+ *
* @param aFile
* File to read.
*/
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.io.InputResource#getInputStream()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public InputStream getInputStream() throws IOException {
return new BufferedInputStream(new FileInputStream(file));
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import java.io.IOException;
import java.io.InputStream;
+
/**
* Represents a resource from which information can be read.
*
*/
public interface InputResource {
/**
- * Gets the input stream to the resource. The obtained input stream must be
- * closed once reading has finished.
- *
+ * Gets the input stream to the resource. The obtained input stream
+ * must be closed once reading has finished.
+ *
* @return Input stream to the resource, never null.
- * @throws IOException
- * in case the resource cannot be found.
+ *
+ * @throws IOException in case the resource cannot be found.
*/
InputStream getInputStream() throws IOException;
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.io;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class SimpleProcess {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final Log LOG = LogFactory.getLog(SimpleProcess.class);
- private static final Log LOG = LogFactory.getLog(SimpleProcess.class);
+ /**
+ * DOCUMENT ME!
+ */
+ private File directory;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private String[] cmd;
- private File directory;
+ /**
+ * DOCUMENT ME!
+ */
+ private String stdout;
- private String[] cmd;
-
- private String stdout;
- private String stderr;
+ /**
+ * DOCUMENT ME!
+ */
+ private String stderr;
- public SimpleProcess(File aDirectory, String[] aCmd) {
- directory = aDirectory;
- cmd = aCmd;
- }
+/**
+ * Creates a new SimpleProcess object.
+ *
+ * @param aDirectory DOCUMENT ME!
+ * @param aCmd DOCUMENT ME!
+ */
+ public SimpleProcess(File aDirectory, String[] aCmd) {
+ directory = aDirectory;
+ cmd = aCmd;
+ }
/**
+ * DOCUMENT ME!
+ *
* @return the stdout
*/
public String getStdout() {
return stdout;
}
-
+
/**
+ * DOCUMENT ME!
+ *
* @return the stderr
*/
public String getStderr() {
return stderr;
}
-
- /**
- * Runs the process and blocks until it is done.
- *
- * @return Exit status of the process.
- * @throws IOException
- * In case of problems.
- */
- public int run() throws IOException {
- return runImpl();
- }
-
- private int runImpl() throws IOException {
- try {
- String fullcmd = "";
- for (String part: cmd) {
- fullcmd += " " + part;
- }
- LOG.debug("Executing '" + fullcmd + "' in directory '" + directory
- + "'");
- java.lang.Process proc = Runtime.getRuntime().exec(cmd, null, directory);
-
- // Read standard output and error in separate threads to avoid
- // deadlock.
-
- StringWriter myStdout = new StringWriter();
- StringWriter myStderr = new StringWriter();
- Thread stdoutReader = readAndLogStream("STDOUT> ", proc
- .getInputStream(), myStdout);
- Thread stderrReader = readAndLogStream("STDERR> ", proc
- .getErrorStream(), myStderr);
-
- try {
- proc.waitFor();
- } catch (InterruptedException e) {
- IOException exception = new IOException(
- "Process was terminated: " + this);
- exception.initCause(e);
- throw exception;
- }
- waitForReader(stdoutReader);
- waitForReader(stderrReader);
-
- stdout = myStdout.toString();
- stderr = myStderr.toString();
-
- if (proc.exitValue() != 0) {
- LOG.warn("Exit value was non-zero: " + this);
- } else {
- LOG.debug("Process finished");
- }
- return proc.exitValue();
- } catch (IOException e) {
- IOException exception = new IOException("Error executing process: "
- + this);
- exception.initCause(e);
- throw exception;
- }
- }
-
- private void waitForReader(Thread aReaderThread) {
- try {
- aReaderThread.join();
- } catch (InterruptedException e) {
- LOG
- .warn(this
- + ": error waiting for output stream reader of process to finish");
- }
- }
-
- private Thread readAndLogStream(final String aPrefix,
- final InputStream aStream, final Writer aOutput) {
- Thread inputReader = new Thread() {
- @Override
- public void run() {
- BufferedReader br = null;
- try {
- br = new BufferedReader(new InputStreamReader(aStream));
- String str;
- while ((str = br.readLine()) != null) {
- LOG.debug(aPrefix + str);
- aOutput.write(str);
- }
- } catch (IOException e) {
- LOG.warn(SimpleProcess.this + ": error reading input stream", e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- LOG.warn("Error closing stream " + aPrefix);
- }
- }
- }
- }
- };
- inputReader.start();
- return inputReader;
- }
-
- @Override
- public String toString() {
+
+ /**
+ * Runs the process and blocks until it is done.
+ *
+ * @return Exit status of the process.
+ *
+ * @throws IOException In case of problems.
+ */
+ public int run() throws IOException {
+ return runImpl();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ private int runImpl() throws IOException {
+ try {
+ String fullcmd = "";
+
+ for (String part : cmd) {
+ fullcmd += (" " + part);
+ }
+
+ LOG.debug("Executing '" + fullcmd + "' in directory '" + directory
+ + "'");
+
+ java.lang.Process proc = Runtime.getRuntime()
+ .exec(cmd, null, directory);
+
+ // Read standard output and error in separate threads to avoid
+ // deadlock.
+ StringWriter myStdout = new StringWriter();
+ StringWriter myStderr = new StringWriter();
+ Thread stdoutReader = readAndLogStream("STDOUT> ",
+ proc.getInputStream(), myStdout);
+ Thread stderrReader = readAndLogStream("STDERR> ",
+ proc.getErrorStream(), myStderr);
+
+ try {
+ proc.waitFor();
+ } catch (InterruptedException e) {
+ IOException exception = new IOException(
+ "Process was terminated: " + this);
+ exception.initCause(e);
+ throw exception;
+ }
+
+ waitForReader(stdoutReader);
+ waitForReader(stderrReader);
+
+ stdout = myStdout.toString();
+ stderr = myStderr.toString();
+
+ if (proc.exitValue() != 0) {
+ LOG.warn("Exit value was non-zero: " + this);
+ } else {
+ LOG.debug("Process finished");
+ }
+
+ return proc.exitValue();
+ } catch (IOException e) {
+ IOException exception = new IOException("Error executing process: "
+ + this);
+ exception.initCause(e);
+ throw exception;
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aReaderThread DOCUMENT ME!
+ */
+ private void waitForReader(Thread aReaderThread) {
+ try {
+ aReaderThread.join();
+ } catch (InterruptedException e) {
+ LOG.warn(this
+ + ": error waiting for output stream reader of process to finish");
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPrefix DOCUMENT ME!
+ * @param aStream DOCUMENT ME!
+ * @param aOutput DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private Thread readAndLogStream(final String aPrefix,
+ final InputStream aStream, final Writer aOutput) {
+ Thread inputReader = new Thread() {
+ @Override
+ public void run() {
+ BufferedReader br = null;
+
+ try {
+ br = new BufferedReader(new InputStreamReader(aStream));
+
+ String str;
+
+ while ((str = br.readLine()) != null) {
+ LOG.debug(aPrefix + str);
+ aOutput.write(str);
+ }
+ } catch (IOException e) {
+ LOG.warn(SimpleProcess.this
+ + ": error reading input stream", e);
+ } finally {
+ if (br != null) {
+ try {
+ br.close();
+ } catch (IOException e) {
+ LOG.warn("Error closing stream " + aPrefix);
+ }
+ }
+ }
+ }
+ };
+
+ inputReader.start();
+
+ return inputReader;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String toString() {
String fullcmd = "";
- for (String part: cmd) {
- fullcmd += part + " ";
+
+ for (String part : cmd) {
+ fullcmd += (part + " ");
}
- return "process(dir = '" + directory + "', cmd = '" + fullcmd + "')";
- }
+
+ return "process(dir = '" + directory + "', cmd = '" + fullcmd + "')";
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import java.io.IOException;
import java.io.InputStream;
+
/**
* Input resource based on an input stream.
*
*/
private InputStream stream;
- /**
+/**
* Constructs a resource.
- *
+ *
* @param aStream
* Input stream to read.
*/
/*
* (non-Javadoc)
- *
+ *
* @see InputResource#getInputStream()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public InputStream getInputStream() throws IOException {
return stream;
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.observer;
+
/**
* Default observer notifier which calls
* {@link org.wamblee.observer.Observer#send(ObservableType, Event)}
*
* @author Erik Brakkee
*/
-public class DefaultObserverNotifier<ObservableType, Event> implements
- ObserverNotifier<ObservableType, Event> {
-
+public class DefaultObserverNotifier<ObservableType, Event>
+ implements ObserverNotifier<ObservableType, Event> {
/**
* Constructs the notifier.
- *
+ *
*/
public DefaultObserverNotifier() {
// Empty
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.observer.ObserverNotifier#update(org.wamblee.observer.Observer,
* ObservableType, Event)
*/
public void update(Observer<ObservableType, Event> aObserver,
- ObservableType aObservable, Event aEvent) {
+ ObservableType aObservable, Event aEvent) {
aObserver.send(aObservable, aEvent);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.observer;
-import java.util.List;
+import org.apache.log4j.Logger;
+
import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
import java.util.TreeMap;
-import org.apache.log4j.Logger;
/**
* Implements subscription and notification logic for an observer pattern. This
* class is thread safe.
*/
public class Observable<ObservableType, Event> {
-
private static final Logger LOGGER = Logger.getLogger(Observable.class);
/**
/**
* Constructs the observable.
- *
+ *
* @param aObservable
* Observable this instance is used for.
* @param aNotifier
* Object used for implementing notification of listeners.
*/
public Observable(ObservableType aObservable,
- ObserverNotifier<ObservableType, Event> aNotifier) {
+ ObserverNotifier<ObservableType, Event> aNotifier) {
observable = aObservable;
notifier = aNotifier;
observers = new TreeMap<Long, Observer<ObservableType, Event>>();
/**
* Subscribe an obvers.
- *
+ *
* @param aObserver
* Observer to subscribe.
* @return Event Event to send.
*/
- public synchronized long subscribe(Observer<ObservableType, Event> aObserver) {
+ public synchronized long subscribe(
+ Observer<ObservableType, Event> aObserver) {
long subscription = counter++; // integer rage is so large it will
- // never roll over.
+ // never roll over.
+
observers.put(subscription, aObserver);
+
return subscription;
}
/**
* Unsubscribe an observer.
- *
+ *
* @param aSubscription
* Subscription which is used
* @throws IllegalArgumentException
*/
public synchronized void unsubscribe(long aSubscription) {
Object obj = observers.remove(aSubscription);
+
if (obj == null) {
- throw new IllegalArgumentException("Subscription '" + aSubscription
- + "'");
+ throw new IllegalArgumentException("Subscription '" +
+ aSubscription + "'");
}
}
/**
* Gets the number of subscribed observers.
- *
+ *
* @return Number of subscribed observers.
*/
public int getObserverCount() {
/**
* Notifies all subscribed observers.
- *
+ *
* @param aEvent
* Event to send.
*/
// potential deadlock
// situations.
List<Observer<ObservableType, Event>> myObservers = new ArrayList<Observer<ObservableType, Event>>();
+
synchronized (this) {
myObservers.addAll(observers.values());
}
+
for (Observer<ObservableType, Event> observer : myObservers) {
notifier.update(observer, observable, aEvent);
}
/*
* (non-Javadoc)
- *
+ *
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
if (observers.size() > 0) {
- LOGGER
- .error("Still observers registered at finalization of observer!");
+ LOGGER.error(
+ "Still observers registered at finalization of observer!");
+
for (Observer observer : observers.values()) {
LOGGER.error(" observer: " + observer);
}
super.finalize();
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.observer;
+
/**
- * This is a type-safe version of {@link java.util.Observable}.
+ * This is a type-safe version of {@link java.util.Observable}.
*
* @author Erik Brakkee
*/
public interface Observer<ObservableType, Event> {
-
/**
* Called when an event has occurred on the observable.
- * @param aObservable Observable.
- * @param aEvent Event.
+ * @param aObservable Observable.
+ * @param aEvent Event.
*/
- void send(ObservableType aObservable, Event aEvent);
+ void send(ObservableType aObservable, Event aEvent);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.observer;
+
/**
- * Implementation of notification of subscribers.
+ * Implementation of notification of subscribers.
*
* @author Erik Brakkee
*/
public interface ObserverNotifier<ObservableType, Event> {
-
/**
- * Notifies an observer.
+ * Notifies an observer.
*
* @param aObserver Observer to notify
- * @param aObservable Observable at which the event occured.
- * @param aEvent Event that occured.
+ * @param aObservable Observable at which the event occured.
+ * @param aEvent Event that occured.
*/
- void update(Observer<ObservableType, Event> aObserver, ObservableType aObservable, Event aEvent);
-
+ void update(Observer<ObservableType, Event> aObserver,
+ ObservableType aObservable, Event aEvent);
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.persistence;
import java.io.Serializable;
+
/**
- * Default implementation of Persistent.
+ * Default implementation of Persistent.
*
* @author Erik Brakkee
*/
public abstract class AbstractPersistent implements Persistent {
-
/**
- * Primary key.
+ * Primary key.
*/
- private Serializable primaryKey;
-
+ private Serializable primaryKey;
+
/**
- * Version.
+ * Version.
*/
- private int version;
-
- /**
- * Constructs the object.
+ private int version;
+
+/**
+ * Constructs the object.
*
*/
- protected AbstractPersistent() {
- primaryKey = null;
- version = -1;
+ protected AbstractPersistent() {
+ primaryKey = null;
+ version = -1;
}
-
- /**
- * Copy constructor.
- * @param aPersistent Object to copy.
+
+/**
+ * Copy constructor.
+ * @param aPersistent Object to copy.
*/
protected AbstractPersistent(AbstractPersistent aPersistent) {
- primaryKey = aPersistent.primaryKey;
- version = aPersistent.version;
+ primaryKey = aPersistent.primaryKey;
+ version = aPersistent.version;
}
/* (non-Javadoc)
* @see org.wamblee.persistence.Persistent#getPrimaryKey()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Serializable getPrimaryKey() {
- return primaryKey;
+ return primaryKey;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.persistence.Persistent#setPrimaryKey(java.io.Serializable)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ */
public void setPrimaryKey(Serializable aKey) {
- primaryKey = aKey;
+ primaryKey = aKey;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.persistence.Persistent#getPersistedVersion()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public int getPersistedVersion() {
- return version;
+ return version;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.persistence.Persistent#setPersistedVersion(int)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aVersion DOCUMENT ME!
+ */
public void setPersistedVersion(int aVersion) {
version = aVersion;
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.persistence;
import java.io.Serializable;
+
/**
* Interface for persistent objects. This defines required functionality for all objects
- * that are persisted.
- *
- * Objects that implement this interface and which implement
+ * that are persisted.
+ *
+ * Objects that implement this interface and which implement
* {@link java.lang.Object#equals(java.lang.Object)}
- * should exclude the primary key and version from determining equality.
+ * should exclude the primary key and version from determining equality.
*/
public interface Persistent {
-
/**
- * Gets the primary key.
+ * Gets the primary key.
+ *
* @return Primary key.
- * @see #setPrimaryKey(Serializable)
+ *
+ * @see #setPrimaryKey(Serializable)
*/
- Serializable getPrimaryKey();
-
+ Serializable getPrimaryKey();
+
/**
- * Sets the primary key.
+ * Sets the primary key.
+ *
* @param aKey Primary key.
- * @see #getPrimaryKey()
+ *
+ * @see #getPrimaryKey()
*/
- void setPrimaryKey(Serializable aKey);
-
+ void setPrimaryKey(Serializable aKey);
+
/**
- * Gets the version.
- * @return Version.
+ * Gets the version.
+ *
+ * @return Version.
+ *
* @see #setPersistedVersion(int)
*/
- int getPersistedVersion();
-
+ int getPersistedVersion();
+
/**
- * Sets the version.
- * @param aVersion Version.
+ * Sets the version.
+ *
+ * @param aVersion Version.
+ *
* @see #getPersistedVersion()
*/
- void setPersistedVersion(int aVersion);
+ void setPersistedVersion(int aVersion);
}
package org.wamblee.reflection;
import java.lang.reflect.Method;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+
public class ReflectionUtils {
+ /**
+ * Wraps a type by the corresponding wrapper type if it is a primitive
+ * type.
+ * @param aClass Type to wrap.
+ * @return Wrapped type for primitives or the provided argument value.
+ */
+ public static Class wrapIfNeeded(Class aClass) {
+ if (aClass == boolean.class) {
+ return Boolean.class;
+ }
+
+ if (aClass == byte.class) {
+ return Byte.class;
+ }
+
+ if (aClass == char.class) {
+ return Character.class;
+ }
+
+ if (aClass == short.class) {
+ return Short.class;
+ }
+
+ if (aClass == int.class) {
+ return Integer.class;
+ }
+
+ if (aClass == long.class) {
+ return Long.class;
+ }
+
+ if (aClass == float.class) {
+ return Float.class;
+ }
+
+ if (aClass == double.class) {
+ return Double.class;
+ }
+
+ if (aClass == void.class) {
+ return Void.class;
+ }
+
+ return aClass;
+ }
+
+ public static List<Method> getAllMethods(Class aClass) {
+ Map<String, Method> found = new HashMap<String, Method>();
+ getAllMethods(aClass, found);
+
+ return new ArrayList<Method>(found.values());
+ }
+
+ private static void getAllMethods(Class aClass, Map<String, Method> aFound) {
+ List<Method> declared = Arrays.asList(aClass.getDeclaredMethods());
+
+ for (Method method : declared) {
+ Method superMethod = aFound.get(method.getName());
+
+ if (superMethod == null) {
+ // no superclass method
+ aFound.put(method.getName(), method);
+ } else {
+ // super class method. Check for override.
+ if (!Arrays.equals(superMethod.getParameterTypes(),
+ method.getParameterTypes())) {
+ // parameters differ so this is a new method.
+ aFound.put(method.getName(), method);
+ }
+ }
+ }
+
+ Class superClass = aClass.getSuperclass();
- /**
- * Wraps a type by the corresponding wrapper type if it is a primitive
- * type.
- * @param aClass Type to wrap.
- * @return Wrapped type for primitives or the provided argument value.
- */
- public static Class wrapIfNeeded(Class aClass) {
-
- if (aClass == boolean.class) {
- return Boolean.class;
- }
- if (aClass == byte.class) {
- return Byte.class;
- }
- if (aClass == char.class) {
- return Character.class;
- }
- if (aClass == short.class) {
- return Short.class;
- }
- if (aClass == int.class) {
- return Integer.class;
- }
- if (aClass == long.class) {
- return Long.class;
- }
- if (aClass == float.class) {
- return Float.class;
- }
- if (aClass == double.class) {
- return Double.class;
- }
- if (aClass == void.class) {
- return Void.class;
- }
- return aClass;
- }
-
-
- public static List<Method> getAllMethods(Class aClass) {
-
- Map<String,Method> found = new HashMap<String, Method>();
- getAllMethods(aClass, found);
- return new ArrayList<Method>(found.values());
- }
-
- private static void getAllMethods(Class aClass, Map<String,Method> aFound) {
- List<Method> declared = Arrays.asList(aClass.getDeclaredMethods());
- for (Method method: declared) {
- Method superMethod = aFound.get(method.getName());
- if ( superMethod == null ) {
- // no superclass method
- aFound.put(method.getName(), method);
- }
- else {
- // super class method. Check for override.
- if ( !Arrays.equals(superMethod.getParameterTypes(), method.getParameterTypes())) {
- // parameters differ so this is a new method.
- aFound.put(method.getName(), method);
- }
- }
- }
- Class superClass = aClass.getSuperclass();
- if (superClass != null) {
- getAllMethods(superClass, aFound);
- }
- }
+ if (superClass != null) {
+ getAllMethods(superClass, aFound);
+ }
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.xml;
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.InputResource;
+
import java.io.IOException;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
-import org.wamblee.io.ClassPathResource;
-import org.wamblee.io.InputResource;
/**
* URI resolver that resolves stylesheets through the classpath.
*/
public class ClasspathUriResolver implements URIResolver {
-
- /**
+/**
* Constructs the resolver.
- *
+ *
*/
public ClasspathUriResolver() {
// Empty.
/*
* (non-Javadoc)
- *
+ *
* @see javax.xml.transform.URIResolver#resolve(java.lang.String,
* java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aHref DOCUMENT ME!
+ * @param aBase DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws TransformerException DOCUMENT ME!
+ */
public Source resolve(String aHref, String aBase)
- throws TransformerException {
+ throws TransformerException {
InputResource xslt = new ClassPathResource(aHref);
+
try {
return new StreamSource(xslt.getInputStream());
} catch (IOException e) {
throw new TransformerException(
- "Could not get XSLT style sheet in classpath '" + aHref
- + "'", e);
+ "Could not get XSLT style sheet in classpath '" + aHref + "'", e);
}
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.xml;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.apache.xml.serialize.OutputFormat;
+import org.apache.xml.serialize.XMLSerializer;
+
+import org.dom4j.DocumentException;
+
+import org.dom4j.io.DOMReader;
+import org.dom4j.io.DOMWriter;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import org.xml.sax.SAXException;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.xml.serialize.OutputFormat;
-import org.apache.xml.serialize.XMLSerializer;
-import org.dom4j.DocumentException;
-import org.dom4j.io.DOMReader;
-import org.dom4j.io.DOMWriter;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
/**
* Some basic XML utilities for common reoccuring tasks for DOM documents.
* @author Erik Brakkee
*/
public final class DomUtils {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final Log LOG = LogFactory.getLog(DomUtils.class);
- /**
+/**
* Disabled default constructor.
- *
+ *
*/
private DomUtils() {
// Empty.
/**
* Parses an XML document from a string.
- *
- * @param aDocument
- * document.
+ *
+ * @param aDocument document.
+ *
* @return
+ *
+ * @throws XMLException DOCUMENT ME!
*/
public static Document read(String aDocument) throws XMLException {
ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
+
return read(is);
}
/**
* Parses an XML document from a stream.
- *
- * @param aIs
- * Input stream.
+ *
+ * @param aIs Input stream.
+ *
* @return
+ *
+ * @throws XMLException DOCUMENT ME!
*/
public static Document read(InputStream aIs) throws XMLException {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
- .newDocumentBuilder();
+ .newDocumentBuilder();
+
return builder.parse(aIs);
- } catch (SAXException e) {
+ } catch (SAXException e) {
throw new XMLException(e.getMessage(), e);
} catch (IOException e) {
throw new XMLException(e.getMessage(), e);
/**
* Reads and validates a document against a schema.
- *
- * @param aIs
- * Input stream.
- * @param aSchema
- * Schema.
+ *
+ * @param aIs Input stream.
+ * @param aSchema Schema.
+ *
* @return Parsed and validated document.
+ *
+ * @throws XMLException DOCUMENT ME!
*/
public static Document readAndValidate(InputStream aIs, InputStream aSchema)
- throws XMLException {
-
+ throws XMLException {
try {
- final Schema schema = SchemaFactory.newInstance(
- XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
- new StreamSource(aSchema));
+ final Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
+ .newSchema(new StreamSource(aSchema));
- final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ final DocumentBuilderFactory factory = DocumentBuilderFactory
+ .newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setSchema(schema);
} catch (Exception e) {
LOG.warn("Error closing schema", e);
}
+
try {
aIs.close();
} catch (Exception e) {
LOG.warn("Error closing XML file", e);
}
}
-
}
/**
* Serializes an XML document to a stream.
- *
- * @param aDocument
- * Document to serialize.
- * @param aOs
- * Output stream.
+ *
+ * @param aDocument Document to serialize.
+ * @param aOs Output stream.
+ *
+ * @throws IOException DOCUMENT ME!
*/
public static void serialize(Document aDocument, OutputStream aOs)
- throws IOException {
+ throws IOException {
XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat());
serializer.serialize(aDocument);
}
/**
* Serializes an XML document.
- *
- * @param aDocument
- * Document to serialize.
+ *
+ * @param aDocument Document to serialize.
+ *
* @return Serialized document.
+ *
+ * @throws IOException DOCUMENT ME!
*/
- public static String serialize(Document aDocument) throws IOException {
+ public static String serialize(Document aDocument)
+ throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
serialize(aDocument, os);
+
return os.toString();
}
/**
* Converts a dom4j document into a w3c DOM document.
- *
- * @param aDocument
- * Document to convert.
+ *
+ * @param aDocument Document to convert.
+ *
* @return W3C DOM document.
+ *
+ * @throws DocumentException DOCUMENT ME!
*/
public static Document convert(org.dom4j.Document aDocument)
- throws DocumentException {
+ throws DocumentException {
return new DOMWriter().write(aDocument);
}
/**
* Converts a W3C DOM document into a dom4j document.
- *
- * @param aDocument
- * Document to convert.
+ *
+ * @param aDocument Document to convert.
+ *
* @return Dom4j document.
*/
public static org.dom4j.Document convert(Document aDocument) {
/**
* Removes duplicate attributes from a DOM tree.This is useful for
* postprocessing the output of JTidy as a workaround for a bug in JTidy.
- *
- * @param aNode
- * Node to remove duplicate attributes from (recursively).
- * Attributes of the node itself are not dealt with. Only the
- * child nodes are dealt with.
+ *
+ * @param aNode Node to remove duplicate attributes from (recursively).
+ * Attributes of the node itself are not dealt with. Only the child
+ * nodes are dealt with.
*/
public static void removeDuplicateAttributes(Node aNode) {
NodeList list = aNode.getChildNodes();
+
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
+
if (node instanceof Element) {
removeDuplicateAttributes((Element) node);
removeDuplicateAttributes(node);
/**
* Removes duplicate attributes from an element.
- *
- * @param aElement
- * Element.
+ *
+ * @param aElement Element.
*/
private static void removeDuplicateAttributes(Element aElement) {
- NamedNodeMap attributes = aElement.getAttributes();
+ NamedNodeMap attributes = aElement.getAttributes();
Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
- List<Attr> attlist = new ArrayList<Attr>();
+ List<Attr> attlist = new ArrayList<Attr>();
+
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr) attributes.item(i);
+
if (uniqueAttributes.containsKey(attribute.getNodeName())) {
LOG.info("Detected duplicate attribute (will be removed)'"
- + attribute.getNodeName() + "'");
+ + attribute.getNodeName() + "'");
}
+
uniqueAttributes.put(attribute.getNodeName(), attribute);
attlist.add(attribute);
}
+
// Remove all attributes from the element.
for (Attr att : attlist) {
aElement.removeAttributeNode(att);
}
+
// Add the unique attributes back to the element.
for (Attr att : uniqueAttributes.values()) {
aElement.setAttributeNode(att);
/*
* Copyright 2006 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.xml;
/**
- * Exception thrown in case of XML parsing problems.
+ * Exception thrown in case of XML parsing problems.
*
* @author Erik Brakkee
*/
public class XMLException extends Exception {
-
- public XMLException(String aMsg) {
- super(aMsg);
+/**
+ * Creates a new XMLException object.
+ *
+ * @param aMsg DOCUMENT ME!
+ */
+ public XMLException(String aMsg) {
+ super(aMsg);
}
-
- public XMLException(String aMsg, Throwable aCause) {
+
+/**
+ * Creates a new XMLException object.
+ *
+ * @param aMsg DOCUMENT ME!
+ * @param aCause DOCUMENT ME!
+ */
+ public XMLException(String aMsg, Throwable aCause) {
super(aMsg, aCause);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
-
package org.wamblee.xml;
+import org.w3c.dom.Document;
+
+import org.wamblee.io.FileResource;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
-import org.w3c.dom.Document;
-import org.wamblee.io.FileResource;
/**
* XSL transformer for simplified usage of XSL transformations.
* @author Erik Brakkee
*/
public class XslTransformer {
-
+ /**
+ * DOCUMENT ME!
+ */
private TransformerFactory factory;
- /**
+/**
* Constructs the URL resolver.
- *
+ *
* @param aResolver
* URI resolver to use.
*/
factory.setURIResolver(aResolver);
}
- /**
+/**
* Constructs the XSLT processor.
- *
+ *
*/
public XslTransformer() {
factory = TransformerFactory.newInstance();
}
/**
- * Resolves an XSLT based on URI.
- * @param aXslt XSLT to resolve,
+ * Resolves an XSLT based on URI.
+ *
+ * @param aXslt XSLT to resolve,
+ *
* @return Source for the XSLT
- * @throws TransformerException In case the XSLT cannot be found.
+ *
+ * @throws TransformerException In case the XSLT cannot be found.
*/
public Source resolve(String aXslt) throws TransformerException {
URIResolver resolver = factory.getURIResolver();
+
if (resolver == null) {
if (new File(aXslt).canRead()) {
try {
return new StreamSource(new FileResource(new File(aXslt))
- .getInputStream());
+ .getInputStream());
} catch (IOException e) {
throw new TransformerException(e.getMessage(), e);
}
} else {
- throw new TransformerException("Cannot read '" + aXslt + "'");
+ throw new TransformerException("Cannot read '" + aXslt + "'");
}
}
+
return resolver.resolve(aXslt, "");
}
/**
- * Transforms a DOM document into another DOM document using a given XSLT
- * transformation.
- *
- * @param aDocument
- * Document to transform.
- * @param aXslt
- * XSLT to use.
+ * Transforms a DOM document into another DOM document using a
+ * given XSLT transformation.
+ *
+ * @param aDocument Document to transform.
+ * @param aXslt XSLT to use.
+ *
* @return Transformed document.
- * @throws IOException
- * In case of problems reading resources.
- * @throws TransformerException
- * In case transformation fails.
+ *
+ * @throws IOException In case of problems reading resources.
+ * @throws TransformerException In case transformation fails.
*/
public Document transform(Document aDocument, Source aXslt)
- throws IOException, TransformerException {
- Source source = new DOMSource(aDocument);
+ throws IOException, TransformerException {
+ Source source = new DOMSource(aDocument);
DOMResult result = new DOMResult();
transform(source, result, aXslt);
+
return (Document) result.getNode();
}
/**
* Transforms a document using XSLT.
- *
- * @param aDocument
- * Document to transform.
- * @param aXslt
- * XSLT to use.
+ *
+ * @param aDocument Document to transform.
+ * @param aXslt XSLT to use.
+ *
* @return Transformed document.
- * @throws IOException
- * In case of problems reading resources.
- * @throws TransformerException
- * In case transformation fails.
+ *
+ * @throws IOException In case of problems reading resources.
+ * @throws TransformerException In case transformation fails.
*/
public Document transform(byte[] aDocument, Source aXslt)
- throws IOException, TransformerException {
- Source source = new StreamSource(new ByteArrayInputStream(aDocument));
+ throws IOException, TransformerException {
+ Source source = new StreamSource(new ByteArrayInputStream(aDocument));
DOMResult result = new DOMResult();
transform(source, result, aXslt);
+
return (Document) result.getNode();
}
/**
* Transforms a document to a text output. This supports XSLT
* transformations that result in text documents.
- *
- * @param aDocument
- * Document to transform.
- * @param aXslt
- * XSL transformation.
+ *
+ * @param aDocument Document to transform.
+ * @param aXslt XSL transformation.
+ *
* @return Transformed document.
+ *
+ * @throws IOException DOCUMENT ME!
+ * @throws TransformerException DOCUMENT ME!
*/
public String textTransform(byte[] aDocument, Source aXslt)
- throws IOException, TransformerException {
- Source source = new StreamSource(new ByteArrayInputStream(aDocument));
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- StreamResult result = new StreamResult(os);
+ throws IOException, TransformerException {
+ Source source = new StreamSource(new ByteArrayInputStream(
+ aDocument));
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ StreamResult result = new StreamResult(os);
transform(source, result, aXslt);
+
return new String(os.toByteArray());
}
/**
* Transforms a document using XSLT.
- *
- * @param aSource
- * Document to transform.
- * @param aResult
- * Result of the transformation.
- * @param aXslt
- * XSLT to use.
- * @throws IOException
- * In case of problems reading resources.
- * @throws TransformerException
- * In case transformation fails.
+ *
+ * @param aSource Document to transform.
+ * @param aResult Result of the transformation.
+ * @param aXslt XSLT to use.
+ *
+ * @throws IOException In case of problems reading resources.
+ * @throws TransformerException In case transformation fails.
*/
public void transform(Source aSource, Result aResult, Source aXslt)
- throws IOException, TransformerException {
+ throws IOException, TransformerException {
try {
Transformer transformer = factory.newTransformer(aXslt);
transformer.transform(aSource, aResult);
} catch (TransformerConfigurationException e) {
- throw new TransformerException(
- "Configuration problem of XSLT transformation", e);
+ throw new TransformerException("Configuration problem of XSLT transformation",
+ e);
}
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.cache;
-import java.io.IOException;
-
import junit.framework.TestCase;
+
import net.sf.ehcache.CacheException;
import org.wamblee.io.TestResource;
+
import org.wamblee.test.TimingUtils;
+import java.io.IOException;
+
+
/**
- * Cached object test.
+ * Cached object test.
*
* @author Erik Brakkee
*/
public class CachedObjectTest extends TestCase {
-
/**
- *
+ *
*/
private static final String EHCACHE_CONFIG = "ehcache.xml";
+ private static final int OBJECT_KEY = 10;
+ private CachedObject.Computation<Integer, Integer> computation;
+ private int ncomputations;
- private static final int OBJECT_KEY = 10;
-
- private CachedObject.Computation<Integer,Integer> computation;
- private int ncomputations;
-
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
- computation = new CachedObject.Computation<Integer,Integer>() {
- public Integer getObject(Integer aObjectKey) {
- ncomputations++;
- return compute(aObjectKey);
- };
- };
- ncomputations = 0;
+ computation = new CachedObject.Computation<Integer, Integer>() {
+ public Integer getObject(Integer aObjectKey) {
+ ncomputations++;
+
+ return compute(aObjectKey);
+ }
+ ;
+ };
+ ncomputations = 0;
}
-
- private int compute(int aValue) {
+
+ private int compute(int aValue) {
return aValue + 10;
}
-
- private CachedObject<Integer, Integer> createCached(Cache<Integer,Integer> aCache) {
- return new CachedObject<Integer, Integer>(aCache, OBJECT_KEY, computation);
+
+ private CachedObject<Integer, Integer> createCached(
+ Cache<Integer, Integer> aCache) {
+ return new CachedObject<Integer, Integer>(aCache, OBJECT_KEY,
+ computation);
}
/**
- * Verifies that upon first use, the cached object uses the computation to
- * retrieve the object.
+ * Verifies that upon first use, the cached object uses the computation to
+ * retrieve the object.
*
*/
- public void testComputation() {
- CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer,Integer>());
+ public void testComputation() {
+ CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer, Integer>());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, ncomputations);
+ assertEquals(1, ncomputations);
}
-
- public void testInvalidateCache() {
- CachedObject<Integer, Integer> cached = createCached(new ForeverCache<Integer,Integer>());
+
+ public void testInvalidateCache() {
+ CachedObject<Integer, Integer> cached = createCached(new ForeverCache<Integer, Integer>());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
- cached.invalidate();
+ cached.invalidate();
value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(2, ncomputations);
}
-
+
public void testBehaviorEhCache() throws CacheException, IOException {
- Cache<Integer,Integer> cache = new EhCache<Integer,Integer>(new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "test");
+ Cache<Integer, Integer> cache = new EhCache<Integer, Integer>(new TestResource(
+ CachedObjectTest.class, EHCACHE_CONFIG), "test");
CachedObject<Integer, Integer> cached = createCached(cache);
-
- assertTrue( cache == cached.getCache());
+
+ assertTrue(cache == cached.getCache());
+
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
// The value must still be cached.
- value = cached.get();
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
-
+
// Cache expiry.
- TimingUtils.sleep(6000);
- value = cached.get();
+ TimingUtils.sleep(6000);
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(2, ncomputations);
-
+
// Should still be cached now.
- value = cached.get();
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(2, ncomputations);
-
+
// explicit invalidation.
- cached.invalidate();
- value = cached.get();
+ cached.invalidate();
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(3, ncomputations);
-
}
-
+
public void testBehaviorEhCacheDefault() throws CacheException, IOException {
- Cache<Integer,Integer> cache = new EhCache<Integer,Integer>(new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "undefined");
+ Cache<Integer, Integer> cache = new EhCache<Integer, Integer>(new TestResource(
+ CachedObjectTest.class, EHCACHE_CONFIG), "undefined");
CachedObject<Integer, Integer> cached = createCached(cache);
-
- assertTrue( cache == cached.getCache());
+
+ assertTrue(cache == cached.getCache());
+
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
// The value must still be cached.
- value = cached.get();
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
-
+
// Cache expiry.
- TimingUtils.sleep(6000);
- value = cached.get();
+ TimingUtils.sleep(6000);
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(2, ncomputations);
-
+
// Should still be cached now.
- value = cached.get();
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(2, ncomputations);
-
}
-
-
- public void testBehaviorForeverCache() {
- CachedObject<Integer, Integer> cached = createCached(new ForeverCache<Integer,Integer>());
+
+ public void testBehaviorForeverCache() {
+ CachedObject<Integer, Integer> cached = createCached(new ForeverCache<Integer, Integer>());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, ncomputations);
- for (int ncomp = 2; ncomp <= 100; ncomp++) {
- value = cached.get();
+ assertEquals(1, ncomputations);
+
+ for (int ncomp = 2; ncomp <= 100; ncomp++) {
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(1, ncomputations);
}
}
-
- public void testBehaviorZeroCache() {
- CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer,Integer>());
+
+ public void testBehaviorZeroCache() {
+ CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer, Integer>());
int value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
- assertEquals(1, ncomputations);
- for (int ncomp = 2; ncomp <= 100; ncomp++) {
- value = cached.get();
+ assertEquals(1, ncomputations);
+
+ for (int ncomp = 2; ncomp <= 100; ncomp++) {
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(ncomp, ncomputations);
}
- cached.invalidate();
- value = cached.get();
+
+ cached.invalidate();
+ value = cached.get();
assertEquals(compute(OBJECT_KEY), value);
assertEquals(101, ncomputations);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.collections;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
+import junit.framework.TestCase;
import org.wamblee.conditions.Condition;
+
import org.wamblee.test.AssertionUtils;
-import junit.framework.TestCase;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
-public class CollectionFilterTest extends TestCase {
-
- public void testFilter() {
- List<String> list = Arrays.asList(new String[] { "x", "y", "z", "y" });
- List<String> result = new ArrayList<String>();
- CollectionFilter.filter(list, result,
- new Condition<String>() {
- @Override
- public boolean matches(String aObject) {
- return aObject.equals("y");
- }
- });
- AssertionUtils.assertEquals(new String[] { "y", "y" }, result.toArray());
- }
+public class CollectionFilterTest extends TestCase {
+ public void testFilter() {
+ List<String> list = Arrays.asList(new String[] { "x", "y", "z", "y" });
+ List<String> result = new ArrayList<String>();
+ CollectionFilter.filter(list, result,
+ new Condition<String>() {
+ @Override
+ public boolean matches(String aObject) {
+ return aObject.equals("y");
+ }
+ });
+ AssertionUtils.assertEquals(new String[] { "y", "y" }, result.toArray());
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.concurrency;
+import junit.framework.TestCase;
+
import org.wamblee.test.EventTracker;
import org.wamblee.test.TimingUtils;
-import junit.framework.TestCase;
/**
* Tests for the JVMLock.
* @author Erik Brakkee
*/
public abstract class AbstractLockTestCase extends TestCase {
-
protected static final int SLEEP_TIME = 1000;
-
protected static final String STARTED = "started";
-
protected static final String ACQUIRED = "acquired";
-
protected static final String RELEASED = "released";
-
private EventTracker<String> tracker;
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
tracker = new EventTracker<String>();
}
-
- protected EventTracker<String> getTracker() {
+
+ protected EventTracker<String> getTracker() {
return tracker;
}
/**
- * Must be implemented to generate the events
- * {@link #STARTED}, {@link #ACQUIRED}, and {@link #RELEASED} in
+ * Must be implemented to generate the events
+ * {@link #STARTED}, {@link #ACQUIRED}, and {@link #RELEASED} in
* that order. The lock should be acquired for
* the time specified by {@link #SLEEP_TIME}.
- * @return Thread which does the work.
+ * @return Thread which does the work.
*/
protected abstract Thread runThread();
Thread t1 = runThread();
Thread t2 = runThread();
TimingUtils.sleep(SLEEP_TIME / 10); // give threads a chance to start
- // up.
+ // up.
+
assertEquals(2, tracker.getEventCount(STARTED)); // both threads
- // should have
- // started.
+ // should have
+ // started.
+
assertEquals(1, tracker.getEventCount(ACQUIRED)); // one thread has
- // acquired the
- // lock.
+ // acquired the
+ // lock.
+
TimingUtils.sleep(SLEEP_TIME);
assertEquals(2, tracker.getEventCount(ACQUIRED)); // now the other
- // thread could also
- // acquire the lock
+ // thread could also
+ // acquire the lock
+
assertEquals(1, tracker.getEventCount(RELEASED)); // and the first
- // thread has
- // released it.
+ // thread has
+ // released it.
+
TimingUtils.sleep(SLEEP_TIME);
assertEquals(2, tracker.getEventCount(RELEASED)); // both threads
- // should be
- // finished.
+ // should be
+ // finished.
+
t1.join();
t2.join();
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.concurrency;
import org.wamblee.test.TimingUtils;
+
/**
* Tests for the JVMLock.
*
* @author Erik Brakkee
*/
public class JvmLockTest extends AbstractLockTestCase {
-
private JvmLock lock;
-
+
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
@Override
protected Thread runThread() {
Thread t = new Thread(new Runnable() {
- public void run() {
- getTracker().eventOccurred(STARTED);
- lock.acquire();
- getTracker().eventOccurred(ACQUIRED);
- TimingUtils.sleep(SLEEP_TIME);
- lock.release();
- getTracker().eventOccurred(RELEASED);
- };
- });
+ public void run() {
+ getTracker().eventOccurred(STARTED);
+ lock.acquire();
+ getTracker().eventOccurred(ACQUIRED);
+ TimingUtils.sleep(SLEEP_TIME);
+ lock.release();
+ getTracker().eventOccurred(RELEASED);
+ }
+ ;
+ });
t.start();
+
return t;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.concurrency;
import junit.framework.Assert;
*/
public class ReadWriteLockTest extends TestCase {
/**
- *
+ *
*/
private static final int HALF_SECOND = 500;
+
/**
- *
+ *
*/
private static final int ONE_SECOND = 1000;
+
/**
- *
+ *
*/
private static final int TWO_SECONDS = 2000;
private ReadWriteLock lock;
- private int nReaders;
- private int nWriters;
+ private int nReaders;
+ private int nWriters;
/**
* Constructor for ReadWriteLockTest.
public void testMultipleReaders() throws InterruptedException {
Runnable runnable = new ReadLocker(lock, this, TWO_SECONDS);
- Thread t1 = new Thread(runnable);
+ Thread t1 = new Thread(runnable);
t1.start();
Thread t2 = new Thread(runnable);
*/
public void testSingleWriter() throws InterruptedException {
WriteLocker writer = new WriteLocker(lock, this, ONE_SECOND);
- Thread t1 = new Thread(writer);
- Thread t2 = new Thread(writer);
+ Thread t1 = new Thread(writer);
+ Thread t2 = new Thread(writer);
t1.start();
t2.start();
* @throws InterruptedException May not occur.
*/
public void testMultipleWriters() throws InterruptedException {
- WriteLocker writer1 = new WriteLocker(lock, this, HALF_SECOND + ONE_SECOND);
+ WriteLocker writer1 = new WriteLocker(lock, this,
+ HALF_SECOND + ONE_SECOND);
WriteLocker writer2 = new WriteLocker(lock, this, ONE_SECOND);
- Thread t1 = new Thread(writer1);
- Thread t2 = new Thread(writer2);
+ Thread t1 = new Thread(writer1);
+ Thread t2 = new Thread(writer2);
t1.start();
Thread.sleep(HALF_SECOND);
* @throws InterruptedException May not occur.
*/
public void testReadWrite1() throws InterruptedException {
- ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS);
- Thread t1 = new Thread(readLocker);
+ ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS);
+ Thread t1 = new Thread(readLocker);
WriteLocker writeLocker = new WriteLocker(lock, this, TWO_SECONDS);
- Thread t2 = new Thread(writeLocker);
+ Thread t2 = new Thread(writeLocker);
t1.start(); // acquire read lock
Thread.sleep(HALF_SECOND);
* @throws InterruptedException May not occur.
*/
public void testReadWrite2() throws InterruptedException {
- ReadLocker readLocker1 = new ReadLocker(lock, this, TWO_SECONDS + HALF_SECOND);
- ReadLocker readLocker2 = new ReadLocker(lock, this, TWO_SECONDS + HALF_SECOND);
- Thread t1 = new Thread(readLocker1);
- Thread t2 = new Thread(readLocker2);
+ ReadLocker readLocker1 = new ReadLocker(lock, this,
+ TWO_SECONDS + HALF_SECOND);
+ ReadLocker readLocker2 = new ReadLocker(lock, this,
+ TWO_SECONDS + HALF_SECOND);
+ Thread t1 = new Thread(readLocker1);
+ Thread t2 = new Thread(readLocker2);
WriteLocker writeLocker = new WriteLocker(lock, this, TWO_SECONDS);
- Thread t3 = new Thread(writeLocker);
+ Thread t3 = new Thread(writeLocker);
t1.start(); // acquire read lock [0, 2.5]
Thread.sleep(ONE_SECOND);
* @throws InterruptedException May not occur.
*/
public void testReadWrite3() throws InterruptedException {
- ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS);
- Thread t1 = new Thread(readLocker);
+ ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS);
+ Thread t1 = new Thread(readLocker);
WriteLocker writeLocker = new WriteLocker(lock, this, TWO_SECONDS);
- Thread t2 = new Thread(writeLocker);
+ Thread t2 = new Thread(writeLocker);
t2.start(); // acquire write lock
Thread.sleep(HALF_SECOND);
* lock, and performs a callback after the lock has been released.
*/
class ReadLocker implements Runnable {
- private ReadWriteLock lock;
+ private ReadWriteLock lock;
private ReadWriteLockTest lockTest;
- private int sleepTime;
+ private int sleepTime;
public ReadLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest,
int aSleepTime) {
- lock = aLock;
- lockTest = aLockTest;
- sleepTime = aSleepTime;
+ lock = aLock;
+ lockTest = aLockTest;
+ sleepTime = aSleepTime;
}
public void run() {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
- Assert.fail("ReadLocker thread was interrupted."
- + Thread.currentThread());
+ Assert.fail("ReadLocker thread was interrupted." +
+ Thread.currentThread());
}
lock.releaseRead();
* lock, and performs a callback after the lock has been released.
*/
class WriteLocker implements Runnable {
- private ReadWriteLock lock;
+ private ReadWriteLock lock;
private ReadWriteLockTest lockTest;
- private int sleepTime;
+ private int sleepTime;
public WriteLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest,
int aSleepTime) {
- lock = aLock;
- lockTest = aLockTest;
- sleepTime = aSleepTime;
+ lock = aLock;
+ lockTest = aLockTest;
+ sleepTime = aSleepTime;
}
public void run() {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
- Assert.fail("WriteLocker thread was interrupted: "
- + Thread.currentThread());
+ Assert.fail("WriteLocker thread was interrupted: " +
+ Thread.currentThread());
}
lock.releaseWrite();
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
+import junit.framework.TestCase;
+
import java.util.ArrayList;
import java.util.List;
-import junit.framework.TestCase;
/**
- * Tests the Or Condition.
+ * Tests the Or Condition.
*
* @author Erik Brakkee
*/
public class AndConditionTest extends TestCase {
-
- public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) {
- AndCondition<Integer> and = new AndCondition<Integer>(new FixedCondition<Integer>(aFirst),
- new FixedCondition<Integer>(aSecond));
+ public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) {
+ AndCondition<Integer> and = new AndCondition<Integer>(new FixedCondition<Integer>(
+ aFirst), new FixedCondition<Integer>(aSecond));
assertEquals(aResult, and.matches(0));
}
-
- public void checkResult(boolean[] aValues, boolean aResult) {
+
+ public void checkResult(boolean[] aValues, boolean aResult) {
List<Condition<Integer>> conditions = new ArrayList<Condition<Integer>>();
- for (boolean value: aValues) {
- conditions.add(new FixedCondition<Integer>(value));
+
+ for (boolean value : aValues) {
+ conditions.add(new FixedCondition<Integer>(value));
}
+
AndCondition<Integer> and = new AndCondition<Integer>(conditions);
assertEquals(aResult, and.matches(new Integer(0)));
}
/**
- * Checks all combinations of two conditions.
+ * Checks all combinations of two conditions.
*
*/
- public void testTwoConditions() {
+ public void testTwoConditions() {
checkResult(false, false, false);
checkResult(true, false, false);
- checkResult(false, true, false);
+ checkResult(false, true, false);
checkResult(true, true, true);
}
-
- public void testMultipleConditions() {
- checkResult(new boolean[]{ false, false, false} , false);
- checkResult(new boolean[]{ true, false, false }, false);
- checkResult(new boolean[]{ false, true, false }, false);
- checkResult(new boolean[]{ false, false, true }, false);
- checkResult(new boolean[]{ true, true, true }, true);
+
+ public void testMultipleConditions() {
+ checkResult(new boolean[] { false, false, false }, false);
+ checkResult(new boolean[] { true, false, false }, false);
+ checkResult(new boolean[] { false, true, false }, false);
+ checkResult(new boolean[] { false, false, true }, false);
+ checkResult(new boolean[] { true, true, true }, true);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
+
/**
- * Test condition object.
+ * Test condition object.
*
* @author Erik Brakkee
*/
public class GreaterThanCondition implements Condition<Integer> {
-
- private int value;
-
- public GreaterThanCondition(int aValue) {
- value = aValue;
+ private int value;
+
+ public GreaterThanCondition(int aValue) {
+ value = aValue;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.conditions.Condition#matches(T)
*/
public boolean matches(Integer aObject) {
- return aObject > value;
+ return aObject > value;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
+
/**
- * Test condition object.
+ * Test condition object.
*
* @author Erik Brakkee
*/
public class LessThanCondition implements Condition<Integer> {
-
- private int value;
-
- public LessThanCondition(int aValue) {
- value = aValue;
+ private int value;
+
+ public LessThanCondition(int aValue) {
+ value = aValue;
}
-
+
/* (non-Javadoc)
* @see org.wamblee.conditions.Condition#matches(T)
*/
public boolean matches(Integer aObject) {
- return aObject < value;
+ return aObject < value;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
+import junit.framework.TestCase;
+
import java.util.ArrayList;
import java.util.List;
-import junit.framework.TestCase;
/**
- * Tests the Or Condition.
+ * Tests the Or Condition.
*
* @author Erik Brakkee
*/
public class OrConditionTest extends TestCase {
-
- public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) {
- OrCondition<Integer> or = new OrCondition<Integer>(new FixedCondition<Integer>(aFirst),
- new FixedCondition<Integer>(aSecond));
+ public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) {
+ OrCondition<Integer> or = new OrCondition<Integer>(new FixedCondition<Integer>(
+ aFirst), new FixedCondition<Integer>(aSecond));
assertEquals(aResult, or.matches(0));
}
-
- public void checkResult(boolean[] aValues, boolean aResult) {
+
+ public void checkResult(boolean[] aValues, boolean aResult) {
List<Condition<Integer>> conditions = new ArrayList<Condition<Integer>>();
- for (boolean value: aValues) {
- conditions.add(new FixedCondition<Integer>(value));
+
+ for (boolean value : aValues) {
+ conditions.add(new FixedCondition<Integer>(value));
}
+
OrCondition<Integer> or = new OrCondition<Integer>(conditions);
assertEquals(aResult, or.matches(new Integer(0)));
}
/**
- * Checks all combinations of two conditions.
+ * Checks all combinations of two conditions.
*
*/
- public void testTwoConditions() {
+ public void testTwoConditions() {
checkResult(false, false, false);
checkResult(true, false, true);
- checkResult(false, true, true);
+ checkResult(false, true, true);
checkResult(true, true, true);
}
-
- public void testMultipleConditions() {
- checkResult(new boolean[]{ false, false, false} , false);
- checkResult(new boolean[]{ true, false, false }, true);
- checkResult(new boolean[]{ false, true, false }, true);
- checkResult(new boolean[]{ false, false, true }, true);
- checkResult(new boolean[]{ true, true, true }, true);
+
+ public void testMultipleConditions() {
+ checkResult(new boolean[] { false, false, false }, false);
+ checkResult(new boolean[] { true, false, false }, true);
+ checkResult(new boolean[] { false, true, false }, true);
+ checkResult(new boolean[] { false, false, true }, true);
+ checkResult(new boolean[] { true, true, true }, true);
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
import junit.framework.TestCase;
+
/**
- * Tests {@link org.wamblee.conditions.PropertyRegexCondition}.
+ * Tests {@link org.wamblee.conditions.PropertyRegexCondition}.
*
* @author Erik Brakkee
*/
public class PropertyRegexConditionTest extends TestCase {
-
- private boolean match(String aProperty, String aRegex, boolean aToLower, TestBean aBean) {
- PropertyRegexCondition<TestBean> condition = new PropertyRegexCondition<TestBean>(aProperty, aRegex, aToLower );
+ private boolean match(String aProperty, String aRegex, boolean aToLower,
+ TestBean aBean) {
+ PropertyRegexCondition<TestBean> condition = new PropertyRegexCondition<TestBean>(aProperty,
+ aRegex, aToLower);
+
return condition.matches(aBean);
}
-
- private void checkMatch(String aProperty, String aRegex, boolean aToLower, TestBean aBean, boolean aResult) {
- assertEquals( aResult, match(aProperty, aRegex, aToLower, aBean));
+
+ private void checkMatch(String aProperty, String aRegex, boolean aToLower,
+ TestBean aBean, boolean aResult) {
+ assertEquals(aResult, match(aProperty, aRegex, aToLower, aBean));
}
-
+
/**
- * Verifies correct matching behavior for several cases.
+ * Verifies correct matching behavior for several cases.
*
*/
public void testMatchProperty() {
- TestBean bean = new TestBean("Hallo");
- checkMatch("value", "Hallo", false, bean, true);
+ TestBean bean = new TestBean("Hallo");
+ checkMatch("value", "Hallo", false, bean, true);
checkMatch("value", "all", false, bean, false);
checkMatch("value", ".a.*o", false, bean, true);
checkMatch("value", "hallo", false, bean, false); // no match when not converting to lower case.
checkMatch("value", "hallo", true, bean, true); // match!
}
-
+
/**
- * Uses property regex condition for non-existing property.
- * Verifies that a runtime exception is thrown.
+ * Uses property regex condition for non-existing property.
+ * Verifies that a runtime exception is thrown.
*
*/
- public void testWrongProperty() {
+ public void testWrongProperty() {
TestBean bean = new TestBean("Hallo");
- try {
- match("bla", ".*", false, bean);
- } catch (RuntimeException e) {
- return; // ok
+
+ try {
+ match("bla", ".*", false, bean);
+ } catch (RuntimeException e) {
+ return; // ok
}
+
fail();
}
-
+
/**
- * Applies condition to a private property. Verifies that a runtime
- * exception is thrown.
+ * Applies condition to a private property. Verifies that a runtime
+ * exception is thrown.
*
*/
- public void testPrivateProperty() {
+ public void testPrivateProperty() {
TestBean bean = new TestBean("Hallo");
- try {
- match("privateValue", ".*", false, bean);
- } catch (RuntimeException e) {
- return; // ok
+
+ try {
+ match("privateValue", ".*", false, bean);
+ } catch (RuntimeException e) {
+ return; // ok
}
+
fail();
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.conditions;
+
/**
- *
+ *
*
* @author Erik Brakkee
*/
public class TestBean {
+ private String value;
- private String value;
-
- public TestBean(String aValue) {
- value = aValue;
+ public TestBean(String aValue) {
+ value = aValue;
}
-
- public String getValue() {
- return value;
+
+ public String getValue() {
+ return value;
}
-
- private String getPrivateValue() {
- return value;
+
+ private String getPrivateValue() {
+ return value;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.general;
import junit.framework.TestCase;
+
/**
* Tests the bean kernel. The lookup of the bean factory itself can be tested
* only partially. Using a global property file for all test cases would tie all
* @author Erik Brakkee
*/
public class BeanKernelTest extends TestCase {
-
/**
* Loads the bean factory based on a property file configuration. Verifies
* the correct bean factory is loaded.
- *
+ *
*/
public void testLoadBeanFactoryFromProperties() {
- BeanFactory factory = BeanKernel
- .lookupBeanFactory("org/wamblee/general/beankernel.properties");
+ BeanFactory factory = BeanKernel.lookupBeanFactory(
+ "org/wamblee/general/beankernel.properties");
assertTrue(factory instanceof TestBeanFactory);
}
/**
- * Loads the bean factory based on a non-existing property file.
- * Verifies that BeanFactoryException is thrown.
- *
+ * Loads the bean factory based on a non-existing property file.
+ * Verifies that BeanFactoryException is thrown.
+ *
*/
public void testNonExistentPropertyFile() {
try {
- BeanKernel
- .lookupBeanFactory("org/wamblee/general/beankernel-nonexistent.properties");
+ BeanKernel.lookupBeanFactory(
+ "org/wamblee/general/beankernel-nonexistent.properties");
} catch (BeanFactoryException e) {
return; // ok
}
+
fail();
}
-
+
/**
* Loads the bean factory based on a property file with a non-existing
- * bean factory defined in it.
- * Verifies that BeanFactoryException is thrown.
- *
+ * bean factory defined in it.
+ * Verifies that BeanFactoryException is thrown.
+ *
*/
public void testNonExistentBeanFactory() {
try {
- BeanKernel
- .lookupBeanFactory("org/wamblee/general/beankernel-wrong.properties");
+ BeanKernel.lookupBeanFactory(
+ "org/wamblee/general/beankernel-wrong.properties");
} catch (BeanFactoryException e) {
return; // ok
}
+
fail();
}
-
/**
* Retrieves a bean factory throug the bean kernel. Verifies that beans can
* be retrieved.
- *
+ *
*/
public void testRetrieveFactory() {
BeanKernel.overrideBeanFactory(new TestBeanFactory()); // bypass
- // default
- // property
- // lookup
+ // default
+ // property
+ // lookup
+
BeanFactory factory = BeanKernel.getBeanFactory();
assertNotNull(factory);
assertEquals("hello", factory.find(String.class));
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.general;
import junit.framework.TestCase;
+
/**
- * Tests the pair class.
+ * Tests the pair class.
*/
public class PairTest extends TestCase {
-
- public void testPair() {
- Pair<Integer, String> pair = new Pair<Integer, String>(10, "hello");
+ public void testPair() {
+ Pair<Integer, String> pair = new Pair<Integer, String>(10, "hello");
assertEquals(new Integer(10), pair.getFirst());
assertEquals("hello", pair.getSecond());
-
+
Pair<Integer, String> pair2 = new Pair<Integer, String>(pair);
assertEquals(new Integer(10), pair2.getFirst());
assertEquals("hello", pair2.getSecond());
-
-
}
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.general;
public class TestBeanFactory implements BeanFactory {
+ @Override
+ public Object find(String aId) {
+ return null;
+ }
- @Override
- public Object find(String aId) {
- return null;
- }
+ @Override
+ public <T> T find(Class<T> aClass) {
+ if (aClass.equals(String.class)) {
+ return (T) "hello";
+ }
- @Override
- public <T> T find(Class<T> aClass) {
- if ( aClass.equals(String.class)) {
- return (T)"hello";
- }
- return null;
- }
-
- @Override
- public <T> T find(String aId, Class<T> aClass) {
- return null;
- }
+ return null;
+ }
+ @Override
+ public <T> T find(String aId, Class<T> aClass) {
+ return null;
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.io;
+import junit.framework.TestCase;
+
import java.io.IOException;
import java.io.InputStream;
-import junit.framework.TestCase;
-
/**
* Tests for the classpath resource.
*/
public class ClassPathResourceTest extends TestCase {
-
/**
* Loads an existing resource from the class path. Verifies it is found.
- *
+ *
*/
public void testResourceFound() throws IOException {
ClassPathResource resource = new ClassPathResource(
/**
* Loads a non-existing resource from the class path. Verifies that an IO
* exception is thrown.
- *
+ *
*/
public void testResourceNotFound() {
try {
} catch (IOException e) {
return; // ok
}
+
fail();
}
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.io;
-import static org.mockito.Mockito.*;
import junit.framework.TestCase;
import org.apache.oro.io.AwkFilenameFilter;
-
+import static org.mockito.Mockito.*;
public class DirectoryMonitorTest extends TestCase {
-
- private static final String REGEX = "^.*\\.txt$";
- private static final String FILE1 = "file1.txt";
-
- private TestData data;
- private DirectoryMonitor.Listener listener;
-
- private DirectoryMonitor monitor;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- data = new TestData(this);
- data.clean();
- listener = mock(DirectoryMonitor.Listener.class);
- monitor = new DirectoryMonitor(data.getRoot(), new AwkFilenameFilter(
- REGEX), listener);
- }
-
- public void testEmptyDir() {
- // Nothing is expected to be called.
- for (int i = 0; i < 10; i++) {
- monitor.poll();
- verifyNoMoreInteractions(listener);
- }
- }
-
- public void testFileCreated() {
- data.createFile(FILE1, "hello");
- monitor.poll();
- verify(listener).fileCreated(data.getFile(FILE1));
- }
-
- public void testFileDeleted() {
- data.createFile(FILE1, "hello");
- monitor.poll();
- reset(listener);
-
- data.deleteFile(FILE1);
- monitor.poll();
-
- verify(listener).fileDeleted(data.getFile(FILE1));
- verifyNoMoreInteractions(listener);
- }
-
- public void testFileChanged() throws InterruptedException {
- data.createFile(FILE1, "hello");
- monitor.poll();
- reset(listener);
-
- Thread.sleep(2000);
- data.deleteFile(FILE1);
- data.createFile(FILE1, "bla");
-
- monitor.poll();
- verify(listener).fileChanged(data.getFile(FILE1));
- verifyNoMoreInteractions(listener);
- }
-
- public void testFileFilterIsUsed() {
- monitor.poll();
-
- data.createFile("file.xml", "hello");
- monitor.poll();
- verifyNoMoreInteractions(listener);
- }
-
- public void testDirectoryIsIgnored() {
- monitor.poll();
- data.createDir(FILE1);
- monitor.poll();
- verifyNoMoreInteractions(listener);
- }
-
- public void testExceptionsWIllLeadToRepeatedNotifications() {
- monitor.poll();
- data.createFile(FILE1, "hello");
-
- stubVoid(listener).toThrow(new RuntimeException()).on().
- fileCreated(data.getFile(FILE1));
-
- try {
- monitor.poll();
- } catch (RuntimeException e) {
- reset(listener);
-
- // polling again should lead to the same filecreated call.
- // this time no exception is thrown.
-
- monitor.poll();
- verify(listener).fileCreated(data.getFile(FILE1));
- verifyNoMoreInteractions(listener);
- return;
- }
- fail(); // should not get here.
-
-
- }
+ private static final String REGEX = "^.*\\.txt$";
+ private static final String FILE1 = "file1.txt";
+ private TestData data;
+ private DirectoryMonitor.Listener listener;
+ private DirectoryMonitor monitor;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ data = new TestData(this);
+ data.clean();
+ listener = mock(DirectoryMonitor.Listener.class);
+ monitor = new DirectoryMonitor(data.getRoot(),
+ new AwkFilenameFilter(REGEX), listener);
+ }
+
+ public void testEmptyDir() {
+ // Nothing is expected to be called.
+ for (int i = 0; i < 10; i++) {
+ monitor.poll();
+ verifyNoMoreInteractions(listener);
+ }
+ }
+
+ public void testFileCreated() {
+ data.createFile(FILE1, "hello");
+ monitor.poll();
+ verify(listener).fileCreated(data.getFile(FILE1));
+ }
+
+ public void testFileDeleted() {
+ data.createFile(FILE1, "hello");
+ monitor.poll();
+ reset(listener);
+
+ data.deleteFile(FILE1);
+ monitor.poll();
+
+ verify(listener).fileDeleted(data.getFile(FILE1));
+ verifyNoMoreInteractions(listener);
+ }
+
+ public void testFileChanged() throws InterruptedException {
+ data.createFile(FILE1, "hello");
+ monitor.poll();
+ reset(listener);
+
+ Thread.sleep(2000);
+ data.deleteFile(FILE1);
+ data.createFile(FILE1, "bla");
+
+ monitor.poll();
+ verify(listener).fileChanged(data.getFile(FILE1));
+ verifyNoMoreInteractions(listener);
+ }
+
+ public void testFileFilterIsUsed() {
+ monitor.poll();
+
+ data.createFile("file.xml", "hello");
+ monitor.poll();
+ verifyNoMoreInteractions(listener);
+ }
+
+ public void testDirectoryIsIgnored() {
+ monitor.poll();
+ data.createDir(FILE1);
+ monitor.poll();
+ verifyNoMoreInteractions(listener);
+ }
+
+ public void testExceptionsWIllLeadToRepeatedNotifications() {
+ monitor.poll();
+ data.createFile(FILE1, "hello");
+
+ stubVoid(listener).toThrow(new RuntimeException()).on()
+ .fileCreated(data.getFile(FILE1));
+
+ try {
+ monitor.poll();
+ } catch (RuntimeException e) {
+ reset(listener);
+
+ // polling again should lead to the same filecreated call.
+ // this time no exception is thrown.
+ monitor.poll();
+ verify(listener).fileCreated(data.getFile(FILE1));
+ verifyNoMoreInteractions(listener);
+
+ return;
+ }
+
+ fail(); // should not get here.
+ }
}
/*
* Copyright 2006 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.io;
+import org.apache.oro.io.AwkFilenameFilter;
+
import java.io.File;
-import org.apache.oro.io.AwkFilenameFilter;
/**
- *
+ *
*
* @author Erik Brakkee
*/
public class DirectoryMonitorTestProgram {
-
- public static void main(String[] aArgs) throws Exception {
-
- DirectoryMonitor monitor = new DirectoryMonitor(new File("."),
- new AwkFilenameFilter(".*\\.txt"), new DirectoryMonitor.Listener() {
- public void fileChanged(File aFile) {
- System.out.println("changed " + aFile);
- }
- public void fileCreated(File aFile) {
- System.out.println("created " + aFile);
- }
- public void fileDeleted(File aFile) {
- System.out.println("deleted " + aFile);
- }
- });
-
- for (;;) {
+ public static void main(String[] aArgs) throws Exception {
+ DirectoryMonitor monitor = new DirectoryMonitor(new File("."),
+ new AwkFilenameFilter(".*\\.txt"),
+ new DirectoryMonitor.Listener() {
+ public void fileChanged(File aFile) {
+ System.out.println("changed " + aFile);
+ }
+
+ public void fileCreated(File aFile) {
+ System.out.println("created " + aFile);
+ }
+
+ public void fileDeleted(File aFile) {
+ System.out.println("deleted " + aFile);
+ }
+ });
+
+ for (;;) {
monitor.poll();
Thread.sleep(1000);
}
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.io;
+import junit.framework.TestCase;
+
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
-import junit.framework.TestCase;
-
/**
- * Tests the file resource.
+ * Tests the file resource.
*
* @author Erik Brakkee
*/
public class FileResourceTest extends TestCase {
-
/**
* Loads an existing resource. Verifies it is found.
- *
+ *
*/
public void testResourceFound() throws IOException {
- FileResource resource = new FileResource( new File(
- FileSystemUtils.getTestInputDir(FileResourceTest.class),
- "myresource.txt"));
+ FileResource resource = new FileResource(new File(
+ FileSystemUtils.getTestInputDir(FileResourceTest.class),
+ "myresource.txt"));
InputStream is = resource.getInputStream();
String data = FileSystemUtils.read(is);
assertEquals("This is my resource", data);
/**
* Loads a non-existing resource. Verifies that an IO
* exception is thrown.
- *
+ *
*/
public void testResourceNotFound() {
try {
- FileResource resource = new FileResource( new File(
- FileSystemUtils.getTestInputDir(FileResourceTest.class),
- "myresource-nonexistent.txt"));
+ FileResource resource = new FileResource(new File(
+ FileSystemUtils.getTestInputDir(FileResourceTest.class),
+ "myresource-nonexistent.txt"));
InputStream is = resource.getInputStream();
} catch (IOException e) {
return; // ok
}
+
fail();
}
}
/*
* Copyright 2006 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.io;
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
+
import java.net.URL;
import java.net.URLDecoder;
+
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
+
import java.security.CodeSource;
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
/**
* File system utilities.
- *
+ *
* @author Erik Brakkee
*/
public final class FileSystemUtils {
-
- private static final Log LOG = LogFactory.getLog(FileSystemUtils.class);
-
- /**
- * Test output directory relative to the sub project.
- */
- private static final String TEST_OUTPUT_DIR = "../target/testoutput";
-
- /**
- * Test input directory relative to the sub project.
- */
- private static final String TEST_INPUT_DIR = "../src/test/resources";
-
- /*
- * Disabled.
- *
- */
- private FileSystemUtils() {
- // Empty
- }
-
- /**
- * Deletes a directory recursively. The test case will fail if the directory
- * does not exist or if deletion fails.
- *
- * @param aDir
- * Directory to delete.
- */
- public static void deleteDirRecursively(String aDir) {
- deleteDirRecursively(new File(aDir));
- }
-
- /**
- * Deletes a directory recursively. See {@link #deleteDirRecursively}.
- *
- * @param aDir
- * Directory.
- */
- public static void deleteDirRecursively(File aDir) {
- TestCase.assertTrue(aDir.isDirectory());
-
- for (File file : aDir.listFiles()) {
- if (file.isDirectory()) {
- deleteDirRecursively(file);
- } else {
- delete(file);
- }
- }
-
- delete(aDir);
- }
-
- /**
- * Deletes a file or directory. The test case will fail if the file or
- * directory does not exist or if deletion fails. Deletion of a non-empty
- * directory will always fail.
- *
- * @param aFile
- * File or directory to delete.
- */
- public static void delete(File aFile) {
- TestCase.assertTrue(aFile.delete());
- }
-
- /**
- * Gets a path relative to a sub project. This utility should be used to
- * easily access file paths within a subproject without requiring any
- * specific Eclipse configuration.
- *
- * @param aRelativePath
- * Relative path.
- * @param aTestClass
- * Test class.
- */
- public static File getPath(String aRelativePath, Class aTestClass) {
- CodeSource source = aTestClass.getProtectionDomain().getCodeSource();
- if (source == null) {
- LOG.warn("Could not obtain path for '" + aRelativePath
- + "' for class " + aTestClass
- + ", using relative path as is");
- return new File(aRelativePath);
- }
- URL location = source.getLocation();
- String protocol = location.getProtocol();
- if (!protocol.equals("file")) {
- LOG.warn("protocol is not 'file': " + location);
- return new File(aRelativePath);
- }
-
- String path = location.getPath();
- try {
- path = URLDecoder.decode(location.getPath(), "UTF-8");
- } catch (UnsupportedEncodingException e) {
- // ignore it.. just don't decode
- LOG.warn("Decoding path failed: '" + location.getPath() + "'", e);
- }
-
- return new File(new File(path).getParentFile(), aRelativePath);
- }
-
- /**
- * Ensures that a directory hierarchy exists (recursively if needed). If it
- * is not possible to create the directory, then the test case will fail.
- *
- * @param aDir
- * Directory to create.
- */
- public static void createDir(File aDir) {
- if (aDir.exists() && !aDir.isDirectory()) {
- TestCase.fail("'" + aDir
- + "' already exists and is not a directory");
- }
- if (aDir.exists()) {
- return;
- }
- createDir(aDir.getParentFile());
- TestCase.assertTrue("Could not create '" + aDir + "'", aDir.mkdir());
- }
-
- /**
- * Creates a file in a directory.
- * @param aDir Directory path. Will be created if it does not exist.
- * @param aName Filename.
- * @param aContents Contents.
- */
- public static void createFile(File aDir, String aName, InputStream aContents) {
- createDir(aDir);
- try {
- OutputStream os = new FileOutputStream(new File(aDir, aName));
- copyStream(aContents, os);
- } catch (IOException e) {
- e.printStackTrace();
- TestCase.fail(e.getMessage());
- }
- }
-
- /**
- * Gets the test output directory for a specific test class.
- *
- * @param aTestClass
- * Test class.
- * @return Test output directory.
- */
- public static File getTestOutputDir(Class aTestClass) {
- File file = getPath(TEST_OUTPUT_DIR, aTestClass);
- String className = aTestClass.getName();
- String classRelPath = className.replaceAll("\\.", "/");
- return new File(file, classRelPath);
- }
-
- /**
- * Gets the test input directory for a specific test class.
- *
- * @param aTestClass
- * Test class.
- * @return Test input directory.
- */
- public static File getTestInputDir(Class aTestClass) {
- File file = getPath(TEST_INPUT_DIR, aTestClass);
- String packageName = aTestClass.getPackage().getName();
- String packagePath = packageName.replaceAll("\\.", "/");
- return new File(file, packagePath);
- }
-
- /**
- * Creates a directory hierarchy for the output directory of a test class if
- * needed.
- *
- * @param aTestClass
- * Test class
- * @return Test directory.
- */
- public static File createTestOutputDir(Class aTestClass) {
- File file = getTestOutputDir(aTestClass);
- createDir(file);
- return file;
- }
-
- /**
- * Gets a test output file name. This returns a File object representing the
- * output file and ensures that the directory where the file will be created
- * already exists.
- *
- * @param aName
- * Name of the file.
- * @param aTestClass
- * Test class.
- * @return File.
- */
- public static File getTestOutputFile(String aName, Class aTestClass) {
- File file = new File(getTestOutputDir(aTestClass), aName);
- createDir(file.getParentFile());
- return file;
- }
-
- public static String read(InputStream aIs) throws IOException {
- try {
- StringBuffer buffer = new StringBuffer();
- int c;
- while ((c = aIs.read()) != -1) {
- buffer.append((char) c);
- }
- return buffer.toString();
- } finally {
- aIs.close();
- }
- }
-
- /**
- * Copies an input stream to an output stream.
- *
- * @param aIs
- * Input stream.
- * @param aOs
- * Output stream.
- */
- public static void copyStream(InputStream aIs, OutputStream aOs) {
- try {
- int c;
- while ((c = aIs.read()) != -1) {
- aOs.write(c);
- }
- aIs.close();
- aOs.close();
- } catch (IOException e) {
- e.printStackTrace();
- Assert.fail(e.getMessage());
- }
- }
-
- /**
- * Recursively copy a directory.
- *
- * @param aSrc
- * Source directory
- * @param aTarget
- * Target directory.
- */
- public static void copyDir(File aSrc, File aTarget) {
- Assert.assertTrue(aSrc.isDirectory());
- Assert.assertTrue(!aTarget.exists());
-
- aTarget.mkdirs();
-
- File[] files = aSrc.listFiles();
- for (int i = 0; i < files.length; i++) {
- File file = files[i];
- if (file.isDirectory()) {
- if (!file.getName().equals(".svn")) {
- copyDir(new File(aSrc, file.getName()), new File(aTarget,
- file.getName()));
- }
- } else {
- copyFile(file, new File(aTarget, file.getName()));
- }
- }
- }
-
- /**
- * Copy a file. If copying fails then the testcase will fail.
- *
- * @param aSrc
- * Source file.
- * @param aTarget
- * Target file.
- */
- public static void copyFile(File aSrc, File aTarget) {
-
- try {
- FileInputStream fis = new FileInputStream(aSrc);
- FileOutputStream fos = new FileOutputStream(aTarget);
- FileChannel fcin = fis.getChannel();
- FileChannel fcout = fos.getChannel();
-
- // map input file
-
- MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0,
- fcin.size());
-
- // do the file copy
- fcout.write(mbb);
-
- // finish up
-
- fcin.close();
- fcout.close();
- fis.close();
- fos.close();
- } catch (IOException e) {
- Assert.assertTrue("Copying file " + aSrc.getPath() + " to "
- + aTarget.getPath() + " failed.", false);
- }
- }
-
- /**
- * Remove all files within a given directory including the directory itself.
- * This only attempts to remove regular files and not directories within the
- * directory. If the directory contains a nested directory, the deletion
- * will fail. The test case will fail if this fails.
- *
- * @param aDir
- * Directory to remove.
- */
- public static void deleteDir(File aDir) {
- cleanDir(aDir);
- delete(aDir);
- }
-
- /**
- * Remove all regular files within a given directory.
- *
- * @param outputDirName
- */
- public static void cleanDir(File aDir) {
- if (!aDir.exists()) {
- return; // nothing to do.
- }
- File[] entries = aDir.listFiles();
- for (int i = 0; i < entries.length; i++) {
- File file = entries[i];
- if (file.isFile()) {
- Assert.assertTrue("Could not delete " + entries[i].getPath(),
- entries[i].delete());
- }
- }
- }
+ private static final Log LOG = LogFactory.getLog(FileSystemUtils.class);
+
+ /**
+ * Test output directory relative to the sub project.
+ */
+ private static final String TEST_OUTPUT_DIR = "../target/testoutput";
+
+ /**
+ * Test input directory relative to the sub project.
+ */
+ private static final String TEST_INPUT_DIR = "../src/test/resources";
+
+ /*
+ * Disabled.
+ *
+ */
+ private FileSystemUtils() {
+ // Empty
+ }
+
+ /**
+ * Deletes a directory recursively. The test case will fail if the directory
+ * does not exist or if deletion fails.
+ *
+ * @param aDir
+ * Directory to delete.
+ */
+ public static void deleteDirRecursively(String aDir) {
+ deleteDirRecursively(new File(aDir));
+ }
+
+ /**
+ * Deletes a directory recursively. See {@link #deleteDirRecursively}.
+ *
+ * @param aDir
+ * Directory.
+ */
+ public static void deleteDirRecursively(File aDir) {
+ TestCase.assertTrue(aDir.isDirectory());
+
+ for (File file : aDir.listFiles()) {
+ if (file.isDirectory()) {
+ deleteDirRecursively(file);
+ } else {
+ delete(file);
+ }
+ }
+
+ delete(aDir);
+ }
+
+ /**
+ * Deletes a file or directory. The test case will fail if the file or
+ * directory does not exist or if deletion fails. Deletion of a non-empty
+ * directory will always fail.
+ *
+ * @param aFile
+ * File or directory to delete.
+ */
+ public static void delete(File aFile) {
+ TestCase.assertTrue(aFile.delete());
+ }
+
+ /**
+ * Gets a path relative to a sub project. This utility should be used to
+ * easily access file paths within a subproject without requiring any
+ * specific Eclipse configuration.
+ *
+ * @param aRelativePath
+ * Relative path.
+ * @param aTestClass
+ * Test class.
+ */
+ public static File getPath(String aRelativePath, Class aTestClass) {
+ CodeSource source = aTestClass.getProtectionDomain().getCodeSource();
+
+ if (source == null) {
+ LOG.warn("Could not obtain path for '" + aRelativePath +
+ "' for class " + aTestClass + ", using relative path as is");
+
+ return new File(aRelativePath);
+ }
+
+ URL location = source.getLocation();
+ String protocol = location.getProtocol();
+
+ if (!protocol.equals("file")) {
+ LOG.warn("protocol is not 'file': " + location);
+
+ return new File(aRelativePath);
+ }
+
+ String path = location.getPath();
+
+ try {
+ path = URLDecoder.decode(location.getPath(), "UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ // ignore it.. just don't decode
+ LOG.warn("Decoding path failed: '" + location.getPath() + "'", e);
+ }
+
+ return new File(new File(path).getParentFile(), aRelativePath);
+ }
+
+ /**
+ * Ensures that a directory hierarchy exists (recursively if needed). If it
+ * is not possible to create the directory, then the test case will fail.
+ *
+ * @param aDir
+ * Directory to create.
+ */
+ public static void createDir(File aDir) {
+ if (aDir.exists() && !aDir.isDirectory()) {
+ TestCase.fail("'" + aDir +
+ "' already exists and is not a directory");
+ }
+
+ if (aDir.exists()) {
+ return;
+ }
+
+ createDir(aDir.getParentFile());
+ TestCase.assertTrue("Could not create '" + aDir + "'", aDir.mkdir());
+ }
+
+ /**
+ * Creates a file in a directory.
+ * @param aDir Directory path. Will be created if it does not exist.
+ * @param aName Filename.
+ * @param aContents Contents.
+ */
+ public static void createFile(File aDir, String aName, InputStream aContents) {
+ createDir(aDir);
+
+ try {
+ OutputStream os = new FileOutputStream(new File(aDir, aName));
+ copyStream(aContents, os);
+ } catch (IOException e) {
+ e.printStackTrace();
+ TestCase.fail(e.getMessage());
+ }
+ }
+
+ /**
+ * Gets the test output directory for a specific test class.
+ *
+ * @param aTestClass
+ * Test class.
+ * @return Test output directory.
+ */
+ public static File getTestOutputDir(Class aTestClass) {
+ File file = getPath(TEST_OUTPUT_DIR, aTestClass);
+ String className = aTestClass.getName();
+ String classRelPath = className.replaceAll("\\.", "/");
+
+ return new File(file, classRelPath);
+ }
+
+ /**
+ * Gets the test input directory for a specific test class.
+ *
+ * @param aTestClass
+ * Test class.
+ * @return Test input directory.
+ */
+ public static File getTestInputDir(Class aTestClass) {
+ File file = getPath(TEST_INPUT_DIR, aTestClass);
+ String packageName = aTestClass.getPackage().getName();
+ String packagePath = packageName.replaceAll("\\.", "/");
+
+ return new File(file, packagePath);
+ }
+
+ /**
+ * Creates a directory hierarchy for the output directory of a test class if
+ * needed.
+ *
+ * @param aTestClass
+ * Test class
+ * @return Test directory.
+ */
+ public static File createTestOutputDir(Class aTestClass) {
+ File file = getTestOutputDir(aTestClass);
+ createDir(file);
+
+ return file;
+ }
+
+ /**
+ * Gets a test output file name. This returns a File object representing the
+ * output file and ensures that the directory where the file will be created
+ * already exists.
+ *
+ * @param aName
+ * Name of the file.
+ * @param aTestClass
+ * Test class.
+ * @return File.
+ */
+ public static File getTestOutputFile(String aName, Class aTestClass) {
+ File file = new File(getTestOutputDir(aTestClass), aName);
+ createDir(file.getParentFile());
+
+ return file;
+ }
+
+ public static String read(InputStream aIs) throws IOException {
+ try {
+ StringBuffer buffer = new StringBuffer();
+ int c;
+
+ while ((c = aIs.read()) != -1) {
+ buffer.append((char) c);
+ }
+
+ return buffer.toString();
+ } finally {
+ aIs.close();
+ }
+ }
+
+ /**
+ * Copies an input stream to an output stream.
+ *
+ * @param aIs
+ * Input stream.
+ * @param aOs
+ * Output stream.
+ */
+ public static void copyStream(InputStream aIs, OutputStream aOs) {
+ try {
+ int c;
+
+ while ((c = aIs.read()) != -1) {
+ aOs.write(c);
+ }
+
+ aIs.close();
+ aOs.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ Assert.fail(e.getMessage());
+ }
+ }
+
+ /**
+ * Recursively copy a directory.
+ *
+ * @param aSrc
+ * Source directory
+ * @param aTarget
+ * Target directory.
+ */
+ public static void copyDir(File aSrc, File aTarget) {
+ Assert.assertTrue(aSrc.isDirectory());
+ Assert.assertTrue(!aTarget.exists());
+
+ aTarget.mkdirs();
+
+ File[] files = aSrc.listFiles();
+
+ for (int i = 0; i < files.length; i++) {
+ File file = files[i];
+
+ if (file.isDirectory()) {
+ if (!file.getName().equals(".svn")) {
+ copyDir(new File(aSrc, file.getName()),
+ new File(aTarget, file.getName()));
+ }
+ } else {
+ copyFile(file, new File(aTarget, file.getName()));
+ }
+ }
+ }
+
+ /**
+ * Copy a file. If copying fails then the testcase will fail.
+ *
+ * @param aSrc
+ * Source file.
+ * @param aTarget
+ * Target file.
+ */
+ public static void copyFile(File aSrc, File aTarget) {
+ try {
+ FileInputStream fis = new FileInputStream(aSrc);
+ FileOutputStream fos = new FileOutputStream(aTarget);
+ FileChannel fcin = fis.getChannel();
+ FileChannel fcout = fos.getChannel();
+
+ // map input file
+ MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0,
+ fcin.size());
+
+ // do the file copy
+ fcout.write(mbb);
+
+ // finish up
+ fcin.close();
+ fcout.close();
+ fis.close();
+ fos.close();
+ } catch (IOException e) {
+ Assert.assertTrue("Copying file " + aSrc.getPath() + " to " +
+ aTarget.getPath() + " failed.", false);
+ }
+ }
+
+ /**
+ * Remove all files within a given directory including the directory itself.
+ * This only attempts to remove regular files and not directories within the
+ * directory. If the directory contains a nested directory, the deletion
+ * will fail. The test case will fail if this fails.
+ *
+ * @param aDir
+ * Directory to remove.
+ */
+ public static void deleteDir(File aDir) {
+ cleanDir(aDir);
+ delete(aDir);
+ }
+
+ /**
+ * Remove all regular files within a given directory.
+ *
+ * @param outputDirName
+ */
+ public static void cleanDir(File aDir) {
+ if (!aDir.exists()) {
+ return; // nothing to do.
+ }
+
+ File[] entries = aDir.listFiles();
+
+ for (int i = 0; i < entries.length; i++) {
+ File file = entries[i];
+
+ if (file.isFile()) {
+ Assert.assertTrue("Could not delete " + entries[i].getPath(),
+ entries[i].delete());
+ }
+ }
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.io;
+import junit.framework.TestCase;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
-import junit.framework.TestCase;
-
/**
- * Tests the stream resource.
+ * Tests the stream resource.
*
* @author Erik Brakkee
*/
public class StreamResourceTest extends TestCase {
-
/**
* Loads an existing resource. Verifies it is found.
- *
+ *
*/
public void testResourceFound() throws IOException {
- File file = new File(
- FileSystemUtils.getTestInputDir(StreamResourceTest.class),
- "myresource.txt");
- assertTrue(file.canRead());
+ File file = new File(FileSystemUtils.getTestInputDir(
+ StreamResourceTest.class), "myresource.txt");
+ assertTrue(file.canRead());
+
InputStream fileIs = new FileInputStream(file);
InputResource resource = new StreamResource(fileIs);
InputStream is = resource.getInputStream();
String data = FileSystemUtils.read(is);
assertEquals("This is my resource", data);
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.io;
+import junit.framework.Assert;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
-import junit.framework.Assert;
/**
* TestData provides a convenient interface for managing test output files.
- *
+ *
* @author Erik Brakkee
*/
public final class TestData {
-
- private Object testcase;
- private File root;
-
- /**
- * Test data to be constructed in the setUp of a test. {@link #clean()} must
- * be called to make sure that this directory is empty before executing a
- * test.
- */
- public TestData(Object aTestcase) {
- testcase = aTestcase;
- root = getTestRootDir(aTestcase);
- FileSystemUtils.createDir(root);
- }
-
- /**
- * Obtain root directory of JUnit tests.
- *
- * @return Directory name.
- */
- private static File getTestRootDir(Object aTestcase) {
- return FileSystemUtils.getTestOutputDir(aTestcase.getClass());
- }
-
- public void createFile(String aRelative, String aFile, InputStream aContents) {
- FileSystemUtils
- .createFile(new File(root, aRelative), aFile, aContents);
- }
-
- public void createFile(String aFile, String aContents) {
- createFile(".", aFile, aContents);
- }
-
- public void createFile(String aRelative, String aFile, String aContents) {
- InputStream is = new ByteArrayInputStream(aContents.getBytes());
- FileSystemUtils.createFile(new File(root, aRelative), aFile, is);
- }
-
- public void deleteFile(String aFile) {
- deleteFile(".", aFile);
- }
-
- public void deleteFile(String aRelative, String aFile) {
- FileSystemUtils.delete(new File(root, aFile));
- }
-
- /**
- * Returns a temporary directory.
- *
- * @return Temporary directory.
- */
- public File getTmpDir() {
- return new File(root, "tmpdir");
- }
-
- /**
- * Cleans up the test output directory.
- */
- public void clean() {
- FileSystemUtils.deleteDirRecursively(root);
- FileSystemUtils.createDir(root);
- }
-
- /**
- * Recursively copy a directory contents to the test output directory.
- *
- * @param sSrc
- * Source directory to copy.
- */
- public void copyDir(File aSrc) {
- FileSystemUtils.copyDir(aSrc, root);
- }
-
- /**
- * Copies a classpath resource to a relative path in the test output
- * directory.
- *
- * @param aResource
- * Resource to copy.
- * @param aRelativePath
- * Relative path.
- */
- public void copyResource(String aResource, String aRelativePath) {
- try {
- InputStream is = new ClassPathResource(aResource).getInputStream();
- FileOutputStream fos = new FileOutputStream(new File(root,
- aRelativePath));
- FileSystemUtils.copyStream(is, fos);
- } catch (IOException e) {
- e.printStackTrace();
- Assert.fail(e.getMessage());
- }
- }
-
- /**
- * Copies a resource to the root directory of the test output.
- *
- * @param aResource
- * Resource.
- */
- public void copyResource(String aResource) {
- String basename = new File(aResource).getName();
- copyResource(aResource, basename);
- }
-
- public void createDir(String aRelative) {
- FileSystemUtils.createDir(new File(root, aRelative));
- }
-
- /**
- * Deletes a file or directory relative to the test output root.
- *
- * @param aRelative
- * Relative path. The testcase will fail if the file or directory
- * cannot be removed.
- */
- public void delete(String aRelative) {
- FileSystemUtils.delete(new File(root, aRelative));
- }
-
- /**
- * Deletes a directory including its contents.
- *
- * @param aRelative
- * Relative path.
- */
- public void deleteDir(String aRelative) {
- FileSystemUtils.deleteDir(new File(root, aRelative));
- }
-
- /**
- * Deletes a directory recursively.
- *
- * @param aRelative
- * Relative path.
- */
- public void deleteDirRecursively(String aRelative) {
- FileSystemUtils.deleteDir(new File(root, aRelative));
- }
-
- /**
- * Gets the root of the test output directory.
- *
- * @return Root of the test output.
- */
- public File getRoot() {
- return root;
- }
-
- /**
- * Gets a file object for a relative path.
- */
- public File getFile(String aRelative) {
- return new File(root, aRelative);
- }
+ private Object testcase;
+ private File root;
+
+ /**
+ * Test data to be constructed in the setUp of a test. {@link #clean()} must
+ * be called to make sure that this directory is empty before executing a
+ * test.
+ */
+ public TestData(Object aTestcase) {
+ testcase = aTestcase;
+ root = getTestRootDir(aTestcase);
+ FileSystemUtils.createDir(root);
+ }
+
+ /**
+ * Obtain root directory of JUnit tests.
+ *
+ * @return Directory name.
+ */
+ private static File getTestRootDir(Object aTestcase) {
+ return FileSystemUtils.getTestOutputDir(aTestcase.getClass());
+ }
+
+ public void createFile(String aRelative, String aFile, InputStream aContents) {
+ FileSystemUtils.createFile(new File(root, aRelative), aFile, aContents);
+ }
+
+ public void createFile(String aFile, String aContents) {
+ createFile(".", aFile, aContents);
+ }
+
+ public void createFile(String aRelative, String aFile, String aContents) {
+ InputStream is = new ByteArrayInputStream(aContents.getBytes());
+ FileSystemUtils.createFile(new File(root, aRelative), aFile, is);
+ }
+
+ public void deleteFile(String aFile) {
+ deleteFile(".", aFile);
+ }
+
+ public void deleteFile(String aRelative, String aFile) {
+ FileSystemUtils.delete(new File(root, aFile));
+ }
+
+ /**
+ * Returns a temporary directory.
+ *
+ * @return Temporary directory.
+ */
+ public File getTmpDir() {
+ return new File(root, "tmpdir");
+ }
+
+ /**
+ * Cleans up the test output directory.
+ */
+ public void clean() {
+ FileSystemUtils.deleteDirRecursively(root);
+ FileSystemUtils.createDir(root);
+ }
+
+ /**
+ * Recursively copy a directory contents to the test output directory.
+ *
+ * @param sSrc
+ * Source directory to copy.
+ */
+ public void copyDir(File aSrc) {
+ FileSystemUtils.copyDir(aSrc, root);
+ }
+
+ /**
+ * Copies a classpath resource to a relative path in the test output
+ * directory.
+ *
+ * @param aResource
+ * Resource to copy.
+ * @param aRelativePath
+ * Relative path.
+ */
+ public void copyResource(String aResource, String aRelativePath) {
+ try {
+ InputStream is = new ClassPathResource(aResource).getInputStream();
+ FileOutputStream fos = new FileOutputStream(new File(root,
+ aRelativePath));
+ FileSystemUtils.copyStream(is, fos);
+ } catch (IOException e) {
+ e.printStackTrace();
+ Assert.fail(e.getMessage());
+ }
+ }
+
+ /**
+ * Copies a resource to the root directory of the test output.
+ *
+ * @param aResource
+ * Resource.
+ */
+ public void copyResource(String aResource) {
+ String basename = new File(aResource).getName();
+ copyResource(aResource, basename);
+ }
+
+ public void createDir(String aRelative) {
+ FileSystemUtils.createDir(new File(root, aRelative));
+ }
+
+ /**
+ * Deletes a file or directory relative to the test output root.
+ *
+ * @param aRelative
+ * Relative path. The testcase will fail if the file or directory
+ * cannot be removed.
+ */
+ public void delete(String aRelative) {
+ FileSystemUtils.delete(new File(root, aRelative));
+ }
+
+ /**
+ * Deletes a directory including its contents.
+ *
+ * @param aRelative
+ * Relative path.
+ */
+ public void deleteDir(String aRelative) {
+ FileSystemUtils.deleteDir(new File(root, aRelative));
+ }
+
+ /**
+ * Deletes a directory recursively.
+ *
+ * @param aRelative
+ * Relative path.
+ */
+ public void deleteDirRecursively(String aRelative) {
+ FileSystemUtils.deleteDir(new File(root, aRelative));
+ }
+
+ /**
+ * Gets the root of the test output directory.
+ *
+ * @return Root of the test output.
+ */
+ public File getRoot() {
+ return root;
+ }
+
+ /**
+ * Gets a file object for a relative path.
+ */
+ public File getFile(String aRelative) {
+ return new File(root, aRelative);
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.io;
import java.io.File;
* Test resource for locating resources in the classpath.
*/
public class TestResource extends FileResource {
-
/**
- * Test class name.
- * @param aTestClass Test class.
- * @param aName Name of the file to look for.
+ * Test class name.
+ * @param aTestClass Test class.
+ * @param aName Name of the file to look for.
*/
public TestResource(Class aTestClass, String aName) {
- super(getFile(aTestClass, aName));
+ super(getFile(aTestClass, aName));
}
-
+
/**
- * Computes the file path of the file to look for.
- * @param aClass Test class name.
- * @param aName Name of the file.
- * @return File.
+ * Computes the file path of the file to look for.
+ * @param aClass Test class name.
+ * @param aName Name of the file.
+ * @return File.
*/
- private static File getFile(Class aClass, String aName) {
+ private static File getFile(Class aClass, String aName) {
File dir = FileSystemUtils.getTestInputDir(aClass);
+
return new File(dir, aName);
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.observer;
-import static org.mockito.Mockito.*;
+import junit.framework.TestCase;
+
+import org.mockito.InOrder;
+import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
-import org.mockito.InOrder;
-
-import junit.framework.TestCase;
/**
* Test of the observer pattern implementation.
- *
+ *
* @author Erik Brakkee
*/
public class ObservableTest extends TestCase {
+ private static final int SUBSCRIBER_COUNT = 100;
+ private static final String UPDATE = "send";
+ private Integer observed;
+ private Observable<Integer, String> observable;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see junit.framework.TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ observed = new Integer(1);
+ observable = new Observable<Integer, String>(observed,
+ new DefaultObserverNotifier());
+ }
+
+ /**
+ * Tests subscription and notification of one subscriber.
+ */
+ public void testOneObserver() {
+ final Observer mockObserver = mock(Observer.class);
+ InOrder order = inOrder(mockObserver);
+
+ long subscription = observable.subscribe(mockObserver);
+
+ assertEquals(1, observable.getObserverCount());
+
+ final String message = "hallo";
+ observable.send(message);
+
+ order.verify(mockObserver).send(observed, message);
+ verifyNoMoreInteractions(mockObserver);
+
+ observable.unsubscribe(subscription);
+ assertEquals(0, observable.getObserverCount());
+
+ observable.send(message);
+ verifyNoMoreInteractions(mockObserver);
+ }
+
+ /**
+ * Subscribes many susbcribers and sends notifications to subscribers.
+ * Verifies that unique subscription number are returned. Also verifies that
+ * the correct subscribers are notfied.
+ */
+ public void testManySubscribers() {
+ final int nsubscribers = SUBSCRIBER_COUNT;
+ final Observer[] mocks = new Observer[nsubscribers];
+ final InOrder[] order = new InOrder[nsubscribers];
+
+ List<Long> subscriptions = new ArrayList<Long>();
+
+ for (int i = 0; i < nsubscribers; i++) {
+ mocks[i] = mock(Observer.class);
+ order[i] = inOrder(mocks[i]);
+
+ long subscription = observable.subscribe(mocks[i]);
+ assertTrue(subscriptions.add(subscription));
+ }
+
+ assertEquals(nsubscribers, observable.getObserverCount());
+
+ final String message = "hallo";
+
+ observable.send(message);
+
+ for (int i = 0; i < nsubscribers; i++) {
+ order[i].verify(mocks[i]).send(observed, message);
+ }
+
+ for (int i = nsubscribers / 2; i < nsubscribers; i++) {
+ observable.unsubscribe(subscriptions.get(i));
+ }
+
+ assertEquals(nsubscribers - (nsubscribers - (nsubscribers / 2)),
+ observable.getObserverCount());
+
+ final String message2 = "blabla";
+
+ observable.send(message2);
+
+ for (int i = 0; i < (nsubscribers / 2); i++) {
+ order[i].verify(mocks[i]).send(observed, message2);
+ }
+
+ for (int i = nsubscribers / 2; i < nsubscribers; i++) {
+ verifyNoMoreInteractions(mocks[i]);
+ }
+ }
+
+ /**
+ * Subscribes and then unsubscribes with a wrong id. Verifies that
+ * IllegalArgumentException is thrown.
+ *
+ */
+ public void testUnsubscribeWithWrongSubscription() {
+ Observer<Integer, String> observer = mock(Observer.class);
+
+ long subscription = observable.subscribe(observer);
+
+ assertEquals(1, observable.getObserverCount());
+
+ try {
+ observable.unsubscribe(subscription + 1);
+ } catch (IllegalArgumentException e) {
+ return; // ok
+ }
- private static final int SUBSCRIBER_COUNT = 100;
-
- private static final String UPDATE = "send";
-
- private Integer observed;
- private Observable<Integer, String> observable;
-
- /*
- * (non-Javadoc)
- *
- * @see junit.framework.TestCase#setUp()
- */
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- observed = new Integer(1);
- observable = new Observable<Integer, String>(observed,
- new DefaultObserverNotifier());
- }
-
- /**
- * Tests subscription and notification of one subscriber.
- */
- public void testOneObserver() {
- final Observer mockObserver = mock(Observer.class);
- InOrder order = inOrder(mockObserver);
-
- long subscription = observable.subscribe(mockObserver);
-
- assertEquals(1, observable.getObserverCount());
-
- final String message = "hallo";
- observable.send(message);
-
- order.verify(mockObserver).send(observed, message);
- verifyNoMoreInteractions(mockObserver);
-
- observable.unsubscribe(subscription);
- assertEquals(0, observable.getObserverCount());
-
- observable.send(message);
- verifyNoMoreInteractions(mockObserver);
- }
-
- /**
- * Subscribes many susbcribers and sends notifications to subscribers.
- * Verifies that unique subscription number are returned. Also verifies that
- * the correct subscribers are notfied.
- */
- public void testManySubscribers() {
- final int nsubscribers = SUBSCRIBER_COUNT;
- final Observer[] mocks = new Observer[nsubscribers];
- final InOrder[] order = new InOrder[nsubscribers];
-
- List<Long> subscriptions = new ArrayList<Long>();
- for (int i = 0; i < nsubscribers; i++) {
- mocks[i] = mock(Observer.class);
- order[i] = inOrder(mocks[i]);
- long subscription = observable.subscribe(mocks[i]);
- assertTrue(subscriptions.add(subscription));
- }
-
- assertEquals(nsubscribers, observable.getObserverCount());
-
- final String message = "hallo";
-
- observable.send(message);
- for (int i = 0; i < nsubscribers; i++) {
- order[i].verify(mocks[i]).send(observed, message);
- }
-
- for (int i = nsubscribers / 2; i < nsubscribers; i++) {
- observable.unsubscribe(subscriptions.get(i));
- }
- assertEquals(nsubscribers - (nsubscribers - nsubscribers / 2),
- observable.getObserverCount());
-
- final String message2 = "blabla";
-
- observable.send(message2);
- for (int i = 0; i < nsubscribers / 2; i++) {
- order[i].verify(mocks[i]).send(observed, message2);
- }
- for (int i = nsubscribers/2; i < nsubscribers; i++) {
- verifyNoMoreInteractions(mocks[i]);
- }
-
- }
-
- /**
- * Subscribes and then unsubscribes with a wrong id. Verifies that
- * IllegalArgumentException is thrown.
- *
- */
- public void testUnsubscribeWithWrongSubscription() {
- Observer<Integer, String> observer = mock(Observer.class);
-
- long subscription = observable.subscribe(observer);
-
- assertEquals(1, observable.getObserverCount());
-
- try {
- observable.unsubscribe(subscription + 1);
- } catch (IllegalArgumentException e) {
- return; // ok
- }
- fail();
- }
+ fail();
+ }
}
/*
* Copyright 2006 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.test;
+import junit.framework.TestCase;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
-import junit.framework.TestCase;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
/**
* Useful assertions for use in test cases.
* @author Erik Brakkee
*/
public final class AssertionUtils {
-
- private static final Log LOG = LogFactory.getLog(AssertionUtils.class);
+ private static final Log LOG = LogFactory.getLog(AssertionUtils.class);
/**
* Disabled constructor.
- *
+ *
*/
private AssertionUtils() {
// Empty
}
-
+
/**
* Asserts that two object arrays are equal.
- *
+ *
* @param aExpected
* Expected object array.
* @param aActual
public static <T> void assertEquals(T[] aExpected, T[] aActual) {
assertEquals("", aExpected, aActual);
}
-
/**
* Asserts that two object arrays are equal.
- *
+ *
* @param aMsg
* Message.
* @param aExpected
* @param aActual
* Actual array.
*/
- public static <T> void assertEquals(String aMsg, T[] aExpected,
- T[] aActual) {
- TestCase.assertEquals(aMsg + " expected " +
- Arrays.asList(aExpected) + ", actual " +
- Arrays.asList(aActual) + ": Array lengths ", aExpected.length,
- aActual.length);
+ public static <T> void assertEquals(String aMsg, T[] aExpected, T[] aActual) {
+ TestCase.assertEquals(aMsg + " expected " + Arrays.asList(aExpected) +
+ ", actual " + Arrays.asList(aActual) + ": Array lengths ",
+ aExpected.length, aActual.length);
for (int i = 0; i < aExpected.length; i++) {
TestCase.assertEquals(aMsg + ": Element " + i, aExpected[i],
- aActual[i]);
+ aActual[i]);
}
}
-
/**
* Asserts that two objects are equal, and in case the object is an Object[]
* delegates to {@link #assertEquals(String, Object[], Object[]).
- *
+ *
* @param aMsg
* Message.
* @param aExpected
* @param aActual
* Actual result.
*/
- public static <T> void assertEquals(String aMsg, T aExpected,
- T aActual) {
+ public static <T> void assertEquals(String aMsg, T aExpected, T aActual) {
if (aExpected instanceof Object[]) {
AssertionUtils.assertEquals(aMsg, (Object[]) aExpected,
- (Object[]) aActual);
+ (Object[]) aActual);
return;
}
/**
* Asserts that two maps are equal by comparing all keys and by checking
* that the values for the same keys are the same.
- *
+ *
* @param aMsg
* Message.
* @param aExpectedMap
* @param aActual
* Actual result.
*/
- public static <Key,Value> void assertEquals(String aMsg,
- Map<Key,Value> aExpectedMap, Map<Key,Value> aActual) {
- TestCase.assertEquals("Map sizes differ", aExpectedMap.size(), aActual
- .size());
+ public static <Key, Value> void assertEquals(String aMsg,
+ Map<Key, Value> aExpectedMap, Map<Key, Value> aActual) {
+ TestCase.assertEquals("Map sizes differ", aExpectedMap.size(),
+ aActual.size());
Set keys = aExpectedMap.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
String key = (String) i.next();
TestCase.assertTrue("Map does not containg entry for key:" + key,
- aActual.containsKey(key));
+ aActual.containsKey(key));
AssertionUtils.assertEquals("Value of key " + key + " of map",
- aExpectedMap.get(key), aActual.get(key));
+ aExpectedMap.get(key), aActual.get(key));
}
}
-
- public static interface ErroneousCode {
- void run() throws Exception;
- }
-
- /**
+
+ /**
* Asserts that an exception occurs.
- * @param aRunnable Test cases should create a subclass of this which contains the
- * code that should throw an exception.
- * @param aType Type of exception that is expected.
+ * @param aRunnable Test cases should create a subclass of this which contains the
+ * code that should throw an exception.
+ * @param aType Type of exception that is expected.
*/
- public static void assertException(ErroneousCode aObject, Class aType) {
- try {
- aObject.run();
- throw new RuntimeException("No exception occurred");
- } catch (Throwable t) {
- if ( aType.isInstance(t)) {
- LOG.info("Expected exception occured " + t.getMessage());
- return; // ok
- }
- else {
- throw new RuntimeException(t);
- }
- }
+ public static void assertException(ErroneousCode aObject, Class aType) {
+ try {
+ aObject.run();
+ throw new RuntimeException("No exception occurred");
+ } catch (Throwable t) {
+ if (aType.isInstance(t)) {
+ LOG.info("Expected exception occured " + t.getMessage());
+
+ return; // ok
+ } else {
+ throw new RuntimeException(t);
+ }
+ }
+ }
+
+ public static interface ErroneousCode {
+ void run() throws Exception;
}
}
/*
* Copyright 2006 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.test;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
/**
* Tracks the occurence of certain events in a test environment. Threads in a
* test environment tell the event tracker of the occurrence of certain events
* using {@link #eventOccurred(Event)}. Test code inspects the events sent by a
* thread using {@link #isEventSent(Thread, Event)}.
- *
+ *
* A record is kept of every event which is sent. Therefore, the occurrence of a
* new event does not erase a previously sent event.
- *
+ *
* @param <Event>
* Type of event sent from test code. Usually String will be
* sufficient. The event type must provide a sensible implementation
* @author Erik Brakkee
*/
public class EventTracker<Event> {
-
private static final Log LOG = LogFactory.getLog(EventTracker.class);
/**
/**
* Constructs the event tracker.
- *
+ *
*/
public EventTracker() {
clear();
}
- public void clear() {
- events = new HashMap<Thread, List<Event>>();
- }
+ public void clear() {
+ events = new HashMap<Thread, List<Event>>();
+ }
/**
* Called by a thread to inform that an event has occurred.
- *
+ *
* @param aEvent
* Event that was sent.
*/
public synchronized void eventOccurred(Event aEvent) {
LOG.info("Event '" + aEvent + "' sent.");
+
Thread current = Thread.currentThread();
List<Event> eventList = events.get(current);
+
if (eventList == null) {
eventList = new ArrayList<Event>();
events.put(current, eventList);
}
+
eventList.add(aEvent);
}
/**
* Checks if a specific event has happened in a specific thread.
- *
+ *
* @param aThread
* Thread to check.
* @param aEvent
*/
public synchronized boolean isEventSent(Thread aThread, Event aEvent) {
List<Event> eventList = events.get(aThread);
+
if (eventList == null) {
return false;
}
+
return eventList.contains(aEvent);
}
/**
* Gets the events for a thread in the order they were sent
- *
+ *
* @param aThread
* Thread to get events for.
* @return Events that were sent. A zero-sized array is returned if no
*/
public synchronized List<Event> getEvents(Thread aThread) {
List<Event> eventList = events.get(aThread);
+
if (eventList == null) {
eventList = Collections.emptyList();
}
+
return Collections.unmodifiableList(eventList);
}
/**
* Gets the number of times an event was sent summed up
- * over all threads.
- *
+ * over all threads.
+ *
* @param aEvent
* Event to check.
* @return Number of times it was reached.
*/
public synchronized int getEventCount(Event aEvent) {
int count = 0;
+
for (Thread thread : events.keySet()) {
List<Event> eventList = events.get(thread);
+
for (Event event : eventList) {
if (event.equals(aEvent)) {
count++;
}
}
}
+
return count;
}
-
+
/**
- * Gets the total event count over all threads.
+ * Gets the total event count over all threads.
* @return
*/
- public synchronized int getEventCount() {
- int count = 0;
- for (Thread thread: events.keySet()) {
- count += events.get(thread).size();
- }
- return count;
+ public synchronized int getEventCount() {
+ int count = 0;
+
+ for (Thread thread : events.keySet()) {
+ count += events.get(thread).size();
+ }
+
+ return count;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.test;
import junit.framework.TestCase;
+
/**
* Timing utilities.
*
* @author Erik Brakkee
*/
public final class TimingUtils {
-
/**
* Disabled constructor.
*
private TimingUtils() {
// Empty
}
-
+
/**
- * Sleeps for a time.
- * @param aMillis Number of milliseconds to sleep.
+ * Sleeps for a time.
+ * @param aMillis Number of milliseconds to sleep.
*/
- public static void sleep(int aMillis) {
- try {
+ public static void sleep(int aMillis) {
+ try {
Thread.sleep(aMillis);
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
TestCase.fail("Who interrupted my sleep?");
}
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.xml;
+import junit.framework.TestCase;
+
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.FileSystemUtils;
+
import java.io.IOException;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
-import junit.framework.TestCase;
-
-
-import org.wamblee.io.ClassPathResource;
-import org.wamblee.io.FileSystemUtils;
/**
* Tests for {@link org.wamblee.xml.ClasspathUriResolver}.
* @author Erik Brakkee
*/
public class ClasspathUriResolverTest extends TestCase {
-
- private URIResolver resolver;
-
+ private URIResolver resolver;
+
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
- resolver = new ClasspathUriResolver();
+ resolver = new ClasspathUriResolver();
}
/**
- * Resolves an existing file. Verifies the file is resolved correctly.
- * @throws TransformerException
+ * Resolves an existing file. Verifies the file is resolved correctly.
+ * @throws TransformerException
* @throws IOException
*/
- public void testResolveExistingFile() throws TransformerException, IOException {
+ public void testResolveExistingFile()
+ throws TransformerException, IOException {
Source source = resolver.resolve("org/wamblee/xml/reportToHtml.xsl", "");
assertTrue(source instanceof StreamSource);
- String resolved = FileSystemUtils.read(((StreamSource)source).getInputStream());
-
- ClassPathResource resource = new ClassPathResource("org/wamblee/xml/reportToHtml.xsl");
+
+ String resolved = FileSystemUtils.read(((StreamSource) source).getInputStream());
+
+ ClassPathResource resource = new ClassPathResource(
+ "org/wamblee/xml/reportToHtml.xsl");
String expected = FileSystemUtils.read(resource.getInputStream());
assertEquals(expected, resolved);
}
-
+
/**
- * Resolves a non-existing file. Verifies that a TransformerException is thrown.
+ * Resolves a non-existing file. Verifies that a TransformerException is thrown.
*
*/
public void testResolveNonExistingFile() {
- try {
- Source source = resolver.resolve("org/wamblee/xml/reportToHtml-nonexisting.xsl", "");
- } catch (TransformerException e) {
+ try {
+ Source source = resolver.resolve("org/wamblee/xml/reportToHtml-nonexisting.xsl",
+ "");
+ } catch (TransformerException e) {
return; // ok
}
+
fail();
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.xml;
+import junit.framework.TestCase;
+
+import org.dom4j.Attribute;
+import org.dom4j.Document;
+import org.dom4j.Element;
+
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
-import junit.framework.TestCase;
-
-import org.dom4j.Attribute;
-import org.dom4j.Document;
-import org.dom4j.Element;
/**
* XML test support utilities.
* @author Erik Brakkee
*/
public final class XmlUtils {
-
/**
* Disabled constructor.
- *
+ *
*/
private XmlUtils() {
// Empty
/**
* Checks equality of two XML documents excluding comment and processing
* nodes and trimming the text of the elements. In case of problems, it
- * provides an xpath-like expression describing where the problem is.
- *
+ * provides an xpath-like expression describing where the problem is.
+ *
* @param aMsg
* @param aExpected
* @param aActual
*/
public static void assertEquals(String aMsg,
- org.w3c.dom.Document aExpected, org.w3c.dom.Document aActual) {
- assertEquals(aMsg, DomUtils.convert(aExpected), DomUtils
- .convert(aActual));
+ org.w3c.dom.Document aExpected, org.w3c.dom.Document aActual) {
+ assertEquals(aMsg, DomUtils.convert(aExpected),
+ DomUtils.convert(aActual));
}
/**
* Checks equality of two XML documents excluding comment and processing
* nodes and trimming the text of the elements. In case of problems, it
- * provides an xpath-like expression describing where the problem is.
- *
+ * provides an xpath-like expression describing where the problem is.
+ *
* @param aMsg
* @param aExpected
* @param aActual
*/
public static void assertEquals(String aMsg, Document aExpected,
- Document aActual) {
- assertEquals(aMsg + "/" + aExpected.getRootElement().getName(), aExpected.getRootElement(), aActual.getRootElement());
+ Document aActual) {
+ assertEquals(aMsg + "/" + aExpected.getRootElement().getName(),
+ aExpected.getRootElement(), aActual.getRootElement());
}
/**
* Checks equality of two XML elements excluding comment and processing
* nodes and trimming the text of the elements. In case of problems, it
- * provides an xpath-like expression describing where the problem is.
- *
+ * provides an xpath-like expression describing where the problem is.
+ *
* @param aMsg
* @param aExpected
* @param aActual
*/
public static void assertEquals(String aMsg, Element aExpected,
- Element aActual) {
-
+ Element aActual) {
// Name.
- TestCase.assertEquals(aMsg + "/name()", aExpected.getName(), aActual
- .getName());
+ TestCase.assertEquals(aMsg + "/name()", aExpected.getName(),
+ aActual.getName());
// Text
TestCase.assertEquals(aMsg + "/text()", aExpected.getTextTrim(),
- aActual.getTextTrim());
+ aActual.getTextTrim());
// Attributes
List<Attribute> expectedAttrs = aExpected.attributes();
Collections.sort(expectedAttrs, new AttributeComparator());
+
List<Attribute> actualAttrs = aActual.attributes();
Collections.sort(actualAttrs, new AttributeComparator());
TestCase.assertEquals("count(" + aMsg + "/@*)", expectedAttrs.size(),
- actualAttrs.size());
+ actualAttrs.size());
+
for (int i = 0; i < expectedAttrs.size(); i++) {
String msg = aMsg + "/@" + expectedAttrs.get(i).getName();
assertEquals(msg, expectedAttrs.get(i), actualAttrs.get(i));
List<Element> expectedElems = aExpected.elements();
List<Element> actualElems = aActual.elements();
TestCase.assertEquals("count(" + aMsg + "/*)", expectedElems.size(),
- actualElems.size());
+ actualElems.size());
+
// determine the how-manyth element of the given name we are at.
// Maps element name to the last used index (or null if not yet used)
Map<String, Integer> elementIndex = new TreeMap<String, Integer>();
+
for (int i = 0; i < expectedElems.size(); i++) {
String elemName = expectedElems.get(i).getName();
Integer index = elementIndex.get(elemName);
+
if (index == null) {
index = 1;
} else {
index++;
}
+
elementIndex.put(elemName, index);
- String msg = aMsg + "/" + expectedElems.get(i).getName() + "["
- + index + "]";
+
+ String msg = aMsg + "/" + expectedElems.get(i).getName() + "[" +
+ index + "]";
assertEquals(msg, expectedElems.get(i), actualElems.get(i));
}
/**
* Checks equality of two attributes. In case of problems, it
- * provides an xpath-like expression describing where the problem is.
- *
+ * provides an xpath-like expression describing where the problem is.
+ *
* @param aMsg
* @param aExpected
* @param aActual
*/
public static void assertEquals(String aMsg, Attribute aExpected,
- Attribute aActual) {
- TestCase.assertEquals(aMsg + ":name", aExpected.getName(), aActual
- .getName());
- TestCase.assertEquals(aMsg + ":value", aExpected.getValue(), aActual
- .getValue());
+ Attribute aActual) {
+ TestCase.assertEquals(aMsg + ":name", aExpected.getName(),
+ aActual.getName());
+ TestCase.assertEquals(aMsg + ":value", aExpected.getValue(),
+ aActual.getValue());
}
/**
* Comparator which compares attributes by name.
*/
- private static final class AttributeComparator implements
- Comparator<Attribute> {
+ private static final class AttributeComparator implements Comparator<Attribute> {
/*
* (non-Javadoc)
- *
+ *
* @see java.util.Comparator#compare(T, T)
*/
public int compare(Attribute aAttribute1, Attribute aAttribute2) {
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.xml;
+import junit.framework.TestCase;
+
+import org.w3c.dom.Document;
+
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.FileSystemUtils;
+import org.wamblee.io.InputResource;
+
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
-import junit.framework.TestCase;
-import org.wamblee.io.ClassPathResource;
-import org.wamblee.io.FileSystemUtils;
-import org.wamblee.io.InputResource;
-
-import org.w3c.dom.Document;
/**
* Tests the XSL transformer.
* @author Erik Brakkee
*/
public class XslTransformerTest extends TestCase {
-
private static final String INCLUDED_XSL_FILE = "utilities.xsl";
-
- private static final String REPORT_XML = "report.xml";
-
+ private static final String REPORT_XML = "report.xml";
private static final String REPORT_TO_HTML_XSLT = "reportToHtml.xsl";
-
private static final String REPORT_TO_HTML2_XSLT = "reportToHtml2.xsl";
-
private static final String REPORT_TO_HTML_INVALID_XSLT = "reportToHtml-invalid.xsl";
-
private static final String REPORT_TO_HTML_NONWELLFORMED_XSLT = "reportToHtml-nonwellformed.xsl";
-
private static final String REPORT_TO_TEXT_XSLT = "reportToText.xsl";
- private String getResourcePath(String aResource) {
- return getClass().getPackage().getName().replaceAll("\\.", "/") + "/" + aResource;
+ private String getResourcePath(String aResource) {
+ return getClass().getPackage().getName().replaceAll("\\.", "/") + "/" +
+ aResource;
}
/**
* Transforms a file while using the default resolver, where the included
* file can be found. Verifies the transformation is done correctly.
- *
+ *
*/
public void testTransformUsingDefaultResolver() throws Exception {
XslTransformer transformer = new XslTransformer();
- InputResource xmlResource = new ClassPathResource(getResourcePath(REPORT_XML));
-
+ InputResource xmlResource = new ClassPathResource(getResourcePath(
+ REPORT_XML));
+
Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_XSLT)).getInputStream());
+ REPORT_TO_HTML_XSLT)).getInputStream());
- byte[] documentData = FileSystemUtils
- .read(xmlResource.getInputStream()).getBytes();
+ byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
+ .getBytes();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
- .newDocumentBuilder();
+ .newDocumentBuilder();
Document document = builder.parse(xmlResource.getInputStream());
Source documentSource = new StreamSource(xmlResource.getInputStream());
Document expected = DomUtils.read(new ClassPathResource(getResourcePath(
- "output-reportToHtml-report.xml")).getInputStream());
+ "output-reportToHtml-report.xml")).getInputStream());
Document output1 = transformer.transform(documentData, xslt);
XmlUtils.assertEquals("byte[] transform", expected, output1);
xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_XSLT)).getInputStream());
+ REPORT_TO_HTML_XSLT)).getInputStream());
+
Document output2 = transformer.transform(document, xslt);
XmlUtils.assertEquals("document transform", expected, output2);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Result output = new StreamResult(os);
-
+
xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_XSLT)).getInputStream());
+ REPORT_TO_HTML_XSLT)).getInputStream());
transformer.transform(documentSource, output, xslt);
- XmlUtils.assertEquals("document source transform", expected, DomUtils
- .read(os.toString()));
+ XmlUtils.assertEquals("document source transform", expected,
+ DomUtils.read(os.toString()));
xslt = new StreamSource(new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_XSLT)).getInputStream());
+ REPORT_TO_HTML_XSLT)).getInputStream());
+
String result = transformer.textTransform(documentData, xslt);
- XmlUtils
- .assertEquals("text transform", expected, DomUtils.read(result));
+ XmlUtils.assertEquals("text transform", expected, DomUtils.read(result));
}
/**
* Transforms a file using the default resolver where the included file
* cannot be found. Verifies that a TransformerException is thrown.
- *
+ *
*/
- public void testTransformUsingDefaultResolverFails() throws IOException {
+ public void testTransformUsingDefaultResolverFails()
+ throws IOException {
XslTransformer transformer = new XslTransformer();
- InputResource xmlResource =
- new ClassPathResource(getResourcePath(REPORT_XML));
- Source xslt = new StreamSource(
- new ClassPathResource(getResourcePath(
- REPORT_TO_HTML2_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(getResourcePath(
+ REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
+ REPORT_TO_HTML2_XSLT)).getInputStream());
+
+ byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
+ .getBytes();
- byte[] documentData = FileSystemUtils
- .read(xmlResource.getInputStream()).getBytes();
try {
Document output1 = transformer.transform(documentData, xslt);
} catch (TransformerException e) {
return; // ok
}
+
fail();
}
/**
* Transforms a file using an invalid Xslt. Verifies that a
* TransformerException is thrown.
- *
+ *
*/
public void testTransformInvalidXslt() throws IOException {
XslTransformer transformer = new XslTransformer();
- InputResource xmlResource = new ClassPathResource(
- getResourcePath(REPORT_XML));
- Source xslt = new StreamSource(
- new ClassPathResource(getResourcePath(REPORT_TO_HTML_INVALID_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(getResourcePath(
+ REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
+ REPORT_TO_HTML_INVALID_XSLT)).getInputStream());
+
+ byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
+ .getBytes();
- byte[] documentData = FileSystemUtils
- .read(xmlResource.getInputStream()).getBytes();
try {
Document output1 = transformer.transform(documentData, xslt);
} catch (TransformerException e) {
return; // ok
}
+
fail();
}
/**
* Transforms a file using a non-well formed xslt. Verifies that a
* TransformerException is thrown.
- *
+ *
*/
public void testTransformNonWellformedXslt() throws IOException {
XslTransformer transformer = new XslTransformer();
- InputResource xmlResource = new ClassPathResource(
- getResourcePath(REPORT_XML));
- Source xslt = new StreamSource(
- new ClassPathResource(getResourcePath(
- REPORT_TO_HTML_NONWELLFORMED_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(getResourcePath(
+ REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
+ REPORT_TO_HTML_NONWELLFORMED_XSLT)).getInputStream());
+
+ byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
+ .getBytes();
- byte[] documentData = FileSystemUtils
- .read(xmlResource.getInputStream()).getBytes();
try {
Document output1 = transformer.transform(documentData, xslt);
} catch (TransformerException e) {
return; // ok
}
+
fail();
}
/**
* Transforms a file using a class path resolver.
- *
+ *
*/
public void testTransformUsingClassPathResolver() throws Exception {
XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
InputResource xmlResource = new ClassPathResource(getResourcePath(
- REPORT_XML));
- Source xslt = new StreamSource(new ClassPathResource(
- getResourcePath(REPORT_TO_HTML2_XSLT)).getInputStream());
+ REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
+ REPORT_TO_HTML2_XSLT)).getInputStream());
+
+ byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
+ .getBytes();
- byte[] documentData = FileSystemUtils
- .read(xmlResource.getInputStream()).getBytes();
-
Document output1 = transformer.transform(documentData, xslt);
- Document expected = DomUtils.read(new ClassPathResource(
- getResourcePath("output-reportToHtml-report.xml"))
- .getInputStream());
+ Document expected = DomUtils.read(new ClassPathResource(getResourcePath(
+ "output-reportToHtml-report.xml")).getInputStream());
XmlUtils.assertEquals("doc", expected, output1);
}
/**
* Transforms a file to text output. Verifies the file is transformed
* correctly.
- *
+ *
*/
public void testTransformToTextOutput() throws Exception {
XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
- InputResource xmlResource = new ClassPathResource(
- getResourcePath(REPORT_XML));
- Source xslt = new StreamSource(
- new ClassPathResource(getResourcePath(REPORT_TO_TEXT_XSLT)).getInputStream());
+ InputResource xmlResource = new ClassPathResource(getResourcePath(
+ REPORT_XML));
+ Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
+ REPORT_TO_TEXT_XSLT)).getInputStream());
+
+ byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream())
+ .getBytes();
- byte[] documentData = FileSystemUtils
- .read(xmlResource.getInputStream()).getBytes();
-
String result = transformer.textTransform(documentData, xslt);
String expected = "Hello world!";
assertEquals("text transform", expected, result);
}
-
+
/**
- * Tests resolving a file using {@link XslTransformer#resolve(String)} with the
- * default resolver where the file does not exist.
+ * Tests resolving a file using {@link XslTransformer#resolve(String)} with the
+ * default resolver where the file does not exist.
*
*/
- public void testResolveWithDefaultResolverFileNotFound() {
+ public void testResolveWithDefaultResolverFileNotFound() {
XslTransformer transformer = new XslTransformer();
- try {
- Source source = transformer.resolve("org/wamblee/xml/utilities-nonexistent.xsl");
- } catch (TransformerException e) {
+
+ try {
+ Source source = transformer.resolve(
+ "org/wamblee/xml/utilities-nonexistent.xsl");
+ } catch (TransformerException e) {
return; // ok
}
+
fail();
}
-
-
+
/**
- * Tests resolving a file using {@link XslTransformer#resolve(String)} with the
- * default resolver.
+ * Tests resolving a file using {@link XslTransformer#resolve(String)} with the
+ * default resolver.
*
*/
- public void testResolveWithClasspathResolver() throws Exception {
+ public void testResolveWithClasspathResolver() throws Exception {
XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
Source source = transformer.resolve(getResourcePath(INCLUDED_XSL_FILE));
- assert(source instanceof StreamSource);
- StreamSource ssource = (StreamSource)source;
+ assert (source instanceof StreamSource);
+
+ StreamSource ssource = (StreamSource) source;
String data = FileSystemUtils.read(ssource.getInputStream());
- String expected = FileSystemUtils.read(new ClassPathResource(getResourcePath(INCLUDED_XSL_FILE)).getInputStream());
+ String expected = FileSystemUtils.read(new ClassPathResource(
+ getResourcePath(INCLUDED_XSL_FILE)).getInputStream());
assertEquals(expected, data);
}
-
}
-
-
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.concurrency.spring;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
+
import org.wamblee.concurrency.Lock;
+
/**
- * Locking advice. This automatically synchronized an object using a given lock.
+ * Locking advice. This automatically synchronized an object using a given
+ * lock.
*
* @author Erik Brakkee
*/
public class LockAdvice implements MethodInterceptor {
-
/**
- * Lock to use.
+ * Lock to use.
*/
- private Lock lock;
-
- /**
+ private Lock lock;
+
+/**
* Constructs lock advice.
* @param aLock Lock to use.
*/
- public LockAdvice(Lock aLock) {
- lock = aLock;
+ public LockAdvice(Lock aLock) {
+ lock = aLock;
}
-
+
/* (non-Javadoc)
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
- public Object invoke(MethodInvocation aInvocation) throws Throwable {
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aInvocation DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws Throwable DOCUMENT ME!
+ */
+ public Object invoke(MethodInvocation aInvocation)
+ throws Throwable {
lock.acquire();
- try {
- return aInvocation.proceed();
- } finally {
+
+ try {
+ return aInvocation.proceed();
+ } finally {
lock.release();
}
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
+
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
+
import org.wamblee.general.BeanFactory;
import org.wamblee.general.BeanFactoryException;
import org.wamblee.general.BeanKernel;
+
/**
* Bean factory which uses Spring. This bean factory cannot be configured
* directly in the {@link org.wamblee.general.BeanKernel} because it does not
* it must tbe subclassed to provide a default constructor.
*/
public class SpringBeanFactory implements BeanFactory {
-
+ /**
+ * DOCUMENT ME!
+ */
private BeanFactoryReference factoryReference;
- /**
+/**
* Constructs the bean factory.
*
* @param aSelector
public SpringBeanFactory(String aSelector, String aFactoryName) {
try {
BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator
- .getInstance(aSelector);
+ .getInstance(aSelector);
factoryReference = locator.useBeanFactory(aFactoryName);
} catch (BeansException e) {
throw new BeanFactoryException(
- "Could not load bean factory: selector = '" + aSelector
- + "', factory = '" + aFactoryName + "'", e);
+ "Could not load bean factory: selector = '" + aSelector
+ + "', factory = '" + aFactoryName + "'", e);
}
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.general.BeanFactory#find(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aId DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Object find(String aId) {
return find(aId, Object.class);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.general.BeanFactory#find(java.lang.Class)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aClass DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public <T> T find(Class<T> aClass) {
return find(aClass.getName(), aClass);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.general.BeanFactory#find(java.lang.String,
* java.lang.Class)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aId DOCUMENT ME!
+ * @param aClass DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws BeanFactoryException DOCUMENT ME!
+ */
public <T> T find(String aId, Class<T> aClass) {
try {
Object obj = factoryReference.getFactory().getBean(aId, aClass);
assert obj != null;
+
return aClass.cast(obj);
} catch (BeansException e) {
throw new BeanFactoryException(e.getMessage(), e);
}
}
-
+
/**
- * Gets the spring bean factory.
- * @return Spring bean factory.
+ * Gets the spring bean factory.
+ *
+ * @return Spring bean factory.
*/
- public org.springframework.beans.factory.BeanFactory getSpringBeanFactory() {
- return factoryReference.getFactory();
+ public org.springframework.beans.factory.BeanFactory getSpringBeanFactory() {
+ return factoryReference.getFactory();
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.persistence.hibernate;
import java.util.ArrayList;
import java.util.Arrays;
+
/**
- * Hibernate mapping files to use.
+ * Hibernate mapping files to use.
*
* @author Erik Brakkee
*/
public class HibernateMappingFiles extends ArrayList<String> {
-
- /**
+/**
* Constructs an empty list of hibernate mapping files.
*
*/
- public HibernateMappingFiles() {
- super();
+ public HibernateMappingFiles() {
+ super();
}
-
- /**
+
+/**
* Constructs the list of Spring config files.
* @param aFiles Files.
*/
- public HibernateMappingFiles(String[] aFiles) {
- super();
+ public HibernateMappingFiles(String[] aFiles) {
+ super();
addAll(Arrays.asList(aFiles));
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.persistence.hibernate;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
+
+import org.wamblee.persistence.Persistent;
+
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.orm.hibernate3.HibernateTemplate;
-import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
-import org.wamblee.persistence.Persistent;
/**
- * Extension of
- * {@link org.springframework.orm.hibernate.support.HibernateDaoSupport}.
+ * Extension of {@link
+ * org.springframework.orm.hibernate.support.HibernateDaoSupport}.
*
* @author Erik Brakkee
*/
public class HibernateSupport extends HibernateDaoSupport {
-
- private static final Log LOG = LogFactory.getLog(HibernateSupport.class);
-
/**
- * This class provided an equality operation based on the object reference
- * of the wrapped object. This is required because we cannto assume that the
- * equals operation has any meaning for different types of persistent
- * objects. This allows us to use the standard collection classes for
- * detecting cyclic dependences and avoiding recursion.
- *
+ * DOCUMENT ME!
*/
- private static final class ObjectElem {
- private Object object;
-
- public ObjectElem(Object aObject) {
- object = aObject;
- }
-
- public boolean equals(Object aObj) {
- return ((ObjectElem) aObj).object == object;
- }
-
- public int hashCode() {
- return object.hashCode();
- }
- }
+ private static final Log LOG = LogFactory.getLog(HibernateSupport.class);
- /**
+/**
* Constructs the object.
*
*/
}
/**
- * Performes a hibernate <code>Session.merge()</code> and updates the
- * object with the correct primary key and version. This is an extension to
- * the hibernate merge operation because hibernate itself leaves the object
- * passed to merge untouched.
- *
- * Use this method with extreme caution since it will recursively load all
- * objects that the current object has relations with and for which
- * cascade="merge" was specified in the Hibernate mapping file.
- *
- * @param aPersistent
- * Object to merge.
+ * Performes a hibernate <code>Session.merge()</code> and updates
+ * the object with the correct primary key and version. This is an
+ * extension to the hibernate merge operation because hibernate itself
+ * leaves the object passed to merge untouched. Use this method with
+ * extreme caution since it will recursively load all objects that the
+ * current object has relations with and for which cascade="merge" was
+ * specified in the Hibernate mapping file.
+ *
+ * @param aPersistent Object to merge.
*/
public void merge(Persistent aPersistent) {
merge(getHibernateTemplate(), aPersistent);
}
/**
- * As {@link #merge(Persistent)} but with a given template. This method can
- * be accessed in a static way.
- *
- * @param aTemplate
- * Hibernate template
- * @param aPersistent
- * Object to merge.
+ * As {@link #merge(Persistent)} but with a given template. This
+ * method can be accessed in a static way.
+ *
+ * @param aTemplate Hibernate template
+ * @param aPersistent Object to merge.
*/
public static void merge(HibernateTemplate aTemplate, Persistent aPersistent) {
Persistent merged = (Persistent) aTemplate.merge(aPersistent);
}
/**
- * Copies primary keys and version from the result of the merged to the
- * object that was passed to the merge operation. It does this by traversing
- * the properties of the object. It copies the primary key and version for
- * objects that implement {@link Persistent} and applies the same rules to
- * objects in maps and sets as well (i.e. recursively).
- *
- * @param aPersistent
- * Object whose primary key and version are to be set.
- * @param aMerged
- * Object that was the result of the merge.
- * @param aProcessed
- * List of already processed Persistent objects of the persistent
- * part.
+ * Copies primary keys and version from the result of the merged to
+ * the object that was passed to the merge operation. It does this by
+ * traversing the properties of the object. It copies the primary key and
+ * version for objects that implement {@link Persistent} and applies the
+ * same rules to objects in maps and sets as well (i.e. recursively).
+ *
+ * @param aPersistent Object whose primary key and version are to be set.
+ * @param aMerged Object that was the result of the merge.
+ * @param aProcessed List of already processed Persistent objects of the
+ * persistent part.
+ *
+ * @throws RuntimeException DOCUMENT ME!
*/
public static void processPersistent(Persistent aPersistent,
- Persistent aMerged, List<ObjectElem> aProcessed) {
- if (aPersistent == null && aMerged == null) {
+ Persistent aMerged, List<ObjectElem> aProcessed) {
+ if ((aPersistent == null) && (aMerged == null)) {
return;
}
- if (aPersistent == null || aMerged == null) {
+
+ if ((aPersistent == null) || (aMerged == null)) {
throw new RuntimeException("persistent or merged object is null '"
- + aPersistent + "'" + " '" + aMerged + "'");
+ + aPersistent + "'" + " '" + aMerged + "'");
}
+
ObjectElem elem = new ObjectElem(aPersistent);
+
if (aProcessed.contains(elem)) {
return; // already processed.
}
+
aProcessed.add(elem);
LOG.debug("Setting pk/version on " + aPersistent + " from " + aMerged);
- if (aPersistent.getPrimaryKey() != null
+ if ((aPersistent.getPrimaryKey() != null)
&& !aMerged.getPrimaryKey().equals(aPersistent.getPrimaryKey())) {
LOG.error("Mismatch between primary key values: " + aPersistent
- + " " + aMerged);
+ + " " + aMerged);
} else {
aPersistent.setPersistedVersion(aMerged.getPersistedVersion());
aPersistent.setPrimaryKey(aMerged.getPrimaryKey());
}
Method[] methods = aPersistent.getClass().getMethods();
+
for (Method getter : methods) {
if (getter.getName().startsWith("get")) {
Class returnType = getter.getReturnType();
try {
if (Set.class.isAssignableFrom(returnType)) {
- Set merged = (Set) getter.invoke(aMerged);
+ Set merged = (Set) getter.invoke(aMerged);
Set persistent = (Set) getter.invoke(aPersistent);
processSet(persistent, merged, aProcessed);
} else if (List.class.isAssignableFrom(returnType)) {
- List merged = (List) getter.invoke(aMerged);
+ List merged = (List) getter.invoke(aMerged);
List persistent = (List) getter.invoke(aPersistent);
processList(persistent, merged, aProcessed);
} else if (Map.class.isAssignableFrom(returnType)) {
- Map merged = (Map) getter.invoke(aMerged);
+ Map merged = (Map) getter.invoke(aMerged);
Map persistent = (Map) getter.invoke(aPersistent);
processMap(persistent, merged, aProcessed);
} else if (Persistent.class.isAssignableFrom(returnType)) {
- Persistent merged = (Persistent) getter.invoke(aMerged);
- Persistent persistent = (Persistent) getter
- .invoke(aPersistent);
+ Persistent merged = (Persistent) getter.invoke(aMerged);
+ Persistent persistent = (Persistent) getter.invoke(aPersistent);
processPersistent(persistent, merged, aProcessed);
} else if (returnType.isArray()
- && Persistent.class.isAssignableFrom(returnType
- .getComponentType())) {
- Persistent[] merged = (Persistent[]) getter
- .invoke(aMerged);
- Persistent[] persistent = (Persistent[]) getter
- .invoke(aPersistent);
+ && Persistent.class.isAssignableFrom(
+ returnType.getComponentType())) {
+ Persistent[] merged = (Persistent[]) getter.invoke(aMerged);
+ Persistent[] persistent = (Persistent[]) getter.invoke(aPersistent);
+
for (int i = 0; i < persistent.length; i++) {
processPersistent(persistent[i], merged[i],
- aProcessed);
+ aProcessed);
}
}
} catch (InvocationTargetException e) {
}
}
}
-
}
/**
* Process the persistent objects in the collections.
- *
- * @param aPersistent
- * Collection in the original object.
- * @param aMerged
- * Collection as a result of the merge.
- * @param aProcessed
- * List of processed persistent objects.
+ *
+ * @param aPersistent Collection in the original object.
+ * @param aMerged Collection as a result of the merge.
+ * @param aProcessed List of processed persistent objects.
+ *
+ * @throws RuntimeException DOCUMENT ME!
*/
public static void processList(List aPersistent, List aMerged,
- List<ObjectElem> aProcessed) {
- Object[] merged = aMerged.toArray();
+ List<ObjectElem> aProcessed) {
+ Object[] merged = aMerged.toArray();
Object[] persistent = aPersistent.toArray();
+
if (merged.length != persistent.length) {
throw new RuntimeException("Array sizes differ " + merged.length
- + " " + persistent.length);
+ + " " + persistent.length);
}
+
for (int i = 0; i < merged.length; i++) {
assert merged[i].equals(persistent[i]);
+
if (merged[i] instanceof Persistent) {
processPersistent((Persistent) persistent[i],
- (Persistent) merged[i], aProcessed);
+ (Persistent) merged[i], aProcessed);
}
}
}
/**
* Process the persistent objects in sets.
- *
- * @param aPersistent
- * Collection in the original object.
- * @param aMerged
- * Collection as a result of the merge.
- * @param aProcessed
- * List of processed persistent objects.
+ *
+ * @param aPersistent Collection in the original object.
+ * @param aMerged Collection as a result of the merge.
+ * @param aProcessed List of processed persistent objects.
+ *
+ * @throws RuntimeException DOCUMENT ME!
*/
public static void processSet(Set aPersistent, Set aMerged,
- List<ObjectElem> aProcessed) {
+ List<ObjectElem> aProcessed) {
if (aMerged.size() != aPersistent.size()) {
throw new RuntimeException("Array sizes differ " + aMerged.size()
- + " " + aPersistent.size());
+ + " " + aPersistent.size());
}
+
for (Object merged : aMerged) {
// Find the object that equals the merged[i]
for (Object persistent : aPersistent) {
if (persistent.equals(merged)) {
processPersistent((Persistent) persistent,
- (Persistent) merged, aProcessed);
+ (Persistent) merged, aProcessed);
+
break;
}
}
/**
* Process the Map objects in the collections.
- *
- * @param aPersistent
- * Collection in the original object.
- * @param aMerged
- * Collection as a result of the merge.
- * @param aProcessed
- * List of processed persistent objects.
+ *
+ * @param aPersistent Collection in the original object.
+ * @param aMerged Collection as a result of the merge.
+ * @param aProcessed List of processed persistent objects.
+ *
+ * @throws RuntimeException DOCUMENT ME!
*/
public static void processMap(Map aPersistent, Map aMerged,
- List<ObjectElem> aProcessed) {
+ List<ObjectElem> aProcessed) {
if (aMerged.size() != aPersistent.size()) {
throw new RuntimeException("Sizes differ " + aMerged.size() + " "
- + aPersistent.size());
+ + aPersistent.size());
}
+
Set keys = aMerged.keySet();
+
for (Object key : keys) {
if (!aPersistent.containsKey(key)) {
throw new RuntimeException("Key '" + key + "' not found");
}
- Object mergedValue = aMerged.get(key);
+
+ Object mergedValue = aMerged.get(key);
Object persistentValue = aPersistent.get(key);
+
if (mergedValue instanceof Persistent) {
if (persistentValue instanceof Persistent) {
processPersistent((Persistent) persistentValue,
- (Persistent) mergedValue, aProcessed);
+ (Persistent) mergedValue, aProcessed);
} else {
throw new RuntimeException(
- "Value in original object is null, whereas merged object contains a value");
+ "Value in original object is null, whereas merged object contains a value");
}
}
}
}
+ /**
+ * This class provided an equality operation based on the object
+ * reference of the wrapped object. This is required because we cannto
+ * assume that the equals operation has any meaning for different types of
+ * persistent objects. This allows us to use the standard collection
+ * classes for detecting cyclic dependences and avoiding recursion.
+ */
+ private static final class ObjectElem {
+ private Object object;
+
+ public ObjectElem(Object aObject) {
+ object = aObject;
+ }
+
+ public boolean equals(Object aObj) {
+ return ((ObjectElem) aObj).object == object;
+ }
+
+ public int hashCode() {
+ return object.hashCode();
+ }
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.concurrency.spring;
import org.springframework.aop.framework.ProxyFactoryBean;
+
import org.wamblee.concurrency.AbstractLockTestCase;
import org.wamblee.concurrency.JvmLock;
import org.wamblee.concurrency.spring.LockAdvice;
+
import org.wamblee.test.TimingUtils;
+
/**
- *
+ * DOCUMENT ME!
*
* @author Erik Brakkee
*/
public class LockAdviceTest extends AbstractLockTestCase {
-
- private class Runner implements Runnable {
- public void run() {
- LockAdviceTest.this.getTracker().eventOccurred(ACQUIRED);
- TimingUtils.sleep(SLEEP_TIME);
- }
- }
-
+ /**
+ * DOCUMENT ME!
+ */
private Runnable target;
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.concurrency.AbstractLockTestCase#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
super.setUp();
-
- Runner runner = new Runner();
- LockAdvice advice = new LockAdvice(new JvmLock());
-
+
+ Runner runner = new Runner();
+ LockAdvice advice = new LockAdvice(new JvmLock());
+
ProxyFactoryBean support = new ProxyFactoryBean();
- support.setInterfaces(new Class[]{ Runnable.class });
+ support.setInterfaces(new Class[] { Runnable.class });
support.setTarget(runner);
support.addAdvice(advice);
- target = (Runnable)support.getObject();
-
+ target = (Runnable) support.getObject();
}
/*
* (non-Javadoc)
- *
+ *
* @see org.wamblee.concurrency.AbstractLockTestCase#runThread()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws RuntimeException DOCUMENT ME!
+ */
@Override
protected Thread runThread() {
Thread t = new Thread(new Runnable() {
- public void run() {
- try {
- getTracker().eventOccurred(STARTED);
- target.run();
- getTracker().eventOccurred(RELEASED);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- };
- });
+ public void run() {
+ try {
+ getTracker().eventOccurred(STARTED);
+ target.run();
+ getTracker().eventOccurred(RELEASED);
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ }
+ ;
+ });
t.start();
+
return t;
}
+ private class Runner implements Runnable {
+ public void run() {
+ LockAdviceTest.this.getTracker().eventOccurred(ACQUIRED);
+ TimingUtils.sleep(SLEEP_TIME);
+ }
+ }
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.general.spring;
+import junit.framework.TestCase;
+
import org.wamblee.general.BeanFactoryException;
-import junit.framework.TestCase;
/**
* Tests the spring bean factory.
* @author Erik Brakkee
*/
public class SpringBeanFactoryTest extends TestCase {
-
/*
* (non-Javadoc)
- *
+ *
* @see junit.framework.TestCase#setUp()
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
super.setUp();
-
}
+ /**
+ * DOCUMENT ME!
+ */
public void testExistingBeanRefContext() {
- SpringBeanFactory factory = new SpringBeanFactory(
- "org/wamblee/general/beanRefContext.xml", "test");
+ SpringBeanFactory factory = new SpringBeanFactory("org/wamblee/general/beanRefContext.xml",
+ "test");
- String value1 = factory.find(String.class);
+ String value1 = factory.find(String.class);
assertEquals("hello", value1);
+
String value2 = (String) factory.find("java.lang.String");
assertEquals("hello", value2);
+
String value3 = factory.find("java.lang.String", String.class);
assertEquals("hello", value3);
} catch (BeanFactoryException e) {
return; // ok
}
+
fail();
}
+ /**
+ * DOCUMENT ME!
+ */
public void testUnknownBeanFactory() {
try {
- new SpringBeanFactory(
- "org/wamblee/general/beanRefContext.xml", "unknown");
+ new SpringBeanFactory("org/wamblee/general/beanRefContext.xml",
+ "unknown");
} catch (BeanFactoryException e) {
return; // ok
}
+
fail();
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.general.spring;
/**
* @author Erik Brakkee
*/
public class TestBeanFactory extends SpringBeanFactory {
-
-
- public TestBeanFactory() {
+/**
+ * Creates a new TestBeanFactory object.
+ */
+ public TestBeanFactory() {
super("org/wamblee/general/beanRefContext.xml", "test");
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
-
+ */
package org.wamblee.test.spring;
+import org.hibernate.cfg.Configuration;
+
+import org.hibernate.tool.hbm2ddl.SchemaExport;
+
import java.io.File;
import java.io.IOException;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
- * Exporting the hibernate mapping.
+ * Exporting the hibernate mapping.
*
* @author Erik Brakkee
*/
public final class HibernateExporter {
-
- /**
+/**
* Disabled constructor.
*
*/
- private HibernateExporter() {
+ private HibernateExporter() {
// Empty
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aArgs DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public static void main(String[] aArgs) throws IOException {
- String file = aArgs[0];
- File dir = new File(aArgs[1]);
-
- Configuration conf = HibernateUtils.getConfiguration(dir);
-
- SchemaExport export = new SchemaExport(conf);
+ String file = aArgs[0];
+ File dir = new File(aArgs[1]);
+
+ Configuration conf = HibernateUtils.getConfiguration(dir);
+
+ SchemaExport export = new SchemaExport(conf);
export.setDelimiter(";");
- export.setOutputFile(file);
+ export.setOutputFile(file);
export.create(true, false);
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.test.spring;
+import org.hibernate.cfg.Configuration;
+
+import org.hibernate.tool.hbm2ddl.SchemaUpdate;
+
import java.io.File;
import java.io.IOException;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.tool.hbm2ddl.SchemaUpdate;
/**
* Exporting the hibernate mapping.
* @author Erik Brakkee
*/
public final class HibernateUpdater {
-
- /**
+/**
* Disabled constructor.
*
*/
- private HibernateUpdater() {
+ private HibernateUpdater() {
// Empty
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aArgs DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public static void main(String[] aArgs) throws IOException {
- String file = aArgs[0];
- File dir = new File(file);
+ String file = aArgs[0];
+ File dir = new File(file);
- Configuration conf = HibernateUtils.getConfiguration(dir);
+ Configuration conf = HibernateUtils.getConfiguration(dir);
- SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf);
+ SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf);
lSchemaUpdate.execute(true, true);
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.test.spring;
+import org.apache.oro.io.AwkFilenameFilter;
+
+import org.hibernate.cfg.Configuration;
+
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.InputResource;
+
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
+
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
-import org.apache.oro.io.AwkFilenameFilter;
-import org.hibernate.cfg.Configuration;
-import org.wamblee.io.ClassPathResource;
-import org.wamblee.io.InputResource;
/**
* Hibernate utilities.
* @author Erik Brakkee
*/
public final class HibernateUtils {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final String DATABASE_PROPS = "test.database.properties";
- /**
+/**
* Disabled.
*
*/
- private HibernateUtils() {
+ private HibernateUtils() {
// Empty
}
-
+
/**
+ * DOCUMENT ME!
+ *
* @param aDir
+ *
* @return
+ *
+ * @throws IOException DOCUMENT ME!
*/
- public static Configuration getConfiguration(File aDir) throws IOException {
- Configuration conf = new Configuration();
- File[] files = aDir.listFiles((FileFilter) (new AwkFilenameFilter(
- ".*\\.hbm\\.xml")));
+ public static Configuration getConfiguration(File aDir)
+ throws IOException {
+ Configuration conf = new Configuration();
+ File[] files = aDir.listFiles((FileFilter) (new AwkFilenameFilter(
+ ".*\\.hbm\\.xml")));
+
for (File f : files) {
System.out.println("Mapping file: " + f);
conf.addFile(f);
for (Map.Entry<String, String> entry : dbProps.entrySet()) {
System.out.println("Property: " + entry.getKey() + "="
- + entry.getValue());
+ + entry.getValue());
conf.setProperty(entry.getKey(), entry.getValue());
}
return conf;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
private static Map<String, String> getHibernateProperties()
- throws IOException {
-
+ throws IOException {
System.out.println("Reading properties file: " + DATABASE_PROPS);
+
InputResource lPropFile = new ClassPathResource(DATABASE_PROPS);
- Properties props = new Properties();
+ Properties props = new Properties();
props.load(lPropFile.getInputStream());
Map<String, String> result = new TreeMap<String, String>();
- result.put("hibernate.connection.driver_class", props
- .getProperty("database.driver"));
- result.put("hibernate.connection.url", props
- .getProperty("database.url"));
- result.put("hibernate.connection.username", props
- .getProperty("database.username"));
- result.put("hibernate.connection.password", props
- .getProperty("database.password"));
+ result.put("hibernate.connection.driver_class",
+ props.getProperty("database.driver"));
+ result.put("hibernate.connection.url", props.getProperty("database.url"));
+ result.put("hibernate.connection.username",
+ props.getProperty("database.username"));
+ result.put("hibernate.connection.password",
+ props.getProperty("database.password"));
return result;
}
-
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.test.spring;
import org.springframework.beans.BeansException;
+
import org.springframework.context.ApplicationContext;
+
import org.wamblee.general.BeanFactory;
import org.wamblee.general.BeanFactoryException;
+
/**
- * Bean factory which uses Spring.
+ * Bean factory which uses Spring.
*
* @author Erik Brakkee
*/
public class TestSpringBeanFactory implements BeanFactory {
-
- private ApplicationContext context;
-
+ /**
+ * DOCUMENT ME!
+ */
+ private ApplicationContext context;
+
+/**
+ * Creates a new TestSpringBeanFactory object.
+ *
+ * @param aContext DOCUMENT ME!
+ */
public TestSpringBeanFactory(ApplicationContext aContext) {
- context = aContext;
+ context = aContext;
}
/* (non-Javadoc)
* @see org.wamblee.general.BeanFactory#find(java.lang.String)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aId DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Object find(String aId) {
- return find(aId, Object.class);
+ return find(aId, Object.class);
}
/* (non-Javadoc)
* @see org.wamblee.general.BeanFactory#find(java.lang.Class)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aClass DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public <T> T find(Class<T> aClass) {
return find(aClass.getName(), aClass);
}
/* (non-Javadoc)
* @see org.wamblee.general.BeanFactory#find(java.lang.String, java.lang.Class)
*/
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aId DOCUMENT ME!
+ * @param aClass DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws BeanFactoryException DOCUMENT ME!
+ */
public <T> T find(String aId, Class<T> aClass) {
try {
Object obj = context.getBean(aId, aClass);
- assert obj != null;
- return aClass.cast(obj);
- } catch (BeansException e) {
+ assert obj != null;
+
+ return aClass.cast(obj);
+ } catch (BeansException e) {
throw new BeanFactoryException(e.getMessage(), e);
}
}
-
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.test.spring;
import java.util.Map;
+
/**
* Transaction callback for testing. The test will fail if any type of exception
* is thrown.
*/
public interface TestTransactionCallback {
/**
- * Executes code within a transaction, causing the testcase to fail if any
- * type of exception is thrown.
- *
+ * Executes code within a transaction, causing the testcase to fail
+ * if any type of exception is thrown.
+ *
* @return A map containg the resuls of the execution. This is a convenient
* method of returning multiple results from a call.
+ *
+ * @throws Exception DOCUMENT ME!
*/
Map execute() throws Exception;
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.test.spring;
/**
*/
public interface TestTransactionCallbackWithoutResult {
/**
- * Executes code within a transaction, causing the testcase to fail if any
- * type of exception is thrown.
- *
+ * Executes code within a transaction, causing the testcase to fail
+ * if any type of exception is thrown.
+ *
+ * @throws Exception DOCUMENT ME!
*/
void execute() throws Exception;
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+
/**
* A Class Adapter adapts a given class to a Component.
- *
+ *
* @author Erik Brakkee
*/
public class ClassAdapter extends AbstractComponent<Object> {
+ /**
+ * DOCUMENT ME!
+ */
+ private ClassConfiguration _classConfig;
+
+ /**
+ * Creates a new ClassAdapter object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aClassConfig DOCUMENT ME!
+ */
+ public ClassAdapter(String aName, ClassConfiguration aClassConfig) {
+ super(aName,
+ aClassConfig.getProvidedInterfaces()
+ .toArray(new ProvidedInterface[0]),
+ aClassConfig.getRequiredInterfaces()
+ .toArray(new RequiredInterface[0]));
+ _classConfig = aClassConfig;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ protected Object doStart(Scope aScope) {
+ Object obj = _classConfig.create(aScope);
+ _classConfig.inject(aScope, obj);
+
+ for (ProvidedInterface provided : getProvidedInterfaces()) {
+ addInterface(provided, obj, aScope);
+ }
+
+ return obj;
+ }
- private ClassConfiguration _classConfig;
-
- public ClassAdapter(String aName, ClassConfiguration aClassConfig) {
- super(aName,
- aClassConfig.getProvidedInterfaces().toArray(new ProvidedInterface[0]),
- aClassConfig.getRequiredInterfaces().toArray(new RequiredInterface[0]));
- _classConfig = aClassConfig;
- }
-
- @Override
- protected Object doStart(Scope aScope) {
-
- Object obj = _classConfig.create(aScope);
- _classConfig.inject(aScope, obj);
-
- for (ProvidedInterface provided: getProvidedInterfaces()) {
- addInterface(provided, obj, aScope);
- }
-
- return obj;
- }
-
- @Override
- protected void doStop(Object aRuntime) {
- // Empty.
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
+ @Override
+ protected void doStop(Object aRuntime) {
+ // Empty.
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.adapters;
-import java.util.ArrayList;
-import java.util.List;
-
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+import java.util.ArrayList;
+import java.util.List;
+
+
/**
- * The class configuration encapsulates the knowledge of how to wrap a class as a component.
- *
- * @author Erik Brakkee
+ * The class configuration encapsulates the knowledge of how to wrap a
+ * class as a component.
*
+ * @author Erik Brakkee
*/
public class ClassConfiguration {
+ /**
+ * DOCUMENT ME!
+ */
+ private Class _class;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private ConstructorConfiguration constructorConfig;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private ObjectConfiguration objectConfig;
+
+/**
+ * Constructs the configuration. By default no constructor is selected and
+ * one of {@link #select(Class...)} or
+ * {@link #greedy()} must be called.
+ * @param aClass Class to construct.
+ */
+ public ClassConfiguration(Class aClass) {
+ _class = aClass;
+ constructorConfig = new ConstructorConfiguration(aClass);
+ objectConfig = new ObjectConfiguration(aClass);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public ConstructorConfiguration getConstructorConfig() {
+ return constructorConfig;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public ObjectConfiguration getObjectConfig() {
+ return objectConfig;
+ }
+
+ /**
+ * Creates the object in the given scope.
+ *
+ * @param aScope Scope containing required interfaces for this object.
+ *
+ * @return object.
+ */
+ public Object create(Scope aScope) {
+ return constructorConfig.create(aScope);
+ }
+
+ /**
+ * Injects required interfaces through the setters
+ *
+ * @param aScope Scope in which injection takes place.
+ * @param aObject Object to inject into.
+ */
+ public void inject(Scope aScope, Object aObject) {
+ objectConfig.inject(aScope, aObject);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public List<ProvidedInterface> getProvidedInterfaces() {
+ List<ProvidedInterface> result = new ArrayList<ProvidedInterface>();
+ result.add(new DefaultProvidedInterface("provided", _class));
+
+ return result;
+ }
- private Class _class;
- private ConstructorConfiguration constructorConfig;
- private ObjectConfiguration objectConfig;
-
- /**
- * Constructs the configuration. By default no constructor is selected and
- * one of {@link #select(Class...)} or
- * {@link #greedy()} must be called.
- * @param aClass Class to construct.
- */
- public ClassConfiguration(Class aClass) {
- _class = aClass;
- constructorConfig = new ConstructorConfiguration(aClass);
- objectConfig = new ObjectConfiguration(aClass);
- }
-
- public ConstructorConfiguration getConstructorConfig() {
- return constructorConfig;
- }
-
- public ObjectConfiguration getObjectConfig() {
- return objectConfig;
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public List<RequiredInterface> getRequiredInterfaces() {
+ List<RequiredInterface> result = new ArrayList<RequiredInterface>();
+ result.addAll(constructorConfig.getRequiredInterfaces());
+ result.addAll(objectConfig.getRequiredInterfaces());
- /**
- * Creates the object in the given scope.
- * @param aScope Scope containing required interfaces for this object.
- * @return object.
- */
- public Object create(Scope aScope) {
- return constructorConfig.create(aScope);
- }
-
- /**
- * Injects required interfaces through the setters
- * @param aObject Object to inject into.
- * @param aScope Scope in which injection takes place.
- */
- public void inject(Scope aScope, Object aObject) {
- objectConfig.inject(aScope, aObject);
- }
-
- public List<ProvidedInterface> getProvidedInterfaces() {
- List<ProvidedInterface> result = new ArrayList<ProvidedInterface>();
- result.add(new DefaultProvidedInterface("provided", _class));
- return result;
- }
-
- public List<RequiredInterface> getRequiredInterfaces() {
- List<RequiredInterface> result = new ArrayList<RequiredInterface>();
- result.addAll(constructorConfig.getRequiredInterfaces());
- result.addAll(objectConfig.getRequiredInterfaces());
- return result;
- }
+ return result;
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+import org.wamblee.collections.CollectionFilter;
+
+import org.wamblee.conditions.Condition;
+
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.core.SystemAssemblyException;
+
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import org.wamblee.collections.CollectionFilter;
-import org.wamblee.conditions.Condition;
-import org.wamblee.system.core.RequiredInterface;
-import org.wamblee.system.core.Scope;
-import org.wamblee.system.core.SystemAssemblyException;
/**
- * Class that allows configuration of the constructor to use.
- *
- * In particular, it provides:
- * <ul>
- * <li> Selection of a constructor using explicit selection
- * {@link #select(Class...)} or using the most greedy constructor
- * {@link #greedy()}.
- * </li>
- * <li>
- * Selection of methods to invoke to inject other objects into the object.
- * </li>
- * <li> Selection of fields to set.
- * </li>
- * </ul>
+ * Class that allows configuration of the constructor to use. In
+ * particular, it provides:
+ * <ul>
+ * <li>Selection of a constructor using explicit selection {@link
+ * #select(Class...)} or using the most greedy constructor {@link
+ * #greedy()}.</li>
+ * <li>Selection of methods to invoke to inject other objects into
+ * the object.</li>
+ * <li>Selection of fields to set.</li>
+ * </ul>
*/
public class ConstructorConfiguration {
- private Class clazz;
- private Constructor<?> constructor;
- private ParameterValues values;
- private boolean publicOnly;
-
- /**
- * Constructs the configuration. By default the public constructor with the
- * most arguments will be used.
- * @param aClass Class to construct.
- */
- public ConstructorConfiguration(Class aClass) {
- clazz = aClass;
- constructor = null;
- publicOnly = true;
- }
-
- /**
- * Sets whether or no non public constructors are also considered.
- * Reset the choice of a constructor to its default.
- * @param aNonPublic
- * @return
- */
- public ConstructorConfiguration setNonPublic(boolean aNonPublic) {
- publicOnly = !aNonPublic;
- constructor = null;
- values = null;
- return this;
- }
-
- /**
- * Selects an explicit constructor.
- * @param aTypes Arguments of the constructor.
- * @return Return the injector to allow call chaining.
- */
- public ConstructorConfiguration select(Class... aTypes) {
- try {
- constructor = clazz.getDeclaredConstructor(aTypes);
- } catch (Exception e) {
- throw new SystemAssemblyException(e.getMessage(), e);
- }
- resetValues();
- return this;
- }
-
- /**
- * Selects the greediest constructor.
- * @return The injector to allow call chaining.
- * @throws SystemAssemblyException if the greediest constructor cannot be uniquely
- * identified.
- */
- public ConstructorConfiguration greedy() {
- Constructor<?>[] declared = clazz.getDeclaredConstructors();
- if (declared.length == 0) {
- throw new SystemAssemblyException("Class '" + clazz
- + " is an interface, primitive type, or array");
- }
- int max = -1;
- List<Constructor<?>> checked = new ArrayList<Constructor<?>>();
- CollectionFilter.filter(Arrays.asList(declared), checked,
- new Condition<Constructor<?>>() {
- @Override
- public boolean matches(Constructor<?> aObject) {
- if ( !publicOnly ) {
- return true;
- } else {
- return Modifier.isPublic(aObject.getModifiers());
- }
- }
- });
- for (Constructor ctor : checked) {
- if (ctor.getParameterTypes().length > max) {
- max = ctor.getParameterTypes().length;
- }
- }
- final int max2 = max;
- List<Constructor<?>> ctors = checked;
- List<Constructor<?>> longest = new ArrayList<Constructor<?>>();
- CollectionFilter.filter(ctors, longest,
- new Condition<Constructor<?>>() {
- @Override
- public boolean matches(Constructor<?> aObject) {
- return aObject.getParameterTypes().length == max2;
- }
- });
- if (longest.size() > 1) {
- throw new SystemAssemblyException(
- "Greediest constructor cannot be uniquely determined");
- }
- constructor = longest.get(0);
- resetValues();
- return this;
- }
-
- public ParameterValues getParameters() {
- getConstructor(); // initialize constructor if needed.
- return values;
- }
-
- /**
- * Resets the values.
- */
- private void resetValues() {
- constructor.setAccessible(true);
- values = new ParameterValues(constructor.getParameterTypes());
- }
-
- /**
- * Creates the object in the given scope.
- * @param aScope Scope containing required interfaces for this object.
- * @return object.
- */
- public Object create(Scope aScope) {
- Object[] valueArray = values.values(aScope);
- try {
- return getConstructor().newInstance(valueArray);
- } catch (Exception e) {
- throw new SystemAssemblyException("Could not construct object "
- + getConstructor() + " " + Arrays.asList(valueArray), e);
- }
- }
-
- public List<RequiredInterface> getRequiredInterfaces() {
- getConstructor(); // initialize constructor if needed.
- return values.getRequiredInterfaces();
- }
-
- private Constructor getConstructor() {
- if (constructor == null ) {
- greedy();
- }
- return constructor;
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private Class clazz;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Constructor<?> constructor;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private ParameterValues values;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private boolean publicOnly;
+
+/**
+ * Constructs the configuration. By default the public constructor with the
+ * most arguments will be used.
+ * @param aClass Class to construct.
+ */
+ public ConstructorConfiguration(Class aClass) {
+ clazz = aClass;
+ constructor = null;
+ publicOnly = true;
+ }
+
+ /**
+ * Sets whether or no non public constructors are also considered.
+ * Reset the choice of a constructor to its default.
+ *
+ * @param aNonPublic
+ *
+ * @return
+ */
+ public ConstructorConfiguration setNonPublic(boolean aNonPublic) {
+ publicOnly = !aNonPublic;
+ constructor = null;
+ values = null;
+
+ return this;
+ }
+
+ /**
+ * Selects an explicit constructor.
+ *
+ * @return Return the injector to allow call chaining.
+ *
+ * @throws SystemAssemblyException DOCUMENT ME!
+ */
+ public ConstructorConfiguration select(Class... aTypes) {
+ try {
+ constructor = clazz.getDeclaredConstructor(aTypes);
+ } catch (Exception e) {
+ throw new SystemAssemblyException(e.getMessage(), e);
+ }
+
+ resetValues();
+
+ return this;
+ }
+
+ /**
+ * Selects the greediest constructor.
+ *
+ * @return The injector to allow call chaining.
+ *
+ * @throws SystemAssemblyException if the greediest constructor cannot be
+ * uniquely identified.
+ */
+ public ConstructorConfiguration greedy() {
+ Constructor<?>[] declared = clazz.getDeclaredConstructors();
+
+ if (declared.length == 0) {
+ throw new SystemAssemblyException("Class '" + clazz
+ + " is an interface, primitive type, or array");
+ }
+
+ int max = -1;
+ List<Constructor<?>> checked = new ArrayList<Constructor<?>>();
+ CollectionFilter.filter(Arrays.asList(declared), checked,
+ new Condition<Constructor<?>>() {
+ @Override
+ public boolean matches(Constructor<?> aObject) {
+ if (!publicOnly) {
+ return true;
+ } else {
+ return Modifier.isPublic(aObject.getModifiers());
+ }
+ }
+ });
+
+ for (Constructor ctor : checked) {
+ if (ctor.getParameterTypes().length > max) {
+ max = ctor.getParameterTypes().length;
+ }
+ }
+
+ final int max2 = max;
+ List<Constructor<?>> ctors = checked;
+ List<Constructor<?>> longest = new ArrayList<Constructor<?>>();
+ CollectionFilter.filter(ctors, longest,
+ new Condition<Constructor<?>>() {
+ @Override
+ public boolean matches(Constructor<?> aObject) {
+ return aObject.getParameterTypes().length == max2;
+ }
+ });
+
+ if (longest.size() > 1) {
+ throw new SystemAssemblyException(
+ "Greediest constructor cannot be uniquely determined");
+ }
+
+ constructor = longest.get(0);
+ resetValues();
+
+ return this;
+ }
+
+ public ParameterValues getParameters() {
+ getConstructor(); // initialize constructor if needed.
+
+ return values;
+ }
+
+ /**
+ * Resets the values.
+ */
+ private void resetValues() {
+ constructor.setAccessible(true);
+ values = new ParameterValues(constructor.getParameterTypes());
+ }
+
+ /**
+ * Creates the object in the given scope.
+ *
+ * @param aScope Scope containing required interfaces for this object.
+ *
+ * @return object.
+ *
+ * @throws SystemAssemblyException DOCUMENT ME!
+ */
+ public Object create(Scope aScope) {
+ Object[] valueArray = values.values(aScope);
+
+ try {
+ return getConstructor().newInstance(valueArray);
+ } catch (Exception e) {
+ throw new SystemAssemblyException("Could not construct object "
+ + getConstructor() + " " + Arrays.asList(valueArray), e);
+ }
+ }
+
+ public List<RequiredInterface> getRequiredInterfaces() {
+ getConstructor(); // initialize constructor if needed.
+
+ return values.getRequiredInterfaces();
+ }
+
+ private Constructor getConstructor() {
+ if (constructor == null) {
+ greedy();
+ }
+
+ return constructor;
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
-public class DefaultContainer extends Container {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class DefaultContainer extends Container {
+ /**
+ * Creates a new DefaultContainer object.
+ *
+ * @param aName DOCUMENT ME!
+ */
public DefaultContainer(String aName) {
super(aName);
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aComponent DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public DefaultContainer addComponent(Component aComponent) {
super.addComponent(aComponent);
+
return this;
}
-
- public DefaultContainer addComponent(String aName, ClassConfiguration aConfiguration) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ * @param aConfiguration DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public DefaultContainer addComponent(String aName,
+ ClassConfiguration aConfiguration) {
return addComponent(new ClassAdapter(aName, aConfiguration));
}
- public DefaultContainer addComponent(String aName, Object aObject, ObjectConfiguration aConfiguration) {
- if ( !aConfiguration.appliesTo(aObject) ) {
- throw new IllegalArgumentException("Configuration '" + aConfiguration + "' does nto applu to '" +
- aObject + "'");
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ * @param aObject DOCUMENT ME!
+ * @param aConfiguration DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public DefaultContainer addComponent(String aName, Object aObject,
+ ObjectConfiguration aConfiguration) {
+ if (!aConfiguration.appliesTo(aObject)) {
+ throw new IllegalArgumentException("Configuration '"
+ + aConfiguration + "' does nto applu to '" + aObject + "'");
}
+
return addComponent(new ObjectAdapter(aName, aObject, aConfiguration));
}
-
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRequired DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public DefaultContainer addRequiredInterface(RequiredInterface aRequired) {
super.addRequiredInterface(aRequired);
+
return this;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aProvided DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public DefaultContainer addProvidedInterface(ProvidedInterface aProvided) {
super.addProvidedInterface(aProvided);
+
return this;
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
import org.wamblee.system.core.Scope;
+
/**
* Value provider that provides a fixed value.
- *
+ *
* @author Erik Brakkee
*/
class FixedValueProvider implements ValueProvider {
-
- private Object _value;
-
- /**
- * Constructs the value.
- * @param aValue Value to construct.
- */
- public FixedValueProvider(Object aValue) {
- _value = aValue;
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private Object _value;
+
+/**
+ * Constructs the value.
+ * @param aValue Value to construct.
+ */
+ public FixedValueProvider(Object aValue) {
+ _value = aValue;
+ }
- @Override
- public Object getValue(Scope aScope) {
- return _value;
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public Object getValue(Scope aScope) {
+ return _value;
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+
/**
- * An adapter class that adapts an existing object to a component.
- *
+ * An adapter class that adapts an existing object to a component.
+ *
* @author Erik Brakkee
*/
public class ObjectAdapter extends AbstractComponent<Object> {
+ /**
+ * DOCUMENT ME!
+ */
+ private ObjectConfiguration objectConfig;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Object object;
+
+ /**
+ * Creates a new ObjectAdapter object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aObject DOCUMENT ME!
+ * @param aObjectConfig DOCUMENT ME!
+ */
+ public ObjectAdapter(String aName, Object aObject,
+ ObjectConfiguration aObjectConfig) {
+ super(aName,
+ new ProvidedInterface[] {
+ new DefaultProvidedInterface(aName, aObject.getClass())
+ },
+ aObjectConfig.getRequiredInterfaces()
+ .toArray(new RequiredInterface[0]));
+ objectConfig = aObjectConfig;
+ object = aObject;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ protected Object doStart(Scope aScope) {
+ objectConfig.inject(aScope, object);
+
+ for (ProvidedInterface provided : getProvidedInterfaces()) {
+ addInterface(provided, object, aScope);
+ }
+
+ return object;
+ }
- private ObjectConfiguration objectConfig;
- private Object object;
-
- public ObjectAdapter(String aName, Object aObject, ObjectConfiguration aObjectConfig) {
- super(aName,
- new ProvidedInterface[] { new DefaultProvidedInterface(aName, aObject.getClass()) },
- aObjectConfig.getRequiredInterfaces().toArray(new RequiredInterface[0]));
- objectConfig = aObjectConfig;
- object = aObject;
- }
-
- @Override
- protected Object doStart(Scope aScope) {
-
- objectConfig.inject(aScope, object);
-
- for (ProvidedInterface provided: getProvidedInterfaces()) {
- addInterface(provided, object, aScope);
- }
-
- return object;
- }
-
- @Override
- protected void doStop(Object aRuntime) {
- // Empty.
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
+ @Override
+ protected void doStop(Object aRuntime) {
+ // Empty.
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
import java.util.ArrayList;
import java.util.List;
-import org.wamblee.system.core.RequiredInterface;
-import org.wamblee.system.core.Scope;
/**
- * General configuration for an instantiated object.
- *
+ * General configuration for an instantiated object.
+ *
* @author Erik Brakkee
*/
public class ObjectConfiguration {
-
- private Class _class;
+ /**
+ * DOCUMENT ME!
+ */
+ private Class _class;
+
+ /**
+ * DOCUMENT ME!
+ */
private SetterConfiguration setterConfig;
- public ObjectConfiguration(Class aClass) {
- _class = aClass;
- setterConfig = new SetterConfiguration(aClass);
+ /**
+ * Creates a new ObjectConfiguration object.
+ *
+ * @param aClass DOCUMENT ME!
+ */
+ public ObjectConfiguration(Class aClass) {
+ _class = aClass;
+ setterConfig = new SetterConfiguration(aClass);
}
-
+
/**
- * Performs injection into an object of the configured class
- * using information from the given scope.
- * @param aScope Scope.
- * @param aObject Object.
+ * Performs injection into an object of the configured class using
+ * information from the given scope.
+ *
+ * @param aScope Scope.
+ * @param aObject Object.
*/
- public void inject(Scope aScope, Object aObject) {
+ public void inject(Scope aScope, Object aObject) {
setterConfig.inject(aScope, aObject);
}
-
- public SetterConfiguration getSetterConfig() {
- return setterConfig;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public SetterConfiguration getSetterConfig() {
+ return setterConfig;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public List<RequiredInterface> getRequiredInterfaces() {
List<RequiredInterface> result = new ArrayList<RequiredInterface>();
result.addAll(setterConfig.getRequiredInterfaces());
- return result;
+
+ return result;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aObject DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public boolean appliesTo(Object aObject) {
return _class.isInstance(aObject);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
-import java.util.ArrayList;
-import java.util.List;
-
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+import java.util.ArrayList;
+import java.util.List;
+
+
/**
- * Represents parameter values for a method or constructor and allows for the configuration
- * of how these values are retrieved.
- *
+ * Represents parameter values for a method or constructor and allows for
+ * the configuration of how these values are retrieved.
+ *
* @author Erik Brakkee
*/
public class ParameterValues {
- private String[] names;
- private Class[] types;
- private ValueProvider[] values;
-
- /**
- * Constructs the configuration. By default no constructor is selected and
- * one of {@link #select(Class...)} or
- * {@link #greedy()} must be called.
- * @param aClass Class to construct.
- */
- public ParameterValues(Class[] aTypes) {
- names = new String[aTypes.length];
- for (int i = 0; i < aTypes.length; i++) {
- names[i] = "arg" + i;
- }
- types = aTypes;
- resetValues();
- }
-
- /**
+ /**
+ * DOCUMENT ME!
+ */
+ private String[] names;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Class[] types;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private ValueProvider[] values;
+
+/**
+ * Constructs the configuration. By default no constructor is selected and
+ * one of {@link #select(Class...)} or
+ * {@link #greedy()} must be called.
+ * @param aClass Class to construct.
+ */
+ public ParameterValues(Class[] aTypes) {
+ names = new String[aTypes.length];
+
+ for (int i = 0; i < aTypes.length; i++) {
+ names[i] = "arg" + i;
+ }
+
+ types = aTypes;
+ resetValues();
+ }
+
+/**
* Constructs the configuration. By default no constructor is selected and
* one of {@link #select(Class...)} or
* {@link #greedy()} must be called.
* @param aClass Class to construct.
*/
public ParameterValues(String[] aNames, Class[] aTypes) {
- assert aNames.length == aTypes.length;
- names = aNames;
- types = aTypes;
- resetValues();
+ assert aNames.length == aTypes.length;
+ names = aNames;
+ types = aTypes;
+ resetValues();
+ }
+
+ /**
+ * The types of the parameter values.
+ *
+ * @return Types.
+ */
+ public Class[] getTypes() {
+ return types;
+ }
+
+ /**
+ * Sets argument i to be optional, meaning that null is allowed to
+ * be passed in.
+ *
+ * @param aArg Argument to set.
+ *
+ * @return DOCUMENT ME!
+ */
+ public ParameterValues setOptional(int aArg) {
+ values[aArg] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
+ "arg" + aArg, types[aArg], true));
+
+ return this;
+ }
+
+ /**
+ * Sets the argument i to a fixed value.
+ *
+ * @param aArg Argument to set.
+ * @param aValue Value.
+ *
+ * @return DOCUMENT ME!
+ */
+ public ParameterValues setValue(int aArg, Object aValue) {
+ values[aArg] = new FixedValueProvider(aValue);
+
+ return this;
+ }
+
+ /**
+ * Resets the values.
+ */
+ private void resetValues() {
+ values = new ValueProvider[types.length];
+
+ for (int i = 0; i < values.length; i++) {
+ values[i] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
+ names[i], types[i]));
+ }
+ }
+
+ /**
+ * Gets the required interfaces to provide values that are not
+ * provided in another way.
+ *
+ * @return Required interfaces.
+ */
+ public List<RequiredInterface> getRequiredInterfaces() {
+ List<RequiredInterface> result = new ArrayList<RequiredInterface>();
+
+ for (ValueProvider provider : values) {
+ if (provider instanceof RequiredInterfaceProvider) {
+ result.add(((RequiredInterfaceProvider) provider)
+ .getRequiredInterface());
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the values to use in the given scope.
+ *
+ * @param aScope Scope within which to retrieve the values.
+ *
+ * @return Values.
+ */
+ public Object[] values(Scope aScope) {
+ Object[] valueArray = new Object[values.length];
+
+ for (int i = 0; i < values.length; i++) {
+ valueArray[i] = values[i].getValue(aScope);
+ }
+
+ return valueArray;
}
-
- /**
- * The types of the parameter values.
- * @return Types.
- */
- public Class[] getTypes() {
- return types;
- }
-
- /**
- * Sets argument i to be optional, meaning that null is allowed to be passed in.
- * @param aArg Argument to set.
- */
- public ParameterValues setOptional(int aArg) {
- values[aArg] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
- "arg" + aArg, types[aArg], true));
- return this;
- }
-
- /**
- * Sets the argument i to a fixed value.
- * @param aArg Argument to set.
- * @param aValue Value.
- */
- public ParameterValues setValue(int aArg, Object aValue) {
- values[aArg] = new FixedValueProvider(aValue);
- return this;
- }
-
- /**
- * Resets the values.
- */
- private void resetValues() {
- values = new ValueProvider[types.length];
- for (int i = 0; i < values.length; i++) {
- values[i] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
- names[i], types[i]));
- }
- }
-
- /**
- * Gets the required interfaces to provide values that are not provided
- * in another way.
- * @return Required interfaces.
- */
- public List<RequiredInterface> getRequiredInterfaces() {
- List<RequiredInterface> result = new ArrayList<RequiredInterface>();
- for (ValueProvider provider: values) {
- if ( provider instanceof RequiredInterfaceProvider) {
- result.add( ((RequiredInterfaceProvider)provider).getRequiredInterface());
- }
- }
- return result;
- }
-
- /**
- * Returns the values to use in the given scope.
- * @param aScope Scope within which to retrieve the values.
- * @return Values.
- */
- public Object[] values(Scope aScope) {
- Object[] valueArray = new Object[values.length];
- for (int i = 0; i < values.length; i++) {
- valueArray[i] = values[i].getValue(aScope);
- }
- return valueArray;
- }
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+
/**
* Value provider that provides a value through a required interface.
- *
+ *
* @author Erik Brakkee
*/
class RequiredInterfaceProvider implements ValueProvider {
-
- private RequiredInterface required;
-
- /**
- * Constructs the provider
- * @param aRequired Required interface.
- */
- public RequiredInterfaceProvider(RequiredInterface aRequired) {
- required = aRequired;
- }
-
- @Override
- public Object getValue(Scope aScope) {
- return aScope.getInterfaceImplementation(required.getProvider(), Object.class);
- }
-
- public RequiredInterface getRequiredInterface() {
- return required;
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private RequiredInterface required;
+
+/**
+ * Constructs the provider
+ * @param aRequired Required interface.
+ */
+ public RequiredInterfaceProvider(RequiredInterface aRequired) {
+ required = aRequired;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public Object getValue(Scope aScope) {
+ return aScope.getInterfaceImplementation(required.getProvider(),
+ Object.class);
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public RequiredInterface getRequiredInterface() {
+ return required;
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.adapters;
-import java.awt.CompositeContext;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
import org.wamblee.collections.CollectionFilter;
+
import org.wamblee.conditions.Condition;
import org.wamblee.conditions.FixedCondition;
+
import org.wamblee.general.Pair;
+
import org.wamblee.reflection.ReflectionUtils;
+
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.Scope;
import org.wamblee.system.core.SystemAssemblyException;
+import java.awt.CompositeContext;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+
/**
- * Represents the configuration for exposing the setters of a class as required
- * interfaces.
- *
+ * Represents the configuration for exposing the setters of a class as
+ * required interfaces.
+ *
* @author Erik Brakkee
*/
public class SetterConfiguration {
+ /**
+ * DOCUMENT ME!
+ */
+ private Class _class;
- private Class _class;
- private boolean publicOnly;
-
- private Map<Method, ParameterValues> setters;
-
- /**
- * Constructs the setter configuration. By default no setters are added.
- *
- * @param aClass
- * Class which is being configured.
- */
- public SetterConfiguration(Class aClass) {
- _class = aClass;
- publicOnly = true;
- setters = new HashMap<Method, ParameterValues>();
- }
-
- /**
- * Makes sure that all available setters are used.
- */
- public SetterConfiguration initAllSetters() {
- setters.clear();
- for (Method method: getAllSetters(_class, publicOnly) ) {
- setters.put(method, createParameterValues(method));
- }
- return this;
- }
-
- /**
- * Called to set whether non-public setters are also used. By default only
- * public setters are used. The currently selected setters remain chosen.
- *
- * @param aIsNonPublic
- * Non public flag.
- */
- public SetterConfiguration setNonPublic(boolean aIsNonPublic) {
- publicOnly = !aIsNonPublic;
- return this;
- }
-
- /**
- * Removes all setters.
- *
- * @return Reference to the current object to allow call chaining.
- */
- public SetterConfiguration clear() {
- setters.clear();
- return this;
- }
-
- /**
- * Removes a setter from the set of methods.
- *
- * @param aName
- * Name of the setter to remove.
- * @return Reference to the current object to allow call chaining.
- */
- public SetterConfiguration remove(String aName) {
- for (Method method : setters.keySet()) {
- if (method.getName().equals(aName)) {
- setters.remove(method);
- return this;
- }
- }
- throw new IllegalArgumentException(
- "No method configured by the name of '" + aName + "'");
- }
-
- /**
- * Removes the method from the set of methods.
- * @param aMethod Method to remove.
- * @return
- */
- public SetterConfiguration remove(Method aMethod) {
- if ( !aMethod.getDeclaringClass().isAssignableFrom(_class) ) {
- throw new RuntimeException("Method " + aMethod + " not found in class " + _class + " or its superclasses");
- }
- for (Method method : setters.keySet()) {
- if (method.equals(aMethod)) {
+ /**
+ * DOCUMENT ME!
+ */
+ private boolean publicOnly;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<Method, ParameterValues> setters;
+
+/**
+ * Constructs the setter configuration. By default no setters are added.
+ *
+ * @param aClass
+ * Class which is being configured.
+ */
+ public SetterConfiguration(Class aClass) {
+ _class = aClass;
+ publicOnly = true;
+ setters = new HashMap<Method, ParameterValues>();
+ }
+
+ /**
+ * Makes sure that all available setters are used.
+ *
+ * @return DOCUMENT ME!
+ */
+ public SetterConfiguration initAllSetters() {
+ setters.clear();
+
+ for (Method method : getAllSetters(_class, publicOnly)) {
+ setters.put(method, createParameterValues(method));
+ }
+
+ return this;
+ }
+
+ /**
+ * Called to set whether non-public setters are also used. By
+ * default only public setters are used. The currently selected setters
+ * remain chosen.
+ *
+ * @param aIsNonPublic Non public flag.
+ *
+ * @return DOCUMENT ME!
+ */
+ public SetterConfiguration setNonPublic(boolean aIsNonPublic) {
+ publicOnly = !aIsNonPublic;
+
+ return this;
+ }
+
+ /**
+ * Removes all setters.
+ *
+ * @return Reference to the current object to allow call chaining.
+ */
+ public SetterConfiguration clear() {
+ setters.clear();
+
+ return this;
+ }
+
+ /**
+ * Removes a setter from the set of methods.
+ *
+ * @param aName Name of the setter to remove.
+ *
+ * @return Reference to the current object to allow call chaining.
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
+ */
+ public SetterConfiguration remove(String aName) {
+ for (Method method : setters.keySet()) {
+ if (method.getName().equals(aName)) {
setters.remove(method);
+
return this;
}
}
+
throw new IllegalArgumentException(
- "Method '" + aMethod + "' was not configured. ");
- }
-
- /**
- * Adds a given setter name to the setters.
- *
- * @param aName Name of a setter method.
- * @return Reference to the current object to allow call chaining.
- */
- public SetterConfiguration add(final String aName) {
- int oldlen = setters.size();
- List<Method> methods = new ArrayList<Method>();
- CollectionFilter.filter(getAllSetters(_class, publicOnly), methods,
- new Condition<Method>() {
- @Override
- public boolean matches(Method aObject) {
- return aObject.getName().equals(aName);
- }
-
- });
- if (methods.size() == 0 ) {
- throw new IllegalArgumentException("Method '" + aName
- + "' not found in " + _class.getName());
- }
- // TODO is it possible to get more than one setter here in case the subclass overrides
- // the baseclass method?
- setters.put(methods.get(0), createParameterValues(methods.get(0)));
- return this;
- }
-
- /**
- * Adds a given setter identified by the type it accepts to the list of
- * setters.N
- *
- * @param aType
- * Type to look for. Note that this must be the exact type as
- * autoboxing and autounboxing is not used.
- * @return Reference to the current object to allow call chaining.
- * @throws IllegalArgumentException
- * In case no setter is found or multiple setters are found.
- */
- public SetterConfiguration addSetter(final Class aType) {
- List<Method> result = new ArrayList<Method>();
- CollectionFilter.filter(getAllSetters(_class, publicOnly), result,
- new Condition<Method>() {
- @Override
- public boolean matches(Method aObject) {
- Class type = aObject.getParameterTypes()[0];
- return type.equals(aType);
- }
-
- });
- if (result.size() == 0) {
- throw new IllegalArgumentException("No setter found in class '"
- + _class.getName()
- + "' that has a setter with argument type '"
- + aType.getName() + "'");
- }
- if (result.size() > 1) {
- String setters = "";
- for (Method method : result) {
- setters += method.getName() + " ";
- }
- throw new IllegalArgumentException(
- "Multiple setters found in class '" + _class.getName()
- + " that accept type '" + aType.getName() + "': "
- + setters);
- }
- Method method = result.get(0);
- setters.put(method, createParameterValues(method));
- return this;
- }
-
- /**
- * Gets all setters for the current class.
- *
- * @return List of all setters.
- */
- public static List<Method> getAllSetters(Class aClass,
- boolean aPublicOnly) {
- List<Method> result = new ArrayList<Method>();
- for (Method method : getAllMethods(aClass)) {
- if (!aPublicOnly || Modifier.isPublic(method.getModifiers())) {
- if (method.getName().startsWith("set")
- && method.getParameterTypes().length == 1) {
- method.setAccessible(true);
- result.add(method);
- }
- }
- }
- return result;
- }
-
- private static ParameterValues createParameterValues(Method aMethod) {
-
- Class[] paramTypes = aMethod.getParameterTypes();
- String[] paramNames = new String[paramTypes.length];
- for (int i = 0; i < paramTypes.length; i++) {
- paramNames[i] = aMethod.getName() + "." + i;
- }
- return new ParameterValues(paramNames, paramTypes);
- }
-
- private static final List<Method> getAllMethods(Class aClass) {
- return ReflectionUtils.getAllMethods(aClass);
- }
-
- /**
- * Gets the required interfaces based on the configured setteres.
- *
- * @return List of required interfaces.
- */
- public List<RequiredInterface> getRequiredInterfaces() {
- List<RequiredInterface> result = new ArrayList<RequiredInterface>();
- for (Method method : setters.keySet()) {
- result.addAll(setters.get(method).getRequiredInterfaces());
- }
- return result;
- }
-
- /**
- * Invokes all configured setters with the appropriate values.
- *
- * @param aScope
- * Scope within which invocation takes place.
- * @param aObject
- * Object on which the invocation takes place.
- */
- public void inject(Scope aScope, Object aObject) {
- if (!_class.isInstance(aObject)) {
- throw new IllegalArgumentException("Object '" + aObject
- + "' is not an instance of " + _class.getName());
- }
- for (Method method : setters.keySet()) {
- ParameterValues values = setters.get(method);
-
- try {
- method.invoke(aObject, values.values(aScope));
- } catch (IllegalAccessException e) {
- throw new SystemAssemblyException("Problem invoking " + method
- + " with " + values, e);
- } catch (InvocationTargetException e) {
- throw new SystemAssemblyException("Problem invoking " + method
- + " with " + values, e);
- }
- }
- }
-
- /**
- * Returns the parameter values for allowing detailed configuration of how
- * parameter values are set.
- *
- * @param aSetter
- * Setter name without the "set" prefix with the first character
- * converted to lower case.
- * @return Parameter values.
- */
- public ParameterValues values(String aMethod) {
- for (Method method : setters.keySet()) {
- if (method.getName().equals(aMethod)) {
- return setters.get(method);
- }
- }
- throw new IllegalArgumentException("No setter method '" + aMethod
- + "' found");
- }
-
- public List<Method> getSetters() {
- return new ArrayList<Method>(setters.keySet());
- }
+ "No method configured by the name of '" + aName + "'");
+ }
+
+ /**
+ * Removes the method from the set of methods.
+ *
+ * @param aMethod Method to remove.
+ *
+ * @return
+ *
+ * @throws RuntimeException DOCUMENT ME!
+ * @throws IllegalArgumentException DOCUMENT ME!
+ */
+ public SetterConfiguration remove(Method aMethod) {
+ if (!aMethod.getDeclaringClass().isAssignableFrom(_class)) {
+ throw new RuntimeException("Method " + aMethod
+ + " not found in class " + _class + " or its superclasses");
+ }
+
+ for (Method method : setters.keySet()) {
+ if (method.equals(aMethod)) {
+ setters.remove(method);
+
+ return this;
+ }
+ }
+
+ throw new IllegalArgumentException("Method '" + aMethod
+ + "' was not configured. ");
+ }
+
+ /**
+ * Adds a given setter name to the setters.
+ *
+ * @param aName Name of a setter method.
+ *
+ * @return Reference to the current object to allow call chaining.
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
+ */
+ public SetterConfiguration add(final String aName) {
+ int oldlen = setters.size();
+ List<Method> methods = new ArrayList<Method>();
+ CollectionFilter.filter(getAllSetters(_class, publicOnly), methods,
+ new Condition<Method>() {
+ @Override
+ public boolean matches(Method aObject) {
+ return aObject.getName().equals(aName);
+ }
+ });
+
+ if (methods.size() == 0) {
+ throw new IllegalArgumentException("Method '" + aName
+ + "' not found in " + _class.getName());
+ }
+
+ // TODO is it possible to get more than one setter here in case the subclass overrides
+ // the baseclass method?
+ setters.put(methods.get(0), createParameterValues(methods.get(0)));
+
+ return this;
+ }
+
+ /**
+ * Adds a given setter identified by the type it accepts to the
+ * list of setters.N
+ *
+ * @param aType Type to look for. Note that this must be the exact type as
+ * autoboxing and autounboxing is not used.
+ *
+ * @return Reference to the current object to allow call chaining.
+ *
+ * @throws IllegalArgumentException In case no setter is found or multiple
+ * setters are found.
+ */
+ public SetterConfiguration addSetter(final Class aType) {
+ List<Method> result = new ArrayList<Method>();
+ CollectionFilter.filter(getAllSetters(_class, publicOnly), result,
+ new Condition<Method>() {
+ @Override
+ public boolean matches(Method aObject) {
+ Class type = aObject.getParameterTypes()[0];
+
+ return type.equals(aType);
+ }
+ });
+
+ if (result.size() == 0) {
+ throw new IllegalArgumentException("No setter found in class '"
+ + _class.getName() + "' that has a setter with argument type '"
+ + aType.getName() + "'");
+ }
+
+ if (result.size() > 1) {
+ String setters = "";
+
+ for (Method method : result) {
+ setters += (method.getName() + " ");
+ }
+
+ throw new IllegalArgumentException(
+ "Multiple setters found in class '" + _class.getName()
+ + " that accept type '" + aType.getName() + "': " + setters);
+ }
+
+ Method method = result.get(0);
+ setters.put(method, createParameterValues(method));
+
+ return this;
+ }
+
+ /**
+ * Gets all setters for the current class.
+ *
+ * @param aClass DOCUMENT ME!
+ * @param aPublicOnly DOCUMENT ME!
+ *
+ * @return List of all setters.
+ */
+ public static List<Method> getAllSetters(Class aClass, boolean aPublicOnly) {
+ List<Method> result = new ArrayList<Method>();
+
+ for (Method method : getAllMethods(aClass)) {
+ if (!aPublicOnly || Modifier.isPublic(method.getModifiers())) {
+ if (method.getName().startsWith("set")
+ && (method.getParameterTypes().length == 1)) {
+ method.setAccessible(true);
+ result.add(method);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aMethod DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private static ParameterValues createParameterValues(Method aMethod) {
+ Class[] paramTypes = aMethod.getParameterTypes();
+ String[] paramNames = new String[paramTypes.length];
+
+ for (int i = 0; i < paramTypes.length; i++) {
+ paramNames[i] = aMethod.getName() + "." + i;
+ }
+
+ return new ParameterValues(paramNames, paramTypes);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aClass DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private static final List<Method> getAllMethods(Class aClass) {
+ return ReflectionUtils.getAllMethods(aClass);
+ }
+
+ /**
+ * Gets the required interfaces based on the configured setteres.
+ *
+ * @return List of required interfaces.
+ */
+ public List<RequiredInterface> getRequiredInterfaces() {
+ List<RequiredInterface> result = new ArrayList<RequiredInterface>();
+
+ for (Method method : setters.keySet()) {
+ result.addAll(setters.get(method).getRequiredInterfaces());
+ }
+
+ return result;
+ }
+
+ /**
+ * Invokes all configured setters with the appropriate values.
+ *
+ * @param aScope Scope within which invocation takes place.
+ * @param aObject Object on which the invocation takes place.
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
+ * @throws SystemAssemblyException DOCUMENT ME!
+ */
+ public void inject(Scope aScope, Object aObject) {
+ if (!_class.isInstance(aObject)) {
+ throw new IllegalArgumentException("Object '" + aObject
+ + "' is not an instance of " + _class.getName());
+ }
+
+ for (Method method : setters.keySet()) {
+ ParameterValues values = setters.get(method);
+
+ try {
+ method.invoke(aObject, values.values(aScope));
+ } catch (IllegalAccessException e) {
+ throw new SystemAssemblyException("Problem invoking " + method
+ + " with " + values, e);
+ } catch (InvocationTargetException e) {
+ throw new SystemAssemblyException("Problem invoking " + method
+ + " with " + values, e);
+ }
+ }
+ }
+
+ /**
+ * Returns the parameter values for allowing detailed configuration
+ * of how parameter values are set.
+ *
+ * @param aMethod Setter name without the "set" prefix with the first
+ * character converted to lower case.
+ *
+ * @return Parameter values.
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
+ */
+ public ParameterValues values(String aMethod) {
+ for (Method method : setters.keySet()) {
+ if (method.getName().equals(aMethod)) {
+ return setters.get(method);
+ }
+ }
+
+ throw new IllegalArgumentException("No setter method '" + aMethod
+ + "' found");
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public List<Method> getSetters() {
+ return new ArrayList<Method>(setters.keySet());
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
import org.wamblee.system.core.Scope;
+
/**
* Interface used to provide values for arguments of methods and constructors.
*
* @author Erik Brakkee
*/
interface ValueProvider {
-
- Object getValue(Scope aScope);
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ Object getValue(Scope aScope);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.components;
-import java.io.IOException;
-import java.util.Properties;
-
import org.wamblee.io.InputResource;
+
import org.wamblee.system.core.AbstractComponent;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.Scope;
+import java.io.IOException;
+
+import java.util.Properties;
+
+
/**
- * Property component that reads a property file and provides
- * it to other components through a provided interface.
- *
- * NOTE: when multiple property components are used, disambiguation
- * of provided and required interfaces is needed.
- *
+ * Property component that reads a property file and provides it to other
+ * components through a provided interface. NOTE: when multiple property
+ * components are used, disambiguation of provided and required interfaces is
+ * needed.
+ *
* @author Erik Brakkee
*/
public class PropertyComponent extends AbstractComponent<Properties> {
-
- private static ProvidedInterface PROPS = new DefaultProvidedInterface("props", Properties.class);
-
+ /**
+ * DOCUMENT ME!
+ */
+ private static ProvidedInterface PROPS = new DefaultProvidedInterface("props",
+ Properties.class);
+
+ /**
+ * DOCUMENT ME!
+ */
private Properties props;
-
- public PropertyComponent(String aName, InputResource aResource) throws IOException {
- this(aName, readProps(aResource));
- }
-
- private static Properties readProps(InputResource aResource) throws IOException {
- Properties props = new Properties();
- props.load(aResource.getInputStream());
- return props;
+
+ /**
+ * Creates a new PropertyComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aResource DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ public PropertyComponent(String aName, InputResource aResource)
+ throws IOException {
+ this(aName, readProps(aResource));
}
+ /**
+ * Creates a new PropertyComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aProps DOCUMENT ME!
+ */
public PropertyComponent(String aName, Properties aProps) {
super(aName);
- props = aProps;
-
+ props = aProps;
+
addProvidedInterface(PROPS);
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResource DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ private static Properties readProps(InputResource aResource)
+ throws IOException {
+ Properties props = new Properties();
+ props.load(aResource.getInputStream());
+
+ return props;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected Properties doStart(Scope aScope) {
addInterface(PROPS, props, aScope);
- return props;
+
+ return props;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
@Override
protected void doStop(Properties aRuntime) {
// Empty
}
-
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.container;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.wamblee.general.Pair;
+
import org.wamblee.system.core.AbstractComponent;
import org.wamblee.system.core.Component;
import org.wamblee.system.core.DefaultScope;
import org.wamblee.system.graph.component.ConnectRequiredExternallyRequiredEdgeFilter;
import org.wamblee.system.graph.component.ConnectRequiredProvidedEdgeFilter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+
/**
* Container consisting of multiple components.
- *
+ *
* @author Erik Brakkee
*/
public class Container extends AbstractComponent<Scope> {
-
+ /**
+ * DOCUMENT ME!
+ */
private static final Log LOG = LogFactory.getLog(Container.class);
+ /**
+ * DOCUMENT ME!
+ */
private List<Component> components;
- private CompositeEdgeFilter edgeFilter;
- private boolean sealed;
/**
+ * DOCUMENT ME!
+ */
+ private CompositeEdgeFilter edgeFilter;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private boolean sealed;
+
+/**
* Constructs the container
*
* @param aName
* Required services by the container.
*/
public Container(String aName, Component[] aComponents,
- List<ProvidedInterface> aProvided, List<RequiredInterface> aRequired) {
+ List<ProvidedInterface> aProvided, List<RequiredInterface> aRequired) {
super(aName, aProvided, aRequired);
- components = new ArrayList<Component>();
+ components = new ArrayList<Component>();
+
+ edgeFilter = new CompositeEdgeFilter();
+ sealed = false;
- edgeFilter = new CompositeEdgeFilter();
- sealed = false;
for (Component component : aComponents) {
addComponent(component);
}
}
-
- /**
+
+/**
* Constructs the container
*
* @param aName
* Required services by the container.
*/
public Container(String aName, Component[] aComponents,
- ProvidedInterface[] aProvided, RequiredInterface[] aRequired) {
- this(aName, aComponents, Arrays.asList(aProvided), Arrays.asList(aRequired));
+ ProvidedInterface[] aProvided, RequiredInterface[] aRequired) {
+ this(aName, aComponents, Arrays.asList(aProvided),
+ Arrays.asList(aRequired));
}
+ /**
+ * Creates a new Container object.
+ *
+ * @param aName DOCUMENT ME!
+ */
public Container(String aName) {
this(aName, new Component[0], new ProvidedInterface[0],
- new RequiredInterface[0]);
+ new RequiredInterface[0]);
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aComponent DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Container addComponent(Component aComponent) {
checkSealed();
+
if (aComponent.getContext() != null) {
throw new SystemAssemblyException(
- "Inconsistent hierarchy, component '"
- + aComponent.getName()
- + "' is already part of another hierarchy");
+ "Inconsistent hierarchy, component '" + aComponent.getName()
+ + "' is already part of another hierarchy");
}
- if ( findComponent(aComponent.getName()) != null ) {
+
+ if (findComponent(aComponent.getName()) != null) {
throw new SystemAssemblyException("Duplicate component '"
- + aComponent.getName() + "'");
+ + aComponent.getName() + "'");
}
+
components.add(aComponent);
aComponent.addContext(getQualifiedName());
+
return this;
}
-
+
/**
- * Explictly connects required and provided interfaces.
- * @param aClientComponent Client component, may not be null.
- * @param aRequiredInterface Required interface. If null it means all required interfaces.
- * @param aServerComponent Server component to connect to. If null, it means that no server components
- * may be connected to and the provider of the required interface will be null.
- * @param aProvidedInterface Provided interface. If null, it means that there is no restriction on the
- * name of the provided interface and that it is automatically selected.
+ * Explictly connects required and provided interfaces.
+ *
+ * @param aClientComponent Client component, may not be null.
+ * @param aRequiredInterface Required interface. If null it means all
+ * required interfaces.
+ * @param aServerComponent Server component to connect to. If null, it
+ * means that no server components may be connected to and the
+ * provider of the required interface will be null.
+ * @param aProvidedInterface Provided interface. If null, it means that
+ * there is no restriction on the name of the provided interface
+ * and that it is automatically selected.
+ *
+ * @throws SystemAssemblyException DOCUMENT ME!
*/
- public void connectRequiredProvided(String aClientComponent, String aRequiredInterface,
- String aServerComponent, String aProvidedInterface) {
+ public void connectRequiredProvided(String aClientComponent,
+ String aRequiredInterface, String aServerComponent,
+ String aProvidedInterface) {
checkSealed();
+
Component client = findComponent(aClientComponent);
Component server = findComponent(aServerComponent);
- if ( client == null ) {
- throw new SystemAssemblyException(getQualifiedName() + ": No component '" + aClientComponent + "' in the container");
+
+ if (client == null) {
+ throw new SystemAssemblyException(getQualifiedName()
+ + ": No component '" + aClientComponent + "' in the container");
}
- if ( aRequiredInterface != null ) {
- if ( findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null ) {
- throw new SystemAssemblyException(
- getQualifiedName() + ": Component '" + aClientComponent + "' does not have a required interface named '"
- + aRequiredInterface + "'");
- }
+
+ if (aRequiredInterface != null) {
+ if (findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName()
+ + ": Component '" + aClientComponent
+ + "' does not have a required interface named '"
+ + aRequiredInterface + "'");
+ }
}
- if ( server == null ) {
- throw new SystemAssemblyException("No component '" + aClientComponent + "' in the container");
+
+ if (server == null) {
+ throw new SystemAssemblyException("No component '"
+ + aClientComponent + "' in the container");
}
- if ( aProvidedInterface != null ) {
- if ( findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) {
- throw new SystemAssemblyException(
- getQualifiedName() + ": Component '" + aServerComponent + "' does not have a provided interface named '"
- + aProvidedInterface + "'");
- }
+
+ if (aProvidedInterface != null) {
+ if (findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName()
+ + ": Component '" + aServerComponent
+ + "' does not have a provided interface named '"
+ + aProvidedInterface + "'");
+ }
}
- edgeFilter.add(new ConnectRequiredProvidedEdgeFilter(aClientComponent, aRequiredInterface, aServerComponent, aProvidedInterface));
+
+ edgeFilter.add(new ConnectRequiredProvidedEdgeFilter(aClientComponent,
+ aRequiredInterface, aServerComponent, aProvidedInterface));
}
-
+
/**
- * Explicitly connects a externally required interface to an internally required interface.
- * @param aComponent Component requiring the interface (must be non-null).
- * @param aRequiredInterface Required interface of the component (must be non-null).
- * @param aExternalRequiredInterface Externally required interface (must be non-null).
+ * Explicitly connects a externally required interface to an
+ * internally required interface.
+ *
+ * @param aComponent Component requiring the interface (must be non-null).
+ * @param aRequiredInterface Required interface of the component (must be
+ * non-null).
+ * @param aExternalRequiredInterface Externally required interface (must be
+ * non-null).
+ *
+ * @throws SystemAssemblyException DOCUMENT ME!
*/
- public void connectExternalRequired(String aComponent, String aRequiredInterface,
- String aExternalRequiredInterface) {
+ public void connectExternalRequired(String aComponent,
+ String aRequiredInterface, String aExternalRequiredInterface) {
checkSealed();
+
Component client = findComponent(aComponent);
- if ( client == null ) {
- throw new SystemAssemblyException(getQualifiedName() + ": No component '" + aComponent + "' in the container");
+
+ if (client == null) {
+ throw new SystemAssemblyException(getQualifiedName()
+ + ": No component '" + aComponent + "' in the container");
}
- if ( aRequiredInterface != null ) {
- if ( findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null ) {
- throw new SystemAssemblyException(
- getQualifiedName() + ": Component '" + aComponent + "' does not have a required interface named '"
- + aRequiredInterface + "'");
- }
+
+ if (aRequiredInterface != null) {
+ if (findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName()
+ + ": Component '" + aComponent
+ + "' does not have a required interface named '"
+ + aRequiredInterface + "'");
+ }
}
- if ( aExternalRequiredInterface != null) {
- if ( findInterface(getRequiredInterfaces(), aExternalRequiredInterface) == null ) {
- throw new SystemAssemblyException(
- getQualifiedName() + ": container does not have a required interface named '"
- + aExternalRequiredInterface + "'");
- }
+
+ if (aExternalRequiredInterface != null) {
+ if (findInterface(getRequiredInterfaces(),
+ aExternalRequiredInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName()
+ + ": container does not have a required interface named '"
+ + aExternalRequiredInterface + "'");
+ }
}
+
edgeFilter.add(new ConnectRequiredExternallyRequiredEdgeFilter(
aComponent, aRequiredInterface, aExternalRequiredInterface));
}
-
- public void connectExternalProvided(String aExternalProvided, String aComponent, String aProvidedInterface) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aExternalProvided DOCUMENT ME!
+ * @param aComponent DOCUMENT ME!
+ * @param aProvidedInterface DOCUMENT ME!
+ */
+ public void connectExternalProvided(String aExternalProvided,
+ String aComponent, String aProvidedInterface) {
checkSealed();
+
Component server = findComponent(aComponent);
-
-
- if ( server == null ) {
- throw new SystemAssemblyException("No component '" + aComponent + "' in the container");
+
+ if (server == null) {
+ throw new SystemAssemblyException("No component '" + aComponent
+ + "' in the container");
}
- if ( aProvidedInterface != null ) {
- if ( findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) {
- throw new SystemAssemblyException(
- getQualifiedName() + ": Component '" + aComponent + "' does not have a provided interface named '"
- + aProvidedInterface + "'");
- }
+
+ if (aProvidedInterface != null) {
+ if (findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) {
+ throw new SystemAssemblyException(getQualifiedName()
+ + ": Component '" + aComponent
+ + "' does not have a provided interface named '"
+ + aProvidedInterface + "'");
+ }
}
- if ( aExternalProvided != null ) {
- if ( findInterface(getProvidedInterfaces(), aExternalProvided) == null) {
- throw new SystemAssemblyException(
- getQualifiedName() + ": Container does not have a provided interface named '"
- + aExternalProvided + "'");
- }
+
+ if (aExternalProvided != null) {
+ if (findInterface(getProvidedInterfaces(), aExternalProvided) == null) {
+ throw new SystemAssemblyException(getQualifiedName()
+ + ": Container does not have a provided interface named '"
+ + aExternalProvided + "'");
+ }
}
- edgeFilter.add(new ConnectExternalProvidedProvidedFilter(aExternalProvided, aComponent, aProvidedInterface));
- }
+ edgeFilter.add(new ConnectExternalProvidedProvidedFilter(
+ aExternalProvided, aComponent, aProvidedInterface));
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aProvided DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public Container addProvidedInterface(ProvidedInterface aProvided) {
checkSealed();
super.addProvidedInterface(aProvided);
+
return this;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRequired DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public Container addRequiredInterface(RequiredInterface aRequired) {
checkSealed();
super.addRequiredInterface(aRequired);
+
return this;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aContext DOCUMENT ME!
+ */
@Override
public void addContext(String aContext) {
super.addContext(aContext);
+
for (Component component : components) {
component.addContext(aContext);
}
}
/**
- * Validates the components together to check that there are no required
- * services not in the required list and no services in the provided list
- * that cannot be provided. Also logs a warning in case of superfluous
- * requirements.
- *
- * @throws SystemAssemblyException
- * in case of any validation problems.
+ * Validates the components together to check that there are no
+ * required services not in the required list and no services in the
+ * provided list that cannot be provided. Also logs a warning in case of
+ * superfluous requirements.
*/
public void validate() {
doStartOptionalDryRun(null, true);
}
/**
- * Seal the container, meaning that no further components or interfaces may
- * be added.
+ * Seal the container, meaning that no further components or
+ * interfaces may be added.
*/
public void seal() {
sealed = true;
/**
* Checks if the container is sealed.
- *
+ *
* @return True iff the container is sealed.
*/
public boolean isSealed() {
}
/**
- * Utility method to start with an empty external scope. This is useful for
- * top-level containers which are not part of another container.
- *
+ * Utility method to start with an empty external scope. This is
+ * useful for top-level containers which are not part of another
+ * container.
+ *
* @return Scope.
*/
public Scope start() {
Scope scope = new DefaultScope(getProvidedInterfaces());
+
return super.start(scope);
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aExternalScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected Scope doStart(Scope aExternalScope) {
validate();
- Scope scope = new DefaultScope(getProvidedInterfaces().toArray(new ProvidedInterface[0]), aExternalScope);
+
+ Scope scope = new DefaultScope(getProvidedInterfaces()
+ .toArray(new ProvidedInterface[0]), aExternalScope);
ComponentGraph graph = doStartOptionalDryRun(scope, false);
exposeProvidedInterfaces(graph, aExternalScope, scope);
seal();
+
return scope;
}
- private void exposeProvidedInterfaces(ComponentGraph aGraph, Scope aExternalScope,
- Scope aInternalScope) {
- for (Pair<ProvidedInterface,ProvidedInterface> mapping:
- aGraph.findExternalProvidedInterfaceMapping()) {
- Object svc = aInternalScope.getInterfaceImplementation(mapping.getSecond(), Object.class);
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aGraph DOCUMENT ME!
+ * @param aExternalScope DOCUMENT ME!
+ * @param aInternalScope DOCUMENT ME!
+ */
+ private void exposeProvidedInterfaces(ComponentGraph aGraph,
+ Scope aExternalScope, Scope aInternalScope) {
+ for (Pair<ProvidedInterface, ProvidedInterface> mapping : aGraph
+ .findExternalProvidedInterfaceMapping()) {
+ Object svc = aInternalScope.getInterfaceImplementation(mapping
+ .getSecond(), Object.class);
addInterface(mapping.getFirst(), svc, aExternalScope);
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ * @param aDryRun DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private ComponentGraph doStartOptionalDryRun(Scope aScope, boolean aDryRun) {
ComponentGraph graph = createComponentGraph();
graph.validate();
LOG.info("Starting '" + getQualifiedName() + "'");
List<Component> started = new ArrayList<Component>();
+
for (Component component : components) {
try {
// Start the service.
throw e;
} catch (RuntimeException e) {
LOG.error(getQualifiedName() + ": could not start '"
- + component.getQualifiedName() + "'", e);
+ + component.getQualifiedName() + "'", e);
stopAlreadyStartedComponents(started, aScope);
throw e;
}
}
+
return graph;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private ComponentGraph createComponentGraph() {
ComponentGraph graph = new ComponentGraph();
+
for (RequiredInterface req : getRequiredInterfaces()) {
graph.addRequiredInterface(this, req);
}
+
for (Component comp : components) {
graph.addComponent(comp);
}
- for (ProvidedInterface prov: getProvidedInterfaces()) {
+
+ for (ProvidedInterface prov : getProvidedInterfaces()) {
graph.addProvidedInterface(this, prov);
}
graph.addEdgeFilter(edgeFilter);
+
return graph;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aStarted DOCUMENT ME!
+ * @param aScope DOCUMENT ME!
+ */
private void stopAlreadyStartedComponents(List<Component> aStarted,
- Scope aScope) {
+ Scope aScope) {
// an exception occurred, stop the successfully started
// components
for (int i = aStarted.size() - 1; i >= 0; i--) {
aStarted.get(i).stop(aScope.getRuntime(component));
} catch (Throwable t) {
LOG.error(getQualifiedName() + ": error stopping "
- + aStarted.get(i).getQualifiedName());
+ + aStarted.get(i).getQualifiedName());
}
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ */
@Override
protected void doStop(Scope aScope) {
for (int i = components.size() - 1; i >= 0; i--) {
Component component = components.get(i);
- Object runtime = aScope.getRuntime(component);
+ Object runtime = aScope.getRuntime(component);
component.stop(runtime);
}
}
+ /**
+ * DOCUMENT ME!
+ */
private void checkSealed() {
if (sealed) {
throw new SystemAssemblyException("Container is sealed");
}
}
-
+
/**
- * Finds a component based on the non-qualified name of the component.
- * @param aName Component name.
- * @return Component or null if not found.
+ * Finds a component based on the non-qualified name of the
+ * component.
+ *
+ * @param aName Component name.
+ *
+ * @return Component or null if not found.
*/
- public Component findComponent(String aName) {
- for (Component<?> component: components) {
- if ( component.getName().equals(aName)) {
- return component;
- }
- }
- return null;
+ public Component findComponent(String aName) {
+ for (Component<?> component : components) {
+ if (component.getName().equals(aName)) {
+ return component;
+ }
+ }
+
+ return null;
}
-
- private static <T extends NamedInterface> T findInterface(List<T> aInterfaces, String aInterfaceName) {
- for (T intf: aInterfaces) {
- if ( intf.getName().equals(aInterfaceName)) {
- return intf;
- }
- }
- return null;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aInterfaces DOCUMENT ME!
+ * @param aInterfaceName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private static <T extends NamedInterface> T findInterface(
+ List<T> aInterfaces, String aInterfaceName) {
+ for (T intf : aInterfaces) {
+ if (intf.getName().equals(aInterfaceName)) {
+ return intf;
+ }
+ }
+
+ return null;
}
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.core;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
/**
* Abstract subsystem class making it easy to implement new subsystems.
+ *
+ * @param <Type> DOCUMENT ME!
*/
public abstract class AbstractComponent<Type> implements Component<Type> {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final Log LOG = LogFactory.getLog(AbstractComponent.class);
- private static final Log LOG = LogFactory.getLog(AbstractComponent.class);
-
- private ThreadLocal<List<ProvidedInterface>> remaining;
-
- private String context;
- private String name;
- private List<ProvidedInterface> provided;
- private List<RequiredInterface> required;
-
- /**
- * Constructs the subsystem.
- *
- * @param aName
- * Name of the system.
- * @param aProvided
- * Provided services.
- * @param aRequired
- * Required services.
- */
- protected AbstractComponent(String aName, List<ProvidedInterface> aProvided,
- List<RequiredInterface> aRequired) {
- remaining = new ThreadLocal<List<ProvidedInterface>>();
- context = null;
- name = aName;
- provided = new ArrayList<ProvidedInterface>(aProvided);
- required = new ArrayList<RequiredInterface>(aRequired);
- }
-
- /**
+ /**
+ * DOCUMENT ME!
+ */
+ private ThreadLocal<List<ProvidedInterface>> remaining;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private String context;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private String name;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private List<ProvidedInterface> provided;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private List<RequiredInterface> required;
+
+/**
+ * Constructs the subsystem.
+ *
+ * @param aName
+ * Name of the system.
+ * @param aProvided
+ * Provided services.
+ * @param aRequired
+ * Required services.
+ */
+ protected AbstractComponent(String aName,
+ List<ProvidedInterface> aProvided, List<RequiredInterface> aRequired) {
+ remaining = new ThreadLocal<List<ProvidedInterface>>();
+ context = null;
+ name = aName;
+ provided = new ArrayList<ProvidedInterface>(aProvided);
+ required = new ArrayList<RequiredInterface>(aRequired);
+ }
+
+/**
* Constructs the subsystem.
*
* @param aName
* Required services.
*/
protected AbstractComponent(String aName, ProvidedInterface[] aProvided,
- RequiredInterface[] aRequired) {
+ RequiredInterface[] aRequired) {
this(aName, Arrays.asList(aProvided), Arrays.asList(aRequired));
}
-
- protected AbstractComponent(String aName) {
- this(aName, new ProvidedInterface[0], new RequiredInterface[0]);
- }
-
- public AbstractComponent<Type> addProvidedInterface(ProvidedInterface aProvided) {
- provided.add(aProvided);
- return this;
- }
-
- public AbstractComponent<Type> addRequiredInterface(RequiredInterface aRequired) {
- required.add(aRequired);
- return this;
- }
-
- @Override
- public final String getName() {
- return name;
- }
-
- @Override
- public void addContext(String aContext) {
- if (context == null) {
- context = aContext;
- } else {
- context = aContext + "." + context;
- }
- }
-
- @Override
- public String getContext() {
- return context;
- }
-
- @Override
- public String getQualifiedName() {
- if (context == null) {
- return getName();
- }
- return context + "." + getName();
- }
-
- @Override
- public final List<ProvidedInterface> getProvidedInterfaces() {
- return Collections.unmodifiableList(provided);
- }
-
- @Override
- public final List<RequiredInterface> getRequiredInterfaces() {
- return Collections.unmodifiableList(required);
- }
-
- @Override
- public final Type start(Scope aScope) {
- LOG.info("Initialization starting '" + getQualifiedName() + "'");
- List<ProvidedInterface> oldRemaining = remaining.get();
- remaining.set(new ArrayList<ProvidedInterface>(getProvidedInterfaces()));
- try {
- Type runtime = doStart(aScope);
- checkNotStartedInterfaces();
- LOG.info("Initialization finished '" + getQualifiedName() + "'");
- return runtime;
- } finally {
- remaining.set(oldRemaining);
- }
- }
-
- private void checkNotStartedInterfaces() {
- if (remaining.get().size() > 0) {
- String notProvided = "";
- for (ProvidedInterface provided : remaining.get()) {
- notProvided += "\nComponent " + getQualifiedName()
- + " did not start interface " + provided;
- }
- throw new SystemAssemblyException(notProvided);
- }
- }
-
- /**
- * Must be implemented for initializing the subsystem. The implementation
- * must call {@link #addInterface(ProvidedInterface, Object, Scope)} for each service that is started.
- *
- * @return Returns the runtime of the component.
- */
- protected abstract Type doStart(Scope aScope);
-
- /**
- * Implementations must call this method to indicate that a new service has
- * been started.
- *
- * @param aDescriptor
- * Provided interface.
- * @param aService
- * Implementation of the interface.
- * @param aScope
- * scope in which to publish the implementation.
- */
- protected final void addInterface(ProvidedInterface aDescriptor,
- Object aService, Scope aScope) {
- LOG.info("Interface '" + getQualifiedName() + "."
- + aDescriptor.getName() + "' started.");
- if ( !remaining.get().remove(aDescriptor) ) {
- throw new SystemAssemblyException("Component '" + getQualifiedName() + "' started an unexpected interface '" +
- aDescriptor + "' that was not registerd as a provided interface before");
- }
- aScope.publishInterface(aDescriptor, aService);
- }
-
- @Override
- public void stop(Type aRuntime) {
- LOG.info("Stopping initiated '" + getQualifiedName() + "'");
- doStop(aRuntime);
- LOG.info("Stopping completed '" + getQualifiedName() + "'");
- }
-
- protected abstract void doStop(Type aRuntime);
-
- @Override
- public String toString() {
- return getQualifiedName();
- }
-
- public ProvidedInterface findProvidedInterface(String aName) {
- for (ProvidedInterface provided: getProvidedInterfaces()) {
- if ( provided.getName().equals(aName)) {
- return provided;
- }
- }
- return null;
- }
-
- public RequiredInterface findRequiredInterface(String aName) {
- for (RequiredInterface required: getRequiredInterfaces()) {
- if ( required.getName().equals(aName)) {
- return required;
- }
- }
- return null;
- }
+ /**
+ * Creates a new AbstractComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ */
+ protected AbstractComponent(String aName) {
+ this(aName, new ProvidedInterface[0], new RequiredInterface[0]);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aProvided DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public AbstractComponent<Type> addProvidedInterface(
+ ProvidedInterface aProvided) {
+ provided.add(aProvided);
+
+ return this;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRequired DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public AbstractComponent<Type> addRequiredInterface(
+ RequiredInterface aRequired) {
+ required.add(aRequired);
+
+ return this;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public final String getName() {
+ return name;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aContext DOCUMENT ME!
+ */
+ @Override
+ public void addContext(String aContext) {
+ if (context == null) {
+ context = aContext;
+ } else {
+ context = aContext + "." + context;
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String getContext() {
+ return context;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String getQualifiedName() {
+ if (context == null) {
+ return getName();
+ }
+
+ return context + "." + getName();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public final List<ProvidedInterface> getProvidedInterfaces() {
+ return Collections.unmodifiableList(provided);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public final List<RequiredInterface> getRequiredInterfaces() {
+ return Collections.unmodifiableList(required);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public final Type start(Scope aScope) {
+ LOG.info("Initialization starting '" + getQualifiedName() + "'");
+
+ List<ProvidedInterface> oldRemaining = remaining.get();
+ remaining.set(new ArrayList<ProvidedInterface>(getProvidedInterfaces()));
+
+ try {
+ Type runtime = doStart(aScope);
+ checkNotStartedInterfaces();
+ LOG.info("Initialization finished '" + getQualifiedName() + "'");
+
+ return runtime;
+ } finally {
+ remaining.set(oldRemaining);
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ private void checkNotStartedInterfaces() {
+ if (remaining.get().size() > 0) {
+ String notProvided = "";
+
+ for (ProvidedInterface provided : remaining.get()) {
+ notProvided += ("\nComponent " + getQualifiedName()
+ + " did not start interface " + provided);
+ }
+
+ throw new SystemAssemblyException(notProvided);
+ }
+ }
+
+ /**
+ * Must be implemented for initializing the subsystem. The
+ * implementation must call {@link #addInterface(ProvidedInterface,
+ * Object, Scope)} for each service that is started.
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return Returns the runtime of the component.
+ */
+ protected abstract Type doStart(Scope aScope);
+
+ /**
+ * Implementations must call this method to indicate that a new
+ * service has been started.
+ *
+ * @param aDescriptor Provided interface.
+ * @param aService Implementation of the interface.
+ * @param aScope scope in which to publish the implementation.
+ *
+ * @throws SystemAssemblyException DOCUMENT ME!
+ */
+ protected final void addInterface(ProvidedInterface aDescriptor,
+ Object aService, Scope aScope) {
+ LOG.info("Interface '" + getQualifiedName() + "."
+ + aDescriptor.getName() + "' started.");
+
+ if (!remaining.get().remove(aDescriptor)) {
+ throw new SystemAssemblyException("Component '"
+ + getQualifiedName() + "' started an unexpected interface '"
+ + aDescriptor
+ + "' that was not registerd as a provided interface before");
+ }
+
+ aScope.publishInterface(aDescriptor, aService);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
+ @Override
+ public void stop(Type aRuntime) {
+ LOG.info("Stopping initiated '" + getQualifiedName() + "'");
+ doStop(aRuntime);
+ LOG.info("Stopping completed '" + getQualifiedName() + "'");
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
+ protected abstract void doStop(Type aRuntime);
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String toString() {
+ return getQualifiedName();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public ProvidedInterface findProvidedInterface(String aName) {
+ for (ProvidedInterface provided : getProvidedInterfaces()) {
+ if (provided.getName().equals(aName)) {
+ return provided;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public RequiredInterface findRequiredInterface(String aName) {
+ for (RequiredInterface required : getRequiredInterfaces()) {
+ if (required.getName().equals(aName)) {
+ return required;
+ }
+ }
+
+ return null;
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
import java.util.List;
+
/**
* A component represents a part of a system that requires a
* number of interfaces and provides a number of interfaces.
* @author Erik Brakkee
*/
public interface Component<Type> {
-
- /**
- * Gets the name of the subsystem.
- * @return Subsystem name.
- */
- String getName();
-
- /**
- * Prepends the context with a super context.
- */
- void addContext(String aContext);
-
- /**
- * Getst the context.
- * @return Context or null if not set.
- */
- String getContext();
-
- /**
- * Gets the fully qualified name of the component which includes
- * the context of the component.
- * This method can only be used after the component has started.
- * @return Qualified name.
- */
- String getQualifiedName();
+ /**
+ * Gets the name of the subsystem.
+ *
+ * @return Subsystem name.
+ */
+ String getName();
+
+ /**
+ * Prepends the context with a super context.
+ *
+ * @param aContext DOCUMENT ME!
+ */
+ void addContext(String aContext);
+
+ /**
+ * Getst the context.
+ *
+ * @return Context or null if not set.
+ */
+ String getContext();
+
+ /**
+ * Gets the fully qualified name of the component which includes
+ * the context of the component. This method can only be used after the
+ * component has started.
+ *
+ * @return Qualified name.
+ */
+ String getQualifiedName();
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * Gets a description of the provided interfaces.
+ * @return Provided interfaces.
+ */
+ List<ProvidedInterface> getProvidedInterfaces();
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * Gets a description of the required interfaces.
+ * @return Required interfaces.
+ */
+ List<RequiredInterface> getRequiredInterfaces();
- /**
- * Gets a description of the provided interfaces.
- * @return Provided interfaces.
- */
- List<ProvidedInterface> getProvidedInterfaces();
-
- /**
- * Gets a description of the required interfaces.
- * @return Required interfaces.
- */
- List<RequiredInterface> getRequiredInterfaces();
+ /**
+ * Initialises the subsystem by starting all the services that it
+ * described as provided.
+ *
+ * @param aScope Scope with external interface implementations that are
+ * available. The component must publish its runtime and its
+ * provided interfaces in this scope.
+ *
+ * @return Gets an object representing the runtime of the component.
+ */
+ Type start(Scope aScope);
-
- /**
- * Initialises the subsystem by starting all the services that
- * it described as provided.
- * @param aScope Scope with external interface implementations that are available. The component
- * must publish its runtime and its provided interfaces in this scope.
- * @return Gets an object representing the runtime of the component.
- */
- Type start(Scope aScope);
-
- /**
- * Stops a component.
- * @param aRuntime THe runtime part of the component.
- */
- void stop(Type aRuntime);
+ /**
+ * Stops a component.
+ *
+ * @param aRuntime THe runtime part of the component.
+ */
+ void stop(Type aRuntime);
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
import java.util.ArrayList;
* @author Erik Brakkee
*/
public class DefaultProvidedInterface implements ProvidedInterface {
-
- private String name;
- private Class[] interfaces;
-
- /**
- * Constructs the descriptor.
- * @param aInterface Type of service.
- */
- public DefaultProvidedInterface(String aName, Class aInterface) {
- this(aName, new Class[] { aInterface });
- }
-
- public DefaultProvidedInterface(String aName, Class[] aInterfaces) {
- name = aName;
- interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length);
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public Class[] getInterfaceTypes() {
- return interfaces;
- }
-
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- buf.append(getName());
- buf.append(":");
- for (Class intf: interfaces) {
- buf.append(" " + intf.getName());
- }
- return buf.toString();
- }
-
- @Override
- public boolean equals(Object aObj) {
- return this == aObj;
- /*
- if ( !(aObj instanceof DefaultProvidedInterface)) {
- return false;
- }
- DefaultProvidedInterface provided = (DefaultProvidedInterface)aObj;
- return getEqualsRepresentation().equals(provided.getEqualsRepresentation());
- */
- }
-
- @Override
- public int hashCode() {
- return getEqualsRepresentation().hashCode();
- }
-
- @Override
- public boolean covers(ProvidedInterface aInterface) {
- // TODO do more than just equals.
- if ( !(aInterface instanceof DefaultProvidedInterface)) {
- return false;
- }
- return getEqualsRepresentation().equals(((DefaultProvidedInterface)aInterface).getEqualsRepresentation());
- }
-
-
- private String getEqualsRepresentation() {
- List<String> result = new ArrayList<String>();
- for (Class cls: interfaces) {
- result.add(cls.getName());
- }
- Collections.sort(result);
- String value = "";
- for (String str: result) {
- value += ":" + str;
- }
- return value;
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private String name;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Class[] interfaces;
+
+/**
+ * Constructs the descriptor.
+ * @param aInterface Type of service.
+ */
+ public DefaultProvidedInterface(String aName, Class aInterface) {
+ this(aName, new Class[] { aInterface });
+ }
+
+/**
+ * Creates a new DefaultProvidedInterface object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aInterfaces DOCUMENT ME!
+ */
+ public DefaultProvidedInterface(String aName, Class[] aInterfaces) {
+ name = aName;
+ interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public Class[] getInterfaceTypes() {
+ return interfaces;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ buf.append(getName());
+ buf.append(":");
+
+ for (Class intf : interfaces) {
+ buf.append(" " + intf.getName());
+ }
+
+ return buf.toString();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aObj DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean equals(Object aObj) {
+ return this == aObj;
+
+ /*
+ if ( !(aObj instanceof DefaultProvidedInterface)) {
+ return false;
+ }
+ DefaultProvidedInterface provided = (DefaultProvidedInterface)aObj;
+ return getEqualsRepresentation().equals(provided.getEqualsRepresentation());
+ */
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public int hashCode() {
+ return getEqualsRepresentation().hashCode();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aInterface DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean covers(ProvidedInterface aInterface) {
+ // TODO do more than just equals.
+ if (!(aInterface instanceof DefaultProvidedInterface)) {
+ return false;
+ }
+
+ return getEqualsRepresentation()
+ .equals(((DefaultProvidedInterface) aInterface).getEqualsRepresentation());
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private String getEqualsRepresentation() {
+ List<String> result = new ArrayList<String>();
+
+ for (Class cls : interfaces) {
+ result.add(cls.getName());
+ }
+
+ Collections.sort(result);
+
+ String value = "";
+
+ for (String str : result) {
+ value += (":" + str);
+ }
+
+ return value;
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
+import org.wamblee.reflection.ReflectionUtils;
+
import java.util.Arrays;
-import org.wamblee.reflection.ReflectionUtils;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DefaultRequiredInterface implements RequiredInterface {
+ /**
+ * DOCUMENT ME!
+ */
+ private String name;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private boolean optional;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Class[] required;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface provider;
+
+/**
+ * Creates a new DefaultRequiredInterface object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aInterface DOCUMENT ME!
+ */
+ public DefaultRequiredInterface(String aName, Class aInterface) {
+ this(aName, new Class[] { aInterface });
+ }
+
+/**
+ * Creates a new DefaultRequiredInterface object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aInterfaces DOCUMENT ME!
+ */
+ public DefaultRequiredInterface(String aName, Class[] aInterfaces) {
+ this(aName, aInterfaces, false);
+ }
+
+/**
+ * Creates a new DefaultRequiredInterface object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aInterface DOCUMENT ME!
+ * @param aIsOptional DOCUMENT ME!
+ */
+ public DefaultRequiredInterface(String aName, Class aInterface,
+ boolean aIsOptional) {
+ this(aName, new Class[] { aInterface }, aIsOptional);
+ }
+
+/**
+ * Creates a new DefaultRequiredInterface object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aInterfaces DOCUMENT ME!
+ * @param aIsOptional DOCUMENT ME!
+ */
+ public DefaultRequiredInterface(String aName, Class[] aInterfaces,
+ boolean aIsOptional) {
+ name = aName;
+ optional = aIsOptional;
+ required = aInterfaces;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean isOptional() {
+ return optional;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aDescriptor DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean implementedBy(ProvidedInterface aDescriptor) {
+ Class[] provided = aDescriptor.getInterfaceTypes();
+
+ for (Class requiredIntf : required) {
+ if (!serviceProvided(requiredIntf, provided)) {
+ return false;
+ }
+ }
+
+ // all required interfaces are provided.
+ return true;
+ }
+
+ /**
+ * Check if the required interface is implemented by one of the
+ * provided interfaces.
+ *
+ * @param aRequired required interface
+ * @param aProvided Provided interfaces.
+ *
+ * @return
+ */
+ private boolean serviceProvided(Class aRequired, Class[] aProvided) {
+ for (Class provided : aProvided) {
+ try {
+ provided = ReflectionUtils.wrapIfNeeded(provided);
+ aRequired = ReflectionUtils.wrapIfNeeded(aRequired);
+ provided.asSubclass(aRequired);
+
+ return true;
+ } catch (ClassCastException e) {
+ // No match, try the next one.
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public ProvidedInterface getProvider() {
+ return provider;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aProvider DOCUMENT ME!
+ */
+ @Override
+ public void setProvider(ProvidedInterface aProvider) {
+ assert aProvider != null;
+ assert implementedBy(aProvider);
+ provider = aProvider;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param obj DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean equals(Object obj) {
+ return this == obj;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param obj DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean covers(RequiredInterface obj) {
+ // TODO do more than equals.
+ if (!(obj instanceof DefaultRequiredInterface)) {
+ return false;
+ }
+
+ DefaultRequiredInterface descr = (DefaultRequiredInterface) obj;
+
+ if (required.length != descr.required.length) {
+ return false;
+ }
+
+ String[] interfaces1 = new String[required.length];
+ String[] interfaces2 = new String[required.length];
+
+ for (int i = 0; i < required.length; i++) {
+ interfaces1[i] = required[i].getName();
+ interfaces2[i] = descr.required[i].getName();
+ }
+
+ Arrays.sort(interfaces1);
+ Arrays.sort(interfaces2);
+
+ return Arrays.equals(interfaces1, interfaces2);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public int hashCode() {
+ return required.hashCode();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String toString() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("." + getName() + ":");
+
+ for (Class intf : required) {
+ buf.append("." + intf.getName());
+ }
- private String name;
- private boolean optional;
- private Class[] required;
- private ProvidedInterface provider;
-
- public DefaultRequiredInterface(String aName, Class aInterface) {
- this(aName, new Class[] { aInterface });
- }
-
- public DefaultRequiredInterface(String aName, Class[] aInterfaces) {
- this(aName, aInterfaces, false);
- }
-
- public DefaultRequiredInterface(String aName, Class aInterface, boolean aIsOptional) {
- this(aName, new Class[] { aInterface }, aIsOptional );
- }
-
-
- public DefaultRequiredInterface(String aName, Class[] aInterfaces, boolean aIsOptional) {
- name = aName;
- optional = aIsOptional;
- required = aInterfaces;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public boolean isOptional() {
- return optional;
- }
-
- @Override
- public boolean implementedBy(ProvidedInterface aDescriptor) {
- Class[] provided = aDescriptor.getInterfaceTypes();
- for (Class requiredIntf : required) {
- if ( !serviceProvided(requiredIntf, provided)) {
- return false;
- }
- }
- // all required interfaces are provided.
- return true;
- }
-
- /**
- * Check if the required interface is implemented by one of the provided interfaces.
- * @param aRequired required interface
- * @param aProvided Provided interfaces.
- * @return
- */
- private boolean serviceProvided(Class aRequired, Class[] aProvided) {
- for (Class provided: aProvided) {
- try {
- provided = ReflectionUtils.wrapIfNeeded(provided);
- aRequired = ReflectionUtils.wrapIfNeeded(aRequired);
- provided.asSubclass(aRequired);
- return true;
- } catch (ClassCastException e) {
- // No match, try the next one.
- }
- }
- return false;
- }
-
- @Override
- public ProvidedInterface getProvider() {
- return provider;
- }
-
- @Override
- public void setProvider(ProvidedInterface aProvider) {
- assert aProvider != null;
- assert implementedBy(aProvider);
- provider = aProvider;
- }
-
- @Override
- public boolean equals(Object obj) {
- return this == obj;
- }
-
- @Override
- public boolean covers(RequiredInterface obj) {
- // TODO do more than equals.
- if ( !(obj instanceof DefaultRequiredInterface)) {
- return false;
- }
- DefaultRequiredInterface descr = (DefaultRequiredInterface)obj;
- if ( required.length != descr.required.length ) {
- return false;
- }
- String[] interfaces1 = new String[required.length];
- String[] interfaces2 = new String[required.length];
- for (int i = 0; i < required.length; i++) {
- interfaces1[i] = required[i].getName();
- interfaces2[i] = descr.required[i].getName();
- }
- Arrays.sort(interfaces1);
- Arrays.sort(interfaces2);
- return Arrays.equals(interfaces1, interfaces2);
- }
-
- @Override
- public int hashCode() {
- return required.hashCode();
- }
-
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- buf.append("." + getName() + ":");
- for (Class intf: required) {
- buf.append("." + intf.getName());
- }
- return buf.toString();
- }
+ return buf.toString();
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import java.util.List;
import java.util.Map;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DefaultScope implements Scope {
+ /**
+ * DOCUMENT ME!
+ */
+ private List<Scope> parents;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<String, Object> properties;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<String, Object> runtimes;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<ProvidedInterface, ProvidedInterfaceImplementation> provided;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private List<ProvidedInterface> externallyProvided;
+
+/**
+ * Creates a new DefaultScope object.
+ *
+ * @param aExternallyProvided DOCUMENT ME!
+ */
+ public DefaultScope(List<ProvidedInterface> aExternallyProvided) {
+ this(aExternallyProvided.toArray(new ProvidedInterface[0]));
+ }
+
+/**
+ * Creates a new DefaultScope object.
+ *
+ * @param aExternallyProvided DOCUMENT ME!
+ */
+ public DefaultScope(ProvidedInterface[] aExternallyProvided) {
+ this(aExternallyProvided, new ArrayList<Scope>());
+ }
+
+/**
+ * Creates a new DefaultScope object.
+ *
+ * @param aExternallyProvided DOCUMENT ME!
+ * @param aParent DOCUMENT ME!
+ */
+ public DefaultScope(ProvidedInterface[] aExternallyProvided, Scope aParent) {
+ this(aExternallyProvided, Arrays.asList(new Scope[] { aParent }));
+ }
+
+/**
+ * Creates a new DefaultScope object.
+ *
+ * @param aExternallyProvided DOCUMENT ME!
+ * @param aParent DOCUMENT ME!
+ */
+ public DefaultScope(ProvidedInterface[] aExternallyProvided,
+ List<Scope> aParent) {
+ parents = new ArrayList<Scope>(aParent);
+ properties = new HashMap<String, Object>();
+ runtimes = new HashMap<String, Object>();
+ provided = new HashMap<ProvidedInterface, ProvidedInterfaceImplementation>();
+ externallyProvided = new ArrayList<ProvidedInterface>();
+ externallyProvided.addAll(Arrays.asList(aExternallyProvided));
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public List<ProvidedInterface> getProvidedInterfaces() {
+ return Collections.unmodifiableList(externallyProvided);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public Object get(String aKey) {
+ return properties.get(aKey);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aKey DOCUMENT ME!
+ * @param aValue DOCUMENT ME!
+ */
+ @Override
+ public void put(String aKey, Object aValue) {
+ properties.put(aKey, aValue);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aComponent DOCUMENT ME!
+ * @param aRuntime DOCUMENT ME!
+ */
+ @Override
+ public void addRuntime(Component aComponent, Object aRuntime) {
+ runtimes.put(aComponent.getName(), aRuntime);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aComponent DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public Object getRuntime(Component aComponent) {
+ return runtimes.get(aComponent.getName());
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public Object getRuntime(String aName) {
+ return runtimes.get(aName);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aInterface DOCUMENT ME!
+ * @param aImplementation DOCUMENT ME!
+ */
+ @Override
+ synchronized public void publishInterface(ProvidedInterface aInterface,
+ Object aImplementation) {
+ provided.put(aInterface,
+ new ProvidedInterfaceImplementation(aInterface, aImplementation));
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aInterface DOCUMENT ME!
+ * @param aType DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public <T> T getInterfaceImplementation(ProvidedInterface aInterface,
+ Class<T> aType) {
+ if (aInterface == null) {
+ return null;
+ }
+
+ ProvidedInterfaceImplementation providedIntf = provided.get(aInterface);
+
+ if (providedIntf == null) {
+ for (Scope parent : parents) {
+ T impl = parent.getInterfaceImplementation(aInterface, aType);
+
+ if (impl != null) {
+ return impl;
+ }
+ }
- private List<Scope> parents;
- private Map<String, Object> properties;
- private Map<String, Object> runtimes;
- private Map<ProvidedInterface, ProvidedInterfaceImplementation> provided;
- private List<ProvidedInterface> externallyProvided;
-
- public DefaultScope(List<ProvidedInterface>aExternallyProvided) {
- this(aExternallyProvided.toArray(new ProvidedInterface[0]));
- }
-
- public DefaultScope(ProvidedInterface[] aExternallyProvided) {
- this(aExternallyProvided, new ArrayList<Scope>());
- }
-
- public DefaultScope(ProvidedInterface[] aExternallyProvided, Scope aParent) {
- this(aExternallyProvided, Arrays.asList(new Scope[] { aParent }));
- }
-
- public DefaultScope(ProvidedInterface[] aExternallyProvided,
- List<Scope> aParent) {
- parents = new ArrayList<Scope>(aParent);
- properties = new HashMap<String, Object>();
- runtimes = new HashMap<String, Object>();
- provided = new HashMap<ProvidedInterface, ProvidedInterfaceImplementation>();
- externallyProvided = new ArrayList<ProvidedInterface>();
- externallyProvided.addAll(Arrays.asList(aExternallyProvided));
- }
-
- @Override
- public List<ProvidedInterface> getProvidedInterfaces() {
- return Collections.unmodifiableList(externallyProvided);
- }
-
- @Override
- public Object get(String aKey) {
- return properties.get(aKey);
- }
-
- @Override
- public void put(String aKey, Object aValue) {
- properties.put(aKey, aValue);
- }
-
- @Override
- public void addRuntime(Component aComponent, Object aRuntime) {
- runtimes.put(aComponent.getName(), aRuntime);
- }
-
- @Override
- public Object getRuntime(Component aComponent) {
- return runtimes.get(aComponent.getName());
- }
-
- @Override
- public Object getRuntime(String aName) {
- return runtimes.get(aName);
- }
-
- @Override
- synchronized public void publishInterface(ProvidedInterface aInterface,
- Object aImplementation) {
- provided.put(aInterface, new ProvidedInterfaceImplementation(aInterface,
- aImplementation));
- }
-
- @Override
- public <T> T getInterfaceImplementation(ProvidedInterface aInterface,
- Class<T> aType) {
- if ( aInterface == null ) {
- return null;
- }
- ProvidedInterfaceImplementation providedIntf = provided.get(aInterface);
- if (providedIntf == null) {
- for (Scope parent : parents) {
- T impl = parent.getInterfaceImplementation(aInterface, aType);
- if ( impl != null ) {
- return impl;
- }
- }
- return null;
- } else {
- return providedIntf.getImplementation(aType);
- }
- }
+ return null;
+ } else {
+ return providedIntf.getImplementation(aType);
+ }
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision: 1.6 $
+ */
public interface NamedInterface {
/**
- * Name for the interface.
+ * Name for the interface.
+ *
+ * @return DOCUMENT ME!
*/
String getName();
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
import java.util.Collection;
+
/**
* Represents an interface provided by a component.
* Different component objects should never share ProvidedInterface instances!
* @author Erik Brakkee
*/
public interface ProvidedInterface extends NamedInterface {
-
- /**
- * Returns the service type.
- * @return Service type.
- */
- Class[] getInterfaceTypes();
-
-
- /**
- * Determines whether the current provided interface exceeds the given provided interface.
- * In other words if it can provide at least what the given provided interface can provide.
- * @param aInterface Interface to compare to.
- * @return True if the current interface exceeds the given provided interface.
- */
- boolean covers(ProvidedInterface aInterface);
+ /**
+ * Returns the service type.
+ *
+ * @return Service type.
+ */
+ Class[] getInterfaceTypes();
+
+ /**
+ * Determines whether the current provided interface exceeds the
+ * given provided interface. In other words if it can provide at least
+ * what the given provided interface can provide.
+ *
+ * @param aInterface Interface to compare to.
+ *
+ * @return True if the current interface exceeds the given provided
+ * interface.
+ */
+ boolean covers(ProvidedInterface aInterface);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
/**
- * Represents a provided interface together with its implementation.
- *
+ * Represents a provided interface together with its implementation.
+ *
* @author Erik Brakkee
*/
class ProvidedInterfaceImplementation {
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface _provided;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Object _implementation;
+
+/**
+ * Constructs the object.
+ * @param aProvided Provided interface.
+ * @param aImplementation Implementation.
+ */
+ public ProvidedInterfaceImplementation(ProvidedInterface aProvided,
+ Object aImplementation) {
+ _provided = aProvided;
+ _implementation = aImplementation;
+ }
- private ProvidedInterface _provided;
- private Object _implementation;
-
- /**
- * Constructs the object.
- * @param aProvided Provided interface.
- * @param aImplementation Implementation.
- */
- public ProvidedInterfaceImplementation(ProvidedInterface aProvided, Object aImplementation) {
- _provided = aProvided;
- _implementation = aImplementation;
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return The provided interface.
+ */
+ public ProvidedInterface getProvided() {
+ return _provided;
+ }
- /**
- * @return The provided interface.
- */
- public ProvidedInterface getProvided() {
- return _provided;
- }
-
- /**
- * @param <T> Expected type of the implementation.
- * @param aType Type of the implementation.
- * @return Implementation.
- */
- public <T> T getImplementation(Class<T> aType) {
- return (T)_implementation;
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> Expected type of the implementation.
+ * @param aType Type of the implementation.
+ *
+ * @return Implementation.
+ */
+ public <T> T getImplementation(Class<T> aType) {
+ return (T) _implementation;
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision: 1.6 $
+ */
public interface RequiredInterface extends NamedInterface {
-
- /**
- * @return True iff the required interface is optional.
- */
- boolean isOptional();
-
-
- /**
- * Checks if the service is provided by a given provided interface.
- * @param aInterface Provided interface.
- * @return
- */
- boolean implementedBy(ProvidedInterface aInterface);
-
- /**
- * Sets the provider of this interface.
- * @param aProvider Provider.
- */
- void setProvider(ProvidedInterface aProvider);
-
- /**
- * Gets the provider interface.
- * @return Provider or null if not set.
- */
- ProvidedInterface getProvider();
-
- /**
- * Determines if the requirements of the current interface are at least those
- * of the given required interface.
- */
- boolean covers(RequiredInterface aInterface);
+ /**
+ * DOCUMENT ME!
+ *
+ * @return True iff the required interface is optional.
+ */
+ boolean isOptional();
+
+ /**
+ * Checks if the service is provided by a given provided interface.
+ *
+ * @param aInterface Provided interface.
+ *
+ * @return
+ */
+ boolean implementedBy(ProvidedInterface aInterface);
+
+ /**
+ * Sets the provider of this interface.
+ *
+ * @param aProvider Provider.
+ */
+ void setProvider(ProvidedInterface aProvider);
+
+ /**
+ * Gets the provider interface.
+ *
+ * @return Provider or null if not set.
+ */
+ ProvidedInterface getProvider();
+
+ /**
+ * Determines if the requirements of the current interface are at
+ * least those of the given required interface.
+ *
+ * @param aInterface DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ boolean covers(RequiredInterface aInterface);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
import java.util.List;
+
/**
* A scope represents a set of running services and the runtime information for the
* started components and is (usually) the result of
* @author Erik Brakkee
*/
public interface Scope {
-
- /**
- * Gets the provided interfaces by this scope.
- * @return Provided interfaces.
- */
- List<ProvidedInterface> getProvidedInterfaces();
-
- /**
- * Adds a key value pair to the scope.
- * @param aKey Key
- * @param aValue Value.
- */
- void put(String aKey, Object aValue);
-
- /**
- * Retrieves a value for the key.
- * @param aKey Key.
- * @return Value.
- */
- Object get(String aKey);
-
- /**
- * Adds the runtime of a started component.
- * @param aComponent Component.
- * @param aRuntime Runtime.
- */
- void addRuntime(Component aComponent, Object aRuntime);
-
- /**
- * Publishes an implementation of a provided interface.
- * @param aInterface Interface that is provided.
- * @param aImplementation Implementation of the interface.
- */
- void publishInterface(ProvidedInterface aInterface, Object aImplementation);
-
- /**
- * Retrieves an implementation of a provided interface.
- * @param aProvided P
- * rovided interface. If it is null then null is returned.
- * @param aType Type of implementation that is expected.
- * @return Retrieved interface.
- */
- <T> T getInterfaceImplementation(ProvidedInterface aProvided, Class<T> aType );
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
+ * Gets the provided interfaces by this scope.
+ * @return Provided interfaces.
+ */
+ List<ProvidedInterface> getProvidedInterfaces();
+
+ /**
+ * Adds a key value pair to the scope.
+ *
+ * @param aKey Key
+ * @param aValue Value.
+ */
+ void put(String aKey, Object aValue);
+
+ /**
+ * Retrieves a value for the key.
+ *
+ * @param aKey Key.
+ *
+ * @return Value.
+ */
+ Object get(String aKey);
+
+ /**
+ * Adds the runtime of a started component.
+ *
+ * @param aComponent Component.
+ * @param aRuntime Runtime.
+ */
+ void addRuntime(Component aComponent, Object aRuntime);
+
+ /**
+ * Publishes an implementation of a provided interface.
+ *
+ * @param aInterface Interface that is provided.
+ * @param aImplementation Implementation of the interface.
+ */
+ void publishInterface(ProvidedInterface aInterface, Object aImplementation);
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param <T> DOCUMENT ME!
+ * @param aProvided DOCUMENT ME!
+ * @param aType DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ <T> T getInterfaceImplementation(ProvidedInterface aProvided, Class<T> aType);
+
+ /**
+ * Gets the runtime for a component.
+ *
+ * @param aComponent Component for which we want to get the runtime.
+ *
+ * @return Runtime.
+ */
+ Object getRuntime(Component aComponent);
- /**
- * Gets the runtime for a component.
- * @param aComponent Component for which we want to get the runtime.
- * @return Runtime.
- */
- Object getRuntime(Component aComponent);
-
- /**
- * Gets the runtime for a component based on the name of the component
- * (excluding its context).
- * @param aName Component name.
- * @return Component name.
- */
- Object getRuntime(String aName);
+ /**
+ * Gets the runtime for a component based on the name of the
+ * component (excluding its context).
+ *
+ * @param aName Component name.
+ *
+ * @return Component name.
+ */
+ Object getRuntime(String aName);
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
/**
* @author Erik Brakkee
*/
public class SystemAssemblyException extends RuntimeException {
+/**
+ * Constructs the exception.
+ * @param aMsg Message.
+ */
+ public SystemAssemblyException(String aMsg) {
+ super(aMsg);
+ }
- /**
- * Constructs the exception.
- * @param aMsg Message.
- */
- public SystemAssemblyException(String aMsg) {
- super(aMsg);
- }
-
- /**
- * Constructs the exception.
- * @param aMsg Message
- * @param aCause Cause.
- */
- public SystemAssemblyException(String aMsg, Throwable aCause) {
- super(aMsg, aCause);
- }
+/**
+ * Constructs the exception.
+ * @param aMsg Message
+ * @param aCause Cause.
+ */
+ public SystemAssemblyException(String aMsg, Throwable aCause) {
+ super(aMsg, aCause);
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
import java.util.ArrayList;
import java.util.List;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class CompositeEdgeFilter implements EdgeFilter {
-
- private List<EdgeFilter> filters;
-
- public CompositeEdgeFilter() {
+ /**
+ * DOCUMENT ME!
+ */
+ private List<EdgeFilter> filters;
+
+ /**
+ * Creates a new CompositeEdgeFilter object.
+ */
+ public CompositeEdgeFilter() {
filters = new ArrayList<EdgeFilter>();
}
-
- public void add(EdgeFilter aFilter) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aFilter DOCUMENT ME!
+ */
+ public void add(EdgeFilter aFilter) {
filters.add(aFilter);
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public boolean isViolated(Edge aEdge) {
- for (EdgeFilter filter: filters) {
- if ( filter.isViolated(aEdge) ) {
- return true;
+ for (EdgeFilter filter : filters) {
+ if (filter.isViolated(aEdge)) {
+ return true;
}
}
- return false;
- }
+ return false;
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
/**
- * Represents an application-independent edge of a graph.
- * Applications might choose to implement the Edge interface
- * directly.
- *
+ * Represents an application-independent edge of a graph. Applications
+ * might choose to implement the Edge interface directly.
+ *
* @author Erik Brakkee
*/
public class DefaultEdge implements Edge {
-
- private Node from;
- private Node to;
-
- public DefaultEdge(Node aFrom, Node aTo) {
- from = aFrom;
- to = aTo;
+ /**
+ * DOCUMENT ME!
+ */
+ private Node from;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Node to;
+
+ /**
+ * Creates a new DefaultEdge object.
+ *
+ * @param aFrom DOCUMENT ME!
+ * @param aTo DOCUMENT ME!
+ */
+ public DefaultEdge(Node aFrom, Node aTo) {
+ from = aFrom;
+ to = aTo;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public Node getFrom() {
return from;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public Node getTo() {
- return to;
+ return to;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
return "Edge(" + from.getName() + ", " + to.getName() + ")";
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
/**
- * Default application-independent node. Specific applications of the graph might
- * implement the Node interface directly.
- * @author Erik Brakkee
+ * Default application-independent node. Specific applications of the graph
+ * might implement the Node interface directly.
*
+ * @author Erik Brakkee
*/
public class DefaultNode implements Node {
-
- private String name;
-
/**
+ * DOCUMENT ME!
+ */
+ private String name;
+
+/**
* Constructs the node.
* @param aName Node name.
*/
- public DefaultNode(String aName) {
- name = aName;
+ public DefaultNode(String aName) {
+ name = aName;
}
/**
- * Returns the node name.
+ * Returns the node name.
+ *
+ * @return DOCUMENT ME!
*/
@Override
public String getName() {
return name;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aObj DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public boolean equals(Object aObj) {
- if ( !(aObj instanceof Node)) {
- return false;
+ if (!(aObj instanceof Node)) {
+ return false;
}
- Node node = (Node)aObj;
+
+ Node node = (Node) aObj;
+
return name.equals(node.getName());
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public int hashCode() {
return name.hashCode();
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
/**
* @author Erik Brakkee
*/
public interface Edge {
-
/**
- * @return The from part of the edge.
+ *
+ DOCUMENT ME!
+ *
+ * @return The from part of the edge.
*/
Node getFrom();
-
+
/**
- * @return The to part of the edge.
+ *
+ DOCUMENT ME!
+ *
+ * @return The to part of the edge.
*/
Node getTo();
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
import java.util.List;
+
/**
* Edge factory used to extend a graph with new edges.
* @author Erik Brakkee
*/
public interface EdgeFactory<NodeType extends Node> {
/**
+ * DOCUMENT ME!
+ *
+ * @param aFrom DOCUMENT ME!
+ * @param aTo DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+/**
* Computes a number of new edges to be added to the graph.
* @param aFrom From node.
* @param aTo To node.
* @return List of edges from the from to the to node.
*/
- List<Edge> create(NodeType aFrom, NodeType aTo);
+ List<Edge> create(NodeType aFrom, NodeType aTo);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision: 1.6 $
+ */
public interface EdgeFilter {
-
- boolean isViolated(Edge aEdge);
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ boolean isViolated(Edge aEdge);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ *
+ * @param <FromType> DOCUMENT ME!
+ * @param <ToType> DOCUMENT ME!
+ */
public class EdgeSelector<FromType extends Node, ToType extends Node> {
-
- public static interface Selector<FromType extends Node, ToType extends Node> {
- void execute(FromType aFrom, ToType aTo);
- }
-
- private Class<FromType> fromType;
+ /**
+ * DOCUMENT ME!
+ */
+ private Class<FromType> fromType;
+
+ /**
+ * DOCUMENT ME!
+ */
private Class<ToType> toType;
-
+
+ /**
+ * Creates a new EdgeSelector object.
+ *
+ * @param aFrom DOCUMENT ME!
+ * @param aTo DOCUMENT ME!
+ */
public EdgeSelector(Class<FromType> aFrom, Class<ToType> aTo) {
- fromType = aFrom;
- toType = aTo;
+ fromType = aFrom;
+ toType = aTo;
}
- public void execute(Selector<FromType,ToType> aSelector, Edge aEdge) {
- if ( fromType.isInstance(aEdge.getFrom()) && toType.isInstance(aEdge.getTo())) {
- aSelector.execute((FromType)aEdge.getFrom(), (ToType)aEdge.getTo());
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aSelector DOCUMENT ME!
+ * @param aEdge DOCUMENT ME!
+ */
+ public void execute(Selector<FromType, ToType> aSelector, Edge aEdge) {
+ if (fromType.isInstance(aEdge.getFrom())
+ && toType.isInstance(aEdge.getTo())) {
+ aSelector.execute((FromType) aEdge.getFrom(), (ToType) aEdge.getTo());
+ }
+ }
+
+ public static interface Selector<FromType extends Node, ToType extends Node> {
+ void execute(FromType aFrom, ToType aTo);
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import java.util.Iterator;
import java.util.List;
+
/**
* Represents a graph consisting of nodes and edges.
- *
+ *
* @author Erik Brakkee
*/
public class Graph {
-
+ /**
+ * DOCUMENT ME!
+ */
private List<Node> nodes;
- private List<Edge> edges;
/**
+ * DOCUMENT ME!
+ */
+ private List<Edge> edges;
+
+/**
* Constructs the graph.
*/
public Graph() {
- nodes = new ArrayList<Node>();
- edges = new ArrayList<Edge>();
+ nodes = new ArrayList<Node>();
+ edges = new ArrayList<Edge>();
}
/**
* Adds a node.
- *
- * @param aNode
- * Node to add.
- * @throws IllegalArgumentException
- * In case the node already exists. Node equality is checked
- * using <code>equals</code>.
+ *
+ * @param aNode Node to add.
+ *
+ * @throws IllegalArgumentException In case the node already exists. Node
+ * equality is checked using <code>equals</code>.
*/
public void addNode(Node aNode) {
if (nodes.contains(aNode)) {
throw new IllegalArgumentException("Node '" + aNode.getName()
- + "' already exists");
+ + "' already exists");
}
+
nodes.add(aNode);
}
/**
* Finds a node with the given name.
- *
- * @param aName
- * Node name.
+ *
+ * @param aName Node name.
+ *
* @return Node or null if not found.
*/
public Node findNode(String aName) {
return node;
}
}
+
return null;
}
/**
* Removes a node.
- *
- * @param aNode
- * Node to remove.
+ *
+ * @param aNode Node to remove.
+ *
* @return True iff the node was removed.
- * @throws IllegalArgumentException
- * In case there are edges of which the node is a part.
+ *
+ * @throws IllegalArgumentException In case there are edges of which the
+ * node is a part.
*/
public boolean removeNode(Node aNode) {
if (!findOutgoing(aNode).isEmpty() || !findIncoming(aNode).isEmpty()) {
throw new IllegalArgumentException("Cannot remove node '"
- + aNode.getName()
- + "' because it is connected to one or more edges");
+ + aNode.getName()
+ + "' because it is connected to one or more edges");
}
+
return nodes.remove(aNode);
}
/**
* Adds a list of nodes.
- *
- * @param aNodes
- * Nodes to add.
- *
+ *
+ * @param aNodes Nodes to add.
+ *
* @see #addNode(Node)
*/
public void addNodes(List<Node> aNodes) {
/**
* Adds an edge.
- *
- * @param aEdge
- * Edge to add.
- * @throws IllegalArgumentException
- * In case one of the nodes of the edges is not part of the
- * graph or if the same edge (as determined by
- * {@link #equals(Object)} is already a part of the graph.
+ *
+ * @param aEdge Edge to add.
+ *
+ * @throws IllegalArgumentException In case one of the nodes of the edges
+ * is not part of the graph or if the same edge (as determined by
+ * {@link #equals(Object)} is already a part of the graph.
*/
public void addEdge(Edge aEdge) {
if (edges.contains(aEdge)) {
throw new IllegalArgumentException("Edge '" + aEdge
- + "' already exists");
+ + "' already exists");
}
+
if (!nodes.contains(aEdge.getFrom())) {
throw new IllegalArgumentException("From node '" + aEdge.getFrom()
- + "' from edge '" + aEdge + "' is not part of the graph");
+ + "' from edge '" + aEdge + "' is not part of the graph");
}
+
if (!nodes.contains(aEdge.getTo())) {
throw new IllegalArgumentException("To node '" + aEdge.getTo()
- + "' from edge '" + aEdge + "' is not part of the graph");
+ + "' from edge '" + aEdge + "' is not part of the graph");
}
+
edges.add(aEdge);
}
/**
- * Removes an edge.
- * @param aEdge Edge to remove.
- * @return True if the edge was removed.
+ * Removes an edge.
+ *
+ * @param aEdge Edge to remove.
+ *
+ * @return True if the edge was removed.
*/
public boolean removeEdge(Edge aEdge) {
return edges.remove(aEdge);
}
/**
- * Adds a number of edges.
- * @param aEdges Edges to add.
+ * Adds a number of edges.
+ *
+ * @param aEdges Edges to add.
*/
public void addEdges(List<Edge> aEdges) {
for (Edge edge : aEdges) {
}
/**
- * Gets the nodes.
- * @return Copy of the list of nodes of the graph.
+ * Gets the nodes.
+ *
+ * @return Copy of the list of nodes of the graph.
*/
public List<Node> getNodes() {
return new ArrayList<Node>(nodes);
}
/**
- * Gets the edges.
- * @return Copy of the list of edges of the graph.
+ * Gets the edges.
+ *
+ * @return Copy of the list of edges of the graph.
*/
public List<Edge> getEdges() {
return new ArrayList<Edge>(edges);
}
/**
- * Extends the graph with edges using an edge factory. All combinations of
- * nodes are passed to the factory which creates additional edges.
- * @param aFactory Edge factory.
+ * Extends the graph with edges using an edge factory. All
+ * combinations of nodes are passed to the factory which creates
+ * additional edges.
+ *
+ * @param aFactory Edge factory.
*/
public void extend(EdgeFactory aFactory) {
for (Node from : nodes) {
}
}
}
-
+
/**
- * Applies a filter to the graph for removing elements.
- * @param aFilter Filter to apply.
+ * Applies a filter to the graph for removing elements.
+ *
+ * @param aFilter Filter to apply.
*/
public void applyFilter(EdgeFilter aFilter) {
- for (Iterator<Edge> edge = edges.iterator(); edge.hasNext(); ) {
- if (aFilter.isViolated(edge.next())) {
+ for (Iterator<Edge> edge = edges.iterator(); edge.hasNext();) {
+ if (aFilter.isViolated(edge.next())) {
edge.remove();
}
}
}
/**
- * Finds all outgoing edges of a node. More specifically, finds
- * all edges <code>e</code> for which <code>e.getFrom().getName() = aNode.getName()</code>.
- * @param aNode Node for which to find outgoing edges.
- * @return List of outgoing edges.
+ * Finds all outgoing edges of a node. More specifically, finds
+ * all edges <code>e</code> for which <code>e.getFrom().getName() =
+ * aNode.getName()</code>.
+ *
+ * @param aNode Node for which to find outgoing edges.
+ *
+ * @return List of outgoing edges.
*/
public List<Edge> findOutgoing(Node aNode) {
List<Edge> result = new ArrayList<Edge>();
+
for (Edge edge : edges) {
if (edge.getFrom().getName().equals(aNode.getName())) {
result.add(edge);
}
}
+
return result;
}
/**
- * Finds all incoming edges of a node.
- * More specifically, finds
- * all edges <code>e</code> for which <code>e.getTo().getName() = aNode.getName()</code>.
- * @param aNode Node for which to find incoming edges.
- * @return List of incoming edges.
+ * Finds all incoming edges of a node. More specifically, finds
+ * all edges <code>e</code> for which <code>e.getTo().getName() =
+ * aNode.getName()</code>.
+ *
+ * @param aNode Node for which to find incoming edges.
+ *
+ * @return List of incoming edges.
*/
public List<Edge> findIncoming(Node aNode) {
List<Edge> result = new ArrayList<Edge>();
+
for (Edge edge : edges) {
if (edge.getTo().getName().equals(aNode.getName())) {
result.add(edge);
}
}
+
return result;
}
/**
- * Implements a visitor design pattern.
- * This loops over all nodes and all edges and invokes the appropriate visit
- * methods on the visitor.
- * @param aVisitor Visitor.
+ * Implements a visitor design pattern. This loops over all nodes
+ * and all edges and invokes the appropriate visit methods on the visitor.
+ *
+ * @param aVisitor Visitor.
*/
public void accept(Visitor aVisitor) {
List<Node> nodes = getNodes(); // copy to make sure the visitor can
- // modify the
- // list of nodes as part of the loop.
+ // modify the
+ // list of nodes as part of the loop.
+
List<Edge> edges = getEdges(); // copy ..... (see above).
for (Node node : nodes) {
aVisitor.visitNode(node);
}
+
for (Edge edge : edges) {
aVisitor.visitEdge(edge);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
/**
* @author Erik Brakkee
*/
public interface Node {
-
/**
- * Gets the node name uniquely identifying the node in the graph.
- * @return Node name.
+ * Gets the node name uniquely identifying the node in the graph.
+ *
+ * @return Node name.
*/
String getName();
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
/**
*
*/
public interface Visitor {
-
/**
* Visits a node. Called by {@link Graph#accept(Visitor)}.
- * @param aNode Node to visit.
+ *
+ * @param aNode Node to visit.
*/
- void visitNode(Node aNode);
-
+ void visitNode(Node aNode);
+
/**
* Visits a node. Called by {@link Graph#accept(Visitor)}.
- * @param aEdge Edge to visit.
+ *
+ * @param aEdge Edge to visit.
*/
- void visitEdge(Edge aEdge);
+ void visitEdge(Edge aEdge);
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
-import java.util.List;
-
import org.wamblee.system.core.SystemAssemblyException;
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.Graph;
import org.wamblee.system.graph.Node;
import org.wamblee.system.graph.Visitor;
+import java.util.List;
+
+
/**
- * Visitor that checks whether all externally provided interfaces are actually provided
- * by any of the internal components.
- *
- * @author Erik Brakkee
+ * Visitor that checks whether all externally provided interfaces are
+ * actually provided by any of the internal components.
*
+ * @author Erik Brakkee
*/
public class CheckExternallyProvidedVisitor implements Visitor {
-
- private Graph graph;
-
/**
+ * DOCUMENT ME!
+ */
+ private Graph graph;
+
+/**
* Constructs the visitor.
* @param aGraph Component graph.
*/
- public CheckExternallyProvidedVisitor(Graph aGraph) {
- graph = aGraph;
+ public CheckExternallyProvidedVisitor(Graph aGraph) {
+ graph = aGraph;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ */
@Override
public void visitEdge(Edge aEdge) {
// Empty.
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aNode DOCUMENT ME!
+ */
@Override
public void visitNode(Node aNode) {
- if ( aNode instanceof ExternalProvidedInterfaceNode) {
- ExternalProvidedInterfaceNode provided = (ExternalProvidedInterfaceNode) aNode;
- List<Edge> edges = graph.findOutgoing(provided);
- if ( edges.size() > 2 ) {
- createDuplicateException("External provided interfaces has multiple internal matches", aNode, edges);
+ if (aNode instanceof ExternalProvidedInterfaceNode) {
+ ExternalProvidedInterfaceNode provided = (ExternalProvidedInterfaceNode) aNode;
+ List<Edge> edges = graph
+ .findOutgoing(provided);
+
+ if (edges.size() > 2) {
+ createDuplicateException("External provided interfaces has multiple internal matches",
+ aNode, edges);
}
- if ( edges.size() == 0 ) {
- throw new SystemAssemblyException(aNode + ": external provded interface is not provided by any of the internal components");
+
+ if (edges.size() == 0) {
+ throw new SystemAssemblyException(aNode
+ + ": external provded interface is not provided by any of the internal components");
}
}
}
-
- private void createDuplicateException(String aMsg, Node aNode, List<Edge> edges) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aMsg DOCUMENT ME!
+ * @param aNode DOCUMENT ME!
+ * @param edges DOCUMENT ME!
+ */
+ private void createDuplicateException(String aMsg, Node aNode,
+ List<Edge> edges) {
StringBuffer buf = new StringBuffer();
- buf.append(aNode
- + ": " + aMsg + ": ");
+ buf.append(aNode + ": " + aMsg + ": ");
+
for (Edge edge : edges) {
buf.append(edge.getTo() + "/ ");
}
+
throw new SystemAssemblyException(buf.toString());
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.graph.component;
-import java.util.List;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.wamblee.system.core.SystemAssemblyException;
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.Graph;
import org.wamblee.system.graph.Node;
import org.wamblee.system.graph.Visitor;
+import java.util.List;
+
+
/**
- * Visitor that checks whether all required external interfaces of the container
- * are provided.
- *
+ * Visitor that checks whether all required external interfaces of the
+ * container are provided.
+ *
* @author Erik Brakkee
- *
*/
public class CheckExternallyRequiredVisitor implements Visitor {
-
+ /**
+ * DOCUMENT ME!
+ */
private Log LOG = LogFactory.getLog(CheckExternallyRequiredVisitor.class);
+ /**
+ * DOCUMENT ME!
+ */
private Graph graph;
+ /**
+ * Creates a new CheckExternallyRequiredVisitor object.
+ *
+ * @param aGraph DOCUMENT ME!
+ */
public CheckExternallyRequiredVisitor(Graph aGraph) {
graph = aGraph;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ */
@Override
public void visitEdge(Edge aEdge) {
// Empty.
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aNode DOCUMENT ME!
+ */
@Override
public void visitNode(Node aNode) {
if (aNode instanceof ExternalRequiredInterfaceNode) {
ExternalRequiredInterfaceNode required = (ExternalRequiredInterfaceNode) aNode;
+
if (!required.getRequired().isOptional()
- && required.getRequired().getProvider() == null) {
+ && (required.getRequired().getProvider() == null)) {
throw new SystemAssemblyException(aNode
- + ": External required interface is not provided");
+ + ": External required interface is not provided");
}
List<Edge> edges = graph.findIncoming(aNode);
if (edges.isEmpty()) {
LOG.warn(aNode + ": Superfluous required interface");
}
+
for (Edge edge : edges) {
Node from = edge.getFrom();
assert from instanceof RequiredInterfaceNode;
- RequiredInterfaceNode reqNode = (RequiredInterfaceNode)from;
+
+ RequiredInterfaceNode reqNode = (RequiredInterfaceNode) from;
+
if (!reqNode.getRequired().isOptional()
&& required.getRequired().isOptional()) {
- throw new SystemAssemblyException(
- aNode
- + ": externally required interface is optional but a corresponding internal required interface is mandatory: "
- + reqNode);
+ throw new SystemAssemblyException(aNode
+ + ": externally required interface is optional but a corresponding internal required interface is mandatory: "
+ + reqNode);
}
}
}
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.graph.component;
-import java.util.List;
-
import org.wamblee.system.core.SystemAssemblyException;
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.Graph;
import org.wamblee.system.graph.Node;
import org.wamblee.system.graph.Visitor;
+import java.util.List;
+
+
/**
* Visitor that checks whether required and provided interfaces are matched
* appropriately:
- * <ul>
- * <li>Each required interface is connected to at most one provided interface
- * </li>
- * <li>Required interfaces that are not optional must be connected to precisely
- * one provided interface</li>
- * </ul>
- *
+ * <ul>
+ * <li>Each required interface is connected to at most one
+ * provided interface</li>
+ * <li>Required interfaces that are not optional must be connected
+ * to precisely one provided interface</li>
+ * </ul>
+ *
* @author Erik Brakkee
- *
*/
public class CheckRequiredProvidedMultiplicityVisitor implements Visitor {
-
+ /**
+ * DOCUMENT ME!
+ */
private Graph graph;
+ /**
+ * Creates a new CheckRequiredProvidedMultiplicityVisitor object.
+ *
+ * @param aGraph DOCUMENT ME!
+ */
public CheckRequiredProvidedMultiplicityVisitor(Graph aGraph) {
graph = aGraph;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ */
@Override
public void visitEdge(Edge aEdge) {
// Empty
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aNode DOCUMENT ME!
+ */
@Override
public void visitNode(Node aNode) {
if (aNode instanceof RequiredInterfaceNode) {
RequiredInterfaceNode required = (RequiredInterfaceNode) aNode;
- List<Edge> edges = graph.findOutgoing(aNode);
+ List<Edge> edges = graph.findOutgoing(aNode);
+
if (edges.size() > 1) {
- createDuplicateException("Multiple providers of required interface found", aNode, edges);
+ createDuplicateException("Multiple providers of required interface found",
+ aNode, edges);
}
- if (edges.size() == 0 && !required.getRequired().isOptional()) {
- throw new SystemAssemblyException(
- aNode
- + ": mandatpory required interface not provided by other components started earlier");
+
+ if ((edges.size() == 0) && !required.getRequired().isOptional()) {
+ throw new SystemAssemblyException(aNode
+ + ": mandatpory required interface not provided by other components started earlier");
}
- } else if ( aNode instanceof ExternalProvidedInterfaceNode) {
- List<Edge> edges = graph.findOutgoing(aNode);
- if ( edges.size() > 1) {
- createDuplicateException("multiple internal matches for externally provided interface", aNode, edges);
+ } else if (aNode instanceof ExternalProvidedInterfaceNode) {
+ List<Edge> edges = graph.findOutgoing(aNode);
+
+ if (edges.size() > 1) {
+ createDuplicateException("multiple internal matches for externally provided interface",
+ aNode, edges);
}
- if ( edges.size() == 0 ) {
- throw new SystemAssemblyException(aNode + ": external provided interface is not provided internally");
+
+ if (edges.size() == 0) {
+ throw new SystemAssemblyException(aNode
+ + ": external provided interface is not provided internally");
}
}
}
- private void createDuplicateException(String aMsg, Node aNode, List<Edge> edges) {
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aMsg DOCUMENT ME!
+ * @param aNode DOCUMENT ME!
+ * @param edges DOCUMENT ME!
+ */
+ private void createDuplicateException(String aMsg, Node aNode,
+ List<Edge> edges) {
StringBuffer buf = new StringBuffer();
- buf.append(aNode
- + ": " + aMsg + ": ");
+ buf.append(aNode + ": " + aMsg + ": ");
+
for (Edge edge : edges) {
buf.append(edge.getTo() + "/ ");
}
+
throw new SystemAssemblyException(buf.toString());
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
-import java.util.ArrayList;
-import java.util.List;
-
import org.wamblee.system.core.SystemAssemblyException;
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.Graph;
import org.wamblee.system.graph.Node;
import org.wamblee.system.graph.Visitor;
+import java.util.ArrayList;
+import java.util.List;
+
+
/**
* Checks whether the given component graph can be started in component
- * order without any missing dependencies.
- * @author Erik Brakkee
+ * order without any missing dependencies.
*
+ * @author Erik Brakkee
*/
public class CheckStartupDependenciesVisitor implements Visitor {
-
- private Graph graph;
- private List<Node> available;
+ /**
+ * DOCUMENT ME!
+ */
+ private Graph graph;
/**
+ * DOCUMENT ME!
+ */
+ private List<Node> available;
+
+/**
* Constructs the visitor.
* @param aGraph Graph.
*/
- public CheckStartupDependenciesVisitor(Graph aGraph) {
- graph = aGraph;
- available = new ArrayList<Node>();
+ public CheckStartupDependenciesVisitor(Graph aGraph) {
+ graph = aGraph;
+ available = new ArrayList<Node>();
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ */
@Override
public void visitEdge(Edge aEdge) {
// Empty
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aNode DOCUMENT ME!
+ */
@Override
public void visitNode(Node aNode) {
List<Edge> edges = graph.findOutgoing(aNode);
-
+
// check dependencies.
- for (Edge edge: edges) {
+ for (Edge edge : edges) {
Node dep = edge.getTo();
- if ( !available.contains(dep)) {
- throw new SystemAssemblyException(aNode + ": required dependency '" + dep + "' was not started");
+
+ if (!available.contains(dep)) {
+ throw new SystemAssemblyException(aNode
+ + ": required dependency '" + dep + "' was not started");
}
}
-
+
available.add(aNode);
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
-import java.util.ArrayList;
-import java.util.List;
-
import org.wamblee.general.Pair;
+
import org.wamblee.system.core.Component;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.graph.Graph;
import org.wamblee.system.graph.Node;
+import java.util.ArrayList;
+import java.util.List;
+
+
/**
- * Represents a component graph and provides the bridge from the
- * component model to a graph model. The graph model is easier
- * to work with to implement specific actions and validations than
- * the component model.
+ * Represents a component graph and provides the bridge from the component
+ * model to a graph model. The graph model is easier to work with to implement
+ * specific actions and validations than the component model.
*/
public class ComponentGraph extends Graph {
-
- private boolean isLinked;
- private CompositeEdgeFilter edgeFilter;
+ /**
+ * DOCUMENT ME!
+ */
+ private boolean isLinked;
/**
+ * DOCUMENT ME!
+ */
+ private CompositeEdgeFilter edgeFilter;
+
+/**
* Constructs an empty component graph.
*/
public ComponentGraph() {
- isLinked = false;
- edgeFilter = new CompositeEdgeFilter();
+ isLinked = false;
+ edgeFilter = new CompositeEdgeFilter();
}
-
+
/**
- * Adds an externally required interface of a container.
- * This should be called before any components of the container are
- * added.
- * @param aComponent Component requiring the interface.
- * @param aInterface Required interface.
+ * Adds an externally required interface of a container. This
+ * should be called before any components of the container are added.
+ *
+ * @param aComponent Component requiring the interface.
+ * @param aInterface Required interface.
*/
- public void addRequiredInterface(Component aComponent, RequiredInterface aInterface) {
+ public void addRequiredInterface(Component aComponent,
+ RequiredInterface aInterface) {
addNode(new ExternalRequiredInterfaceNode(aComponent, aInterface));
}
-
+
/**
- * Adds an externally provided interface of a container.
- * This should be called after all components of the container have been added.
- * @param aComponent Component providing the interface.
- * @param aInterface Provided interface.
+ * Adds an externally provided interface of a container. This
+ * should be called after all components of the container have been added.
+ *
+ * @param aComponent Component providing the interface.
+ * @param aInterface Provided interface.
*/
- public void addProvidedInterface(Component aComponent, ProvidedInterface aInterface) {
+ public void addProvidedInterface(Component aComponent,
+ ProvidedInterface aInterface) {
addNode(new ExternalProvidedInterfaceNode(aComponent, aInterface));
}
-
+
/**
- * Validates the component graph.
+ * Validates the component graph.
*/
- public void validate() {
+ public void validate() {
extend(new RequiredProvidedEdgeFactory());
applyFilter(edgeFilter);
accept(new CheckRequiredProvidedMultiplicityVisitor(this));
- accept(new CheckExternallyRequiredVisitor(this));
+ accept(new CheckExternallyRequiredVisitor(this));
accept(new CheckExternallyProvidedVisitor(this));
accept(new CheckStartupDependenciesVisitor(this));
}
-
+
/**
* Links provided and required interfaces together in the component
- * model based on the graph model.
+ * model based on the graph model.
*/
public void link() {
- if ( isLinked ) {
- return;
+ if (isLinked) {
+ return;
}
+
accept(new LinkVisitor());
- isLinked = true;
+ isLinked = true;
}
-
+
/**
- * Finds a list of mappings of external provided interface to internal provided interface.
- *
- * @return List of pairs of external to internal interface.
+ * Finds a list of mappings of external provided interface to
+ * internal provided interface.
+ *
+ * @return List of pairs of external to internal interface.
*/
- public List<Pair<ProvidedInterface, ProvidedInterface>> findExternalProvidedInterfaceMapping() {
- List<Pair<ProvidedInterface, ProvidedInterface>> result =
- new ArrayList<Pair<ProvidedInterface,ProvidedInterface>>();
- for (Edge edge: getEdges()) {
- if ( edge.getFrom() instanceof ExternalProvidedInterfaceNode &&
- edge.getTo() instanceof ProvidedInterfaceNode ) {
- result.add(new Pair<ProvidedInterface,ProvidedInterface>(
- ((ExternalProvidedInterfaceNode)edge.getFrom()).getProvided(),
- ((ProvidedInterfaceNode)edge.getTo()).getProvided()
- ));
+ public List<Pair<ProvidedInterface, ProvidedInterface>> findExternalProvidedInterfaceMapping() {
+ List<Pair<ProvidedInterface, ProvidedInterface>> result = new ArrayList<Pair<ProvidedInterface, ProvidedInterface>>();
+
+ for (Edge edge : getEdges()) {
+ if (edge.getFrom() instanceof ExternalProvidedInterfaceNode
+ && edge.getTo() instanceof ProvidedInterfaceNode) {
+ result.add(new Pair<ProvidedInterface, ProvidedInterface>(
+ ((ExternalProvidedInterfaceNode) edge.getFrom())
+ .getProvided(),
+ ((ProvidedInterfaceNode) edge.getTo()).getProvided()));
}
}
- return result;
+
+ return result;
}
-
+
/**
* Adds a component by adding required interfaces, components, and
- * provided interfaces.
- * @param aComponent Component to add.
+ * provided interfaces.
+ *
+ * @param aComponent Component to add.
*/
- public void addComponent(Component<?> aComponent) {
+ public void addComponent(Component<?> aComponent) {
// Add required interfaces.
- Node compNode = new ComponentNode(aComponent);
+ Node compNode = new ComponentNode(aComponent);
List<Node> requiredNodes = new ArrayList<Node>();
- for (RequiredInterface required: aComponent.getRequiredInterfaces()) {
- Node reqNode = new RequiredInterfaceNode(aComponent, required);
+
+ for (RequiredInterface required : aComponent.getRequiredInterfaces()) {
+ Node reqNode = new RequiredInterfaceNode(aComponent, required);
addNode(reqNode);
requiredNodes.add(reqNode);
}
+
// Add the component
addNode(compNode);
-
+
// Edges from component to required interface.
- for (Node reqNode: requiredNodes) {
+ for (Node reqNode : requiredNodes) {
addEdge(new DefaultEdge(compNode, reqNode));
}
-
+
// Add provided interfaces
List<Node> providedNodes = new ArrayList<Node>();
- for (ProvidedInterface provided: aComponent.getProvidedInterfaces()) {
- Node provNode = new ProvidedInterfaceNode(aComponent, provided);
+
+ for (ProvidedInterface provided : aComponent.getProvidedInterfaces()) {
+ Node provNode = new ProvidedInterfaceNode(aComponent, provided);
addNode(provNode);
providedNodes.add(provNode);
}
-
+
// Edges from provided interface to component
- for (Node provNode: providedNodes) {
+ for (Node provNode : providedNodes) {
addEdge(new DefaultEdge(provNode, compNode));
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdgeFilter DOCUMENT ME!
+ */
public void addEdgeFilter(CompositeEdgeFilter aEdgeFilter) {
- edgeFilter.add(aEdgeFilter);
+ edgeFilter.add(aEdgeFilter);
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
import org.wamblee.system.core.Component;
import org.wamblee.system.graph.Node;
+
/**
- * Represents a component node.
- * @author Erik Brakkee.
+ * Represents a component node.
*
+ * @author Erik Brakkee.
*/
public class ComponentNode implements Node {
-
- private Component<?> component;
-
- public ComponentNode(Component<?> aComponent) {
- component = aComponent;
+ /**
+ * DOCUMENT ME!
+ */
+ private Component<?> component;
+
+ /**
+ * Creates a new ComponentNode object.
+ *
+ * @param aComponent DOCUMENT ME!
+ */
+ public ComponentNode(Component<?> aComponent) {
+ component = aComponent;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String getName() {
return component.getQualifiedName();
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Component<?> getComponent() {
return component;
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
+
/**
- * Filter used to explicitly connect required and provided interfaces within a
- * container.
- *
+ * Filter used to explicitly connect required and provided interfaces
+ * within a container.
+ *
* @author Erik Brakkee
- *
*/
public class ConnectExternalProvidedProvidedFilter implements EdgeFilter {
-
+ /**
+ * DOCUMENT ME!
+ */
private String externalProvided;
+
+ /**
+ * DOCUMENT ME!
+ */
private String component;
+
+ /**
+ * DOCUMENT ME!
+ */
private String provided;
- public ConnectExternalProvidedProvidedFilter(String aExternalProvided, String aComponent,
- String aProvided) {
- externalProvided = aExternalProvided;
- component = aComponent;
- provided = aProvided;
- if ( externalProvided == null ) {
- throw new IllegalArgumentException("External provided interface name must be specified.");
+ /**
+ * Creates a new ConnectExternalProvidedProvidedFilter object.
+ *
+ * @param aExternalProvided DOCUMENT ME!
+ * @param aComponent DOCUMENT ME!
+ * @param aProvided DOCUMENT ME!
+ */
+ public ConnectExternalProvidedProvidedFilter(String aExternalProvided,
+ String aComponent, String aProvided) {
+ externalProvided = aExternalProvided;
+ component = aComponent;
+ provided = aProvided;
+
+ if (externalProvided == null) {
+ throw new IllegalArgumentException(
+ "External provided interface name must be specified.");
}
- if ( component == null ) {
- throw new IllegalArgumentException("Component name must be specified");
+
+ if (component == null) {
+ throw new IllegalArgumentException(
+ "Component name must be specified");
}
- if ( provided == null ) {
- throw new IllegalArgumentException("Provided interface name of internal component must be specified");
+
+ if (provided == null) {
+ throw new IllegalArgumentException(
+ "Provided interface name of internal component must be specified");
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public boolean isViolated(Edge aEdge) {
if (aEdge.getFrom() instanceof ExternalProvidedInterfaceNode
&& aEdge.getTo() instanceof ProvidedInterfaceNode) {
return isViolated((ExternalProvidedInterfaceNode) aEdge.getFrom(),
- (ProvidedInterfaceNode) aEdge.getTo());
+ (ProvidedInterfaceNode) aEdge.getTo());
}
+
return false;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aFrom DOCUMENT ME!
+ * @param aTo DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private boolean isViolated(ExternalProvidedInterfaceNode aFrom,
- ProvidedInterfaceNode aTo) {
- if ( !aFrom.getName().equals(externalProvided)) {
+ ProvidedInterfaceNode aTo) {
+ if (!aFrom.getName().equals(externalProvided)) {
return false; // wrong provided interface.
}
- if ( aTo.getComponent().getName().equals(component) &&
- aTo.getProvided().getName().equals(provided) ) {
+
+ if (aTo.getComponent().getName().equals(component)
+ && aTo.getProvided().getName().equals(provided)) {
return false; // ok
}
- return true;
+
+ return true;
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
+
/**
- * Filter used to explicitly connect required and provided interfaces within a
- * container.
- *
+ * Filter used to explicitly connect required and provided interfaces
+ * within a container.
+ *
* @author Erik Brakkee
- *
*/
public class ConnectRequiredExternallyRequiredEdgeFilter implements EdgeFilter {
-
+ /**
+ * DOCUMENT ME!
+ */
private String client;
+
+ /**
+ * DOCUMENT ME!
+ */
private String required;
+
+ /**
+ * DOCUMENT ME!
+ */
private String externalRequired;
- public ConnectRequiredExternallyRequiredEdgeFilter(String aClient, String aRequired,
- String aExternalRequired) {
- client = aClient;
- required = aRequired;
- externalRequired = aExternalRequired;
- if ( client == null ) {
- throw new IllegalArgumentException("Client component must be specified");
+ /**
+ * Creates a new ConnectRequiredExternallyRequiredEdgeFilter object.
+ *
+ * @param aClient DOCUMENT ME!
+ * @param aRequired DOCUMENT ME!
+ * @param aExternalRequired DOCUMENT ME!
+ */
+ public ConnectRequiredExternallyRequiredEdgeFilter(String aClient,
+ String aRequired, String aExternalRequired) {
+ client = aClient;
+ required = aRequired;
+ externalRequired = aExternalRequired;
+
+ if (client == null) {
+ throw new IllegalArgumentException(
+ "Client component must be specified");
}
- if ( required == null ) {
- throw new IllegalArgumentException("Required interface must be specified");
+
+ if (required == null) {
+ throw new IllegalArgumentException(
+ "Required interface must be specified");
}
- if ( externalRequired == null ) {
- throw new IllegalArgumentException("External required interface must be specified");
+
+ if (externalRequired == null) {
+ throw new IllegalArgumentException(
+ "External required interface must be specified");
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public boolean isViolated(Edge aEdge) {
if (aEdge.getFrom() instanceof RequiredInterfaceNode
&& aEdge.getTo() instanceof ExternalRequiredInterfaceNode) {
return isViolated((RequiredInterfaceNode) aEdge.getFrom(),
- (ExternalRequiredInterfaceNode) aEdge.getTo());
+ (ExternalRequiredInterfaceNode) aEdge.getTo());
}
+
return false;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aFrom DOCUMENT ME!
+ * @param aTo DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private boolean isViolated(RequiredInterfaceNode aFrom,
- ExternalRequiredInterfaceNode aTo) {
- if ( !aFrom.getComponent().getName().equals(client)) {
+ ExternalRequiredInterfaceNode aTo) {
+ if (!aFrom.getComponent().getName().equals(client)) {
return false; // wrong component.
}
- if ( !(required == null || aFrom.getRequired().getName().equals(required))) {
+
+ if (!((required == null)
+ || aFrom.getRequired().getName().equals(required))) {
return false; // wrong interface
}
- if ( !aTo.getRequired().getName().equals(externalRequired)) {
+
+ if (!aTo.getRequired().getName().equals(externalRequired)) {
return true; // wrong externally required interface.
}
-
- return false;
+
+ return false;
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
+
/**
- * Filter used to explicitly connect required and provided interfaces within a
- * container.
- *
+ * Filter used to explicitly connect required and provided interfaces
+ * within a container.
+ *
* @author Erik Brakkee
- *
*/
public class ConnectRequiredProvidedEdgeFilter implements EdgeFilter {
-
+ /**
+ * DOCUMENT ME!
+ */
private String client;
+
+ /**
+ * DOCUMENT ME!
+ */
private String required;
+
+ /**
+ * DOCUMENT ME!
+ */
private String server;
+
+ /**
+ * DOCUMENT ME!
+ */
private String provided;
+ /**
+ * Creates a new ConnectRequiredProvidedEdgeFilter object.
+ *
+ * @param aClient DOCUMENT ME!
+ * @param aRequired DOCUMENT ME!
+ * @param aServer DOCUMENT ME!
+ * @param aProvided DOCUMENT ME!
+ */
public ConnectRequiredProvidedEdgeFilter(String aClient, String aRequired,
- String aServer, String aProvided) {
- client = aClient;
- required = aRequired;
- server = aServer;
- provided = aProvided;
- if ( client == null ) {
- throw new IllegalArgumentException("Client component must be specified");
+ String aServer, String aProvided) {
+ client = aClient;
+ required = aRequired;
+ server = aServer;
+ provided = aProvided;
+
+ if (client == null) {
+ throw new IllegalArgumentException(
+ "Client component must be specified");
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public boolean isViolated(Edge aEdge) {
if (aEdge.getFrom() instanceof RequiredInterfaceNode
&& aEdge.getTo() instanceof ProvidedInterfaceNode) {
return isViolated((RequiredInterfaceNode) aEdge.getFrom(),
- (ProvidedInterfaceNode) aEdge.getTo());
+ (ProvidedInterfaceNode) aEdge.getTo());
}
+
return false;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aFrom DOCUMENT ME!
+ * @param aTo DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private boolean isViolated(RequiredInterfaceNode aFrom,
- ProvidedInterfaceNode aTo) {
+ ProvidedInterfaceNode aTo) {
if (client.equals(aFrom.getComponent().getName())
- && (required == null || required.equals(aFrom.getRequired()
- .getName()))) {
+ && ((required == null)
+ || required.equals(aFrom.getRequired().getName()))) {
// From part matches.
- if ( server == null ) {
+ if (server == null) {
return true; // all connections are eliminated
}
+
if (server.equals(aTo.getComponent().getName())
- && (provided == null || provided.equals(aTo.getProvided()
- .getName()))) {
+ && ((provided == null)
+ || provided.equals(aTo.getProvided().getName()))) {
// to part matches also
return false;
- }
- else {
+ } else {
// From matches and to doesn't so edgefilter is violated.
- return true;
+ return true;
}
} else {
// From part does not match, restriction does not apply.
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
import org.wamblee.system.core.Component;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.graph.Node;
+
/**
- * Represents an external provided interface of a container.
- * @author Erik Brakkee
+ * Represents an external provided interface of a container.
*
+ * @author Erik Brakkee
*/
public class ExternalProvidedInterfaceNode implements Node {
+ /**
+ * DOCUMENT ME!
+ */
+ private Component component;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private ProvidedInterface provided;
- private Component component;
- private ProvidedInterface provided;
-
- public ExternalProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) {
- component = aComponent;
- provided = aProvided;
+ /**
+ * Creates a new ExternalProvidedInterfaceNode object.
+ *
+ * @param aComponent DOCUMENT ME!
+ * @param aProvided DOCUMENT ME!
+ */
+ public ExternalProvidedInterfaceNode(Component aComponent,
+ ProvidedInterface aProvided) {
+ component = aComponent;
+ provided = aProvided;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String getName() {
- return provided.getName();
+ return provided.getName();
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Component getComponent() {
return component;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public ProvidedInterface getProvided() {
return provided;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
- return component.getQualifiedName() + ":" + provided;
+ return component.getQualifiedName() + ":" + provided;
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
import org.wamblee.system.core.Component;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.graph.Node;
+
/**
- * Represents an externally required interface of a container.
- * @author Erik Brakkee
+ * Represents an externally required interface of a container.
*
+ * @author Erik Brakkee
*/
public class ExternalRequiredInterfaceNode implements Node {
-
+ /**
+ * DOCUMENT ME!
+ */
private Component component;
- private RequiredInterface required;
- public ExternalRequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) {
- component = aComponent;
- required = aRequired;
+ /**
+ * DOCUMENT ME!
+ */
+ private RequiredInterface required;
+
+ /**
+ * Creates a new ExternalRequiredInterfaceNode object.
+ *
+ * @param aComponent DOCUMENT ME!
+ * @param aRequired DOCUMENT ME!
+ */
+ public ExternalRequiredInterfaceNode(Component aComponent,
+ RequiredInterface aRequired) {
+ component = aComponent;
+ required = aRequired;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String getName() {
- return required.getName();
+ return required.getName();
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Component getComponent() {
return component;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public RequiredInterface getRequired() {
return required;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
return component.getQualifiedName() + ":" + required;
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.graph.Node;
import org.wamblee.system.graph.Visitor;
+
/**
* Visitor that creates links between required and provided interfaces as
- * described by the edges in the graph.
- *
- * Specically it links together (1) required and provided interfaces of internal component
- * of a container and (2) the providers of externally required interfaces and internal required
- * interfaces.
- *
+ * described by the edges in the graph. Specically it links together (1)
+ * required and provided interfaces of internal component of a container and
+ * (2) the providers of externally required interfaces and internal required
+ * interfaces.
+ *
* @author Erik Brakkee
- *
*/
public class LinkVisitor implements Visitor {
-
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aEdge DOCUMENT ME!
+ */
@Override
public void visitEdge(Edge aEdge) {
Node from = aEdge.getFrom();
- Node to = aEdge.getTo();
+ Node to = aEdge.getTo();
+
if (from instanceof RequiredInterfaceNode) {
RequiredInterfaceNode required = (RequiredInterfaceNode) from;
- if (to instanceof ProvidedInterfaceNode) {
+ if (to instanceof ProvidedInterfaceNode) {
ProvidedInterfaceNode provided = (ProvidedInterfaceNode) to;
required.getRequired().setProvider(provided.getProvided());
-
} else if (to instanceof ExternalRequiredInterfaceNode) {
ExternalRequiredInterfaceNode external = (ExternalRequiredInterfaceNode) to;
- ProvidedInterface provider = external.getRequired()
- .getProvider();
- if (provider == null && !required.getRequired().isOptional()) {
+ ProvidedInterface provider = external.getRequired()
+ .getProvider();
+
+ if ((provider == null) && !required.getRequired().isOptional()) {
throw new SystemAssemblyException("Mandatory interface '"
- + from + "' is not provided.");
+ + from + "' is not provided.");
}
- if ( provider != null ) {
+
+ if (provider != null) {
required.getRequired().setProvider(provider);
}
}
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aNode DOCUMENT ME!
+ */
@Override
public void visitNode(Node aNode) {
// Empty.
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
import org.wamblee.system.core.Component;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.graph.Node;
+
/**
- * Provided interface node.
+ * Provided interface node.
+ *
* @author Erik Brakkee
*/
public class ProvidedInterfaceNode implements Node {
-
- private Component component;
+ /**
+ * DOCUMENT ME!
+ */
+ private Component component;
+
+ /**
+ * DOCUMENT ME!
+ */
private ProvidedInterface provided;
-
- public ProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) {
- component = aComponent;
- provided = aProvided;
+
+ /**
+ * Creates a new ProvidedInterfaceNode object.
+ *
+ * @param aComponent DOCUMENT ME!
+ * @param aProvided DOCUMENT ME!
+ */
+ public ProvidedInterfaceNode(Component aComponent,
+ ProvidedInterface aProvided) {
+ component = aComponent;
+ provided = aProvided;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String getName() {
- return component.getQualifiedName() + ":" + provided.getName();
+ return component.getQualifiedName() + ":" + provided.getName();
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public ProvidedInterface getProvided() {
return provided;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Component getComponent() {
return component;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
- return component.getQualifiedName() + ":" + provided;
+ return component.getQualifiedName() + ":" + provided;
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
import org.wamblee.system.core.Component;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.graph.Node;
+
/**
- * Required interface node.
- * @author Erik Brakkee
+ * Required interface node.
*
+ * @author Erik Brakkee
*/
public class RequiredInterfaceNode implements Node {
-
- private Component component;
- private RequiredInterface required;
-
- public RequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) {
- component = aComponent;
- required = aRequired;
+ /**
+ * DOCUMENT ME!
+ */
+ private Component component;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private RequiredInterface required;
+
+ /**
+ * Creates a new RequiredInterfaceNode object.
+ *
+ * @param aComponent DOCUMENT ME!
+ * @param aRequired DOCUMENT ME!
+ */
+ public RequiredInterfaceNode(Component aComponent,
+ RequiredInterface aRequired) {
+ component = aComponent;
+ required = aRequired;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String getName() {
return component.getQualifiedName() + ":" + required.getName();
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public RequiredInterface getRequired() {
return required;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Component getComponent() {
return component;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public String toString() {
- return component.getQualifiedName() + ":" + required;
+ return component.getQualifiedName() + ":" + required;
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.graph.component;
-import java.util.ArrayList;
-import java.util.List;
-
import org.wamblee.system.graph.DefaultEdge;
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFactory;
import org.wamblee.system.graph.Node;
+import java.util.ArrayList;
+import java.util.List;
+
+
/**
* Factory that creates edges between required and provided interfaces.
- * Speciflcally it creates:
- * <ul>
- * <li> Edges between provided and required interfaces of a container. </li>
- * <li> Edges between required and externally required interfaces </li>
- * <li> Edges between externally provided and provided interfaces.
- * </ul>
- *
+ * Speciflcally it creates:
+ * <ul>
+ * <li>Edges between provided and required interfaces of a
+ * container.</li>
+ * <li>Edges between required and externally required interfaces</li>
+ * <li>Edges between externally provided and provided interfaces.
+ * </ul>
+ *
* @author Erik Brakkee
- *
*/
public class RequiredProvidedEdgeFactory implements EdgeFactory {
-
+ /**
+ * Creates a new RequiredProvidedEdgeFactory object.
+ */
public RequiredProvidedEdgeFactory() {
// Empty.
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aFrom DOCUMENT ME!
+ * @param aTo DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public List<Edge> create(Node aFrom, Node aTo) {
List<Edge> result = new ArrayList<Edge>();
+
if (aFrom instanceof RequiredInterfaceNode) {
RequiredInterfaceNode required = (RequiredInterfaceNode) aFrom;
+
if (aTo instanceof ProvidedInterfaceNode) {
-
ProvidedInterfaceNode provided = (ProvidedInterfaceNode) aTo;
- if (required.getRequired()
- .implementedBy(provided.getProvided())) {
+
+ if (required.getRequired().implementedBy(provided.getProvided())) {
result.add(new DefaultEdge(required, provided));
}
} else if (aTo instanceof ExternalRequiredInterfaceNode) {
ExternalRequiredInterfaceNode external = (ExternalRequiredInterfaceNode) aTo;
- if ( external.getRequired().covers(required.getRequired())) {
+
+ if (external.getRequired().covers(required.getRequired())) {
result.add(new DefaultEdge(required, external));
}
}
- } else if ( aFrom instanceof ProvidedInterfaceNode) {
- ProvidedInterfaceNode provided = (ProvidedInterfaceNode)aFrom;
- if ( aTo instanceof ExternalProvidedInterfaceNode) {
- ExternalProvidedInterfaceNode external = (ExternalProvidedInterfaceNode)aTo;
- if (provided.getProvided().covers(external.getProvided())) {
+ } else if (aFrom instanceof ProvidedInterfaceNode) {
+ ProvidedInterfaceNode provided = (ProvidedInterfaceNode) aFrom;
+
+ if (aTo instanceof ExternalProvidedInterfaceNode) {
+ ExternalProvidedInterfaceNode external = (ExternalProvidedInterfaceNode) aTo;
+
+ if (provided.getProvided().covers(external.getProvided())) {
result.add(new DefaultEdge(external, provided));
}
}
}
+
return result;
}
-
}
import org.wamblee.system.core.Component;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
-
* <li> {@link EdgeFactory}: For extending the graph with new edges </li>
* </ul>
*/
-package org.wamblee.system.graph;
\ No newline at end of file
+package org.wamblee.system.graph;
+
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+import junit.framework.TestCase;
+
import org.wamblee.system.core.DefaultScope;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.Scope;
+
import org.wamblee.test.EventTracker;
-import junit.framework.TestCase;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class AdapterTestCase extends TestCase {
-
- protected Scope scope;
- static EventTracker<String> EVENT_TRACKER;
+ /**
+ * DOCUMENT ME!
+ */
+ static EventTracker<String> EVENT_TRACKER;
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- EVENT_TRACKER = new EventTracker<String>();
- scope = new DefaultScope(new ProvidedInterface[0]);
- }
+ /**
+ * DOCUMENT ME!
+ */
+ protected Scope scope;
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ EVENT_TRACKER = new EventTracker<String>();
+ scope = new DefaultScope(new ProvidedInterface[0]);
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
import org.wamblee.system.container.Container;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+
import org.wamblee.test.AssertionUtils;
-public class ClassAdapterTest extends AdapterTestCase {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ClassAdapterTest extends AdapterTestCase {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testSimpleConstructorInjection() {
+ ClassConfiguration x1Config = new ClassConfiguration(X1.class);
+ x1Config.getObjectConfig().getSetterConfig().initAllSetters();
+ x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
- public void testSimpleConstructorInjection() {
- ClassConfiguration x1Config = new ClassConfiguration(X1.class);
- x1Config.getObjectConfig().getSetterConfig().initAllSetters();
- x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
ClassConfiguration x4Config = new ClassConfiguration(X4.class);
x4Config.getObjectConfig().getSetterConfig().initAllSetters();
-
+
ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
-
- Container container = new Container("top", new Component[] {
- x1Adapter, x4Adapter
- }, new ProvidedInterface[0], new RequiredInterface[0]);
-
- Scope scope = container.start();
+
+ Container container = new Container("top",
+ new Component[] { x1Adapter, x4Adapter },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+
+ Scope scope = container.start();
AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" },
- EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
-
+ EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+
Object obj1 = scope.getRuntime(x1Adapter);
- assertTrue(obj1 instanceof X1);
+ assertTrue(obj1 instanceof X1);
+
Object obj4 = scope.getRuntime(x4Adapter);
assertTrue(obj4 instanceof X4);
-
+
X1 x1 = (X1) obj1;
X4 x4 = (X4) obj4;
-
+
assertSame(x1, x4.getX1());
- }
-
- public void testConstructorAndSetterInjection() {
- ClassConfiguration x1Config = new ClassConfiguration(X1.class);
- x1Config.getObjectConfig().getSetterConfig().initAllSetters();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testConstructorAndSetterInjection() {
+ ClassConfiguration x1Config = new ClassConfiguration(X1.class);
+ x1Config.getObjectConfig().getSetterConfig().initAllSetters();
x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
+
ClassConfiguration x4Config = new ClassConfiguration(X4.class);
x4Config.getObjectConfig().getSetterConfig().initAllSetters();
+
ClassConfiguration x8Config = new ClassConfiguration(X8.class);
x8Config.getObjectConfig().getSetterConfig().initAllSetters();
-
+
ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
ClassAdapter x8Adapter = new ClassAdapter("x8", x8Config);
-
- Container container = new Container("top", new Component[] {
- x1Adapter, x4Adapter, x8Adapter
- }, new ProvidedInterface[0], new RequiredInterface[0]);
-
- Scope scope = container.start();
- AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)", "x8(x1)", "x8.setX4(x4)" },
- EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
-
+
+ Container container = new Container("top",
+ new Component[] { x1Adapter, x4Adapter, x8Adapter },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+
+ Scope scope = container.start();
+ AssertionUtils.assertEquals(new String[] {
+ "x1(hello)", "x4(x1)", "x8(x1)", "x8.setX4(x4)"
+ }, EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+
Object obj1 = scope.getRuntime(x1Adapter);
- assertTrue(obj1 instanceof X1);
+ assertTrue(obj1 instanceof X1);
+
Object obj4 = scope.getRuntime(x4Adapter);
assertTrue(obj4 instanceof X4);
- Object obj8 = scope.getRuntime(x8Adapter);
-
- X1 x1 = (X1) obj1;
- X4 x4 = (X4) obj4;
- X8 x8 = (X8) obj8;
-
+
+ Object obj8 = scope.getRuntime(x8Adapter);
+
+ X1 x1 = (X1) obj1;
+ X4 x4 = (X4) obj4;
+ X8 x8 = (X8) obj8;
+
assertSame(x4, x8.getX4());
assertSame(x1, x8.getX1());
- }
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.adapters;
-import java.util.Collections;
-import java.util.List;
-
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.RequiredInterfaceComparator;
+
import org.wamblee.test.AssertionUtils;
-public class ClassConfigurationTest extends AdapterTestCase {
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ClassConfigurationTest extends AdapterTestCase {
+ /**
+ * DOCUMENT ME!
+ */
public void testConstructorConfig() {
- ClassConfiguration classConfig = new ClassConfiguration(X1.class);
+ ClassConfiguration classConfig = new ClassConfiguration(X1.class);
+
+ ConstructorConfiguration config = classConfig.getConstructorConfig()
+ .greedy();
- ConstructorConfiguration config = classConfig.getConstructorConfig()
- .greedy();
-
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
String.class);
- List<RequiredInterface> required = classConfig.getRequiredInterfaces();
+ List<RequiredInterface> required = classConfig.getRequiredInterfaces();
assertEquals(1, required.size());
assertFalse(required.get(0).isOptional());
classConfig.create(scope);
AssertionUtils.assertEquals(new String[] { "x1(hello)" },
- AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
- .toArray());
+ AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
}
+ /**
+ * DOCUMENT ME!
+ */
public void testConstructorConfigWithSetters() {
ClassConfiguration classConfig = new ClassConfiguration(X7.class);
classConfig.getConstructorConfig().select(Boolean.class);
- classConfig.getObjectConfig().getSetterConfig().initAllSetters().values("setPort").setValue(0, 10);
-
- ProvidedInterface providedBoolean = new DefaultProvidedInterface("boolean",
+ classConfig.getObjectConfig().getSetterConfig().initAllSetters()
+ .values("setPort").setValue(0, 10);
+
+ ProvidedInterface providedBoolean = new DefaultProvidedInterface("boolean",
Boolean.class);
- ProvidedInterface providedHost = new DefaultProvidedInterface("host", String.class);
- List<RequiredInterface> required = classConfig.getRequiredInterfaces();
+ ProvidedInterface providedHost = new DefaultProvidedInterface("host",
+ String.class);
+ List<RequiredInterface> required = classConfig
+ .getRequiredInterfaces();
Collections.sort(required, new RequiredInterfaceComparator());
assertEquals(2, required.size());
scope.publishInterface(providedBoolean, true);
scope.publishInterface(providedHost, "host.name.org");
-
+
Object obj = classConfig.create(scope);
assertTrue(obj instanceof X7);
- X7 x7 = (X7)obj;
+
+ X7 x7 = (X7) obj;
assertNotNull(x7.getBoolean());
assertTrue(x7.getBoolean());
assertNull(x7.getHost());
assertNull(x7.getPort());
classConfig.inject(scope, obj);
-
+
assertEquals("host.name.org", x7.getHost());
assertEquals(10, x7.getPort().intValue());
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.adapters;
-import java.util.List;
-
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.SystemAssemblyException;
+
import org.wamblee.test.AssertionUtils;
-public class ConstructorConfigurationTest extends AdapterTestCase {
+import java.util.List;
+
- public void testGreedyUnique() {
- ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
- .greedy();
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
- List<RequiredInterface> required = config.getRequiredInterfaces();
-
- assertEquals(1, required.size());
- assertFalse(required.get(0).isOptional());
-
- required.get(0).setProvider(provided);
-
- scope.publishInterface(provided, "hello");
- config.create(scope);
-
- AssertionUtils.assertEquals(new String[] { "x1(hello)" }, AdapterTestCase.EVENT_TRACKER
- .getEvents(Thread.currentThread()).toArray());
- }
-
- public void testGreedyNonUnique() {
- try {
- ConstructorConfiguration config = new ConstructorConfiguration(
- X2.class).greedy();
- } catch (SystemAssemblyException e) {
- // e.printStackTrace();
- return;
- }
- fail();
- }
-
- public void testSpecificConstructor() {
- ConstructorConfiguration config = new ConstructorConfiguration(X2.class)
- .select(String.class);
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
- List<RequiredInterface> required = config.getRequiredInterfaces();
-
- assertEquals(1, required.size());
- required.get(0).setProvider(provided);
-
- scope.publishInterface(provided, "hello");
- config.create(scope);
-
- AssertionUtils.assertEquals(new String[] { "x2(hello)" }, AdapterTestCase.EVENT_TRACKER
- .getEvents(Thread.currentThread()).toArray());
- }
-
- public void testSetValue() {
- ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
- .greedy();
- config.getParameters().setValue(0, "bla");
-
- config.create(scope);
-
- AssertionUtils.assertEquals(new String[] { "x1(bla)" }, AdapterTestCase.EVENT_TRACKER
- .getEvents(Thread.currentThread()).toArray());
- }
-
- public void testOptionalValueProvided() {
- ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
- .greedy();
- config.getParameters().setOptional(0);
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
- List<RequiredInterface> required = config.getRequiredInterfaces();
-
- assertEquals(1, required.size());
- required.get(0).setProvider(provided);
-
- scope.publishInterface(provided, "hello");
- config.create(scope);
-
- AssertionUtils.assertEquals(new String[] { "x1(hello)" }, AdapterTestCase.EVENT_TRACKER
- .getEvents(Thread.currentThread()).toArray());
- }
-
- public void testOptionalValueMissing() {
- ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
- .greedy();
- config.getParameters().setOptional(0);
- assertTrue(config.getRequiredInterfaces().get(0).isOptional());
-
- config.create(scope);
-
- AssertionUtils.assertEquals(new String[] { "x1(null)" }, AdapterTestCase.EVENT_TRACKER
- .getEvents(Thread.currentThread()).toArray());
- }
-
- public void testIgnoredNonPublic() {
- ConstructorConfiguration config = new ConstructorConfiguration(X3.class)
- .greedy();
- List<RequiredInterface> required = config.getRequiredInterfaces();
- assertEquals(0, config.getParameters().getTypes().length);
- }
-
- public void testNonPublicConstructor() {
- ConstructorConfiguration config = new ConstructorConfiguration(X3.class)
- .setNonPublic(true).greedy();
- ProvidedInterface provided = new DefaultProvidedInterface("arg",
- String.class);
- List<RequiredInterface> required = config.getRequiredInterfaces();
-
- assertEquals(1, required.size());
- assertFalse(required.get(0).isOptional());
-
- required.get(0).setProvider(provided);
-
- scope.publishInterface(provided, "hello");
- config.create(scope);
-
- AssertionUtils.assertEquals(new String[] { "x3(hello)" }, AdapterTestCase.EVENT_TRACKER
- .getEvents(Thread.currentThread()).toArray());
- }
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ConstructorConfigurationTest extends AdapterTestCase {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testGreedyUnique() {
+ ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+ .greedy();
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+
+ assertEquals(1, required.size());
+ assertFalse(required.get(0).isOptional());
+
+ required.get(0).setProvider(provided);
+
+ scope.publishInterface(provided, "hello");
+ config.create(scope);
+
+ AssertionUtils.assertEquals(new String[] { "x1(hello)" },
+ AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testGreedyNonUnique() {
+ try {
+ ConstructorConfiguration config = new ConstructorConfiguration(X2.class)
+ .greedy();
+ } catch (SystemAssemblyException e) {
+ // e.printStackTrace();
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testSpecificConstructor() {
+ ConstructorConfiguration config = new ConstructorConfiguration(X2.class)
+ .select(String.class);
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+
+ assertEquals(1, required.size());
+ required.get(0).setProvider(provided);
+
+ scope.publishInterface(provided, "hello");
+ config.create(scope);
+
+ AssertionUtils.assertEquals(new String[] { "x2(hello)" },
+ AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testSetValue() {
+ ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+ .greedy();
+ config.getParameters().setValue(0, "bla");
+
+ config.create(scope);
+
+ AssertionUtils.assertEquals(new String[] { "x1(bla)" },
+ AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOptionalValueProvided() {
+ ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+ .greedy();
+ config.getParameters().setOptional(0);
+
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+
+ assertEquals(1, required.size());
+ required.get(0).setProvider(provided);
+
+ scope.publishInterface(provided, "hello");
+ config.create(scope);
+
+ AssertionUtils.assertEquals(new String[] { "x1(hello)" },
+ AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOptionalValueMissing() {
+ ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+ .greedy();
+ config.getParameters().setOptional(0);
+ assertTrue(config.getRequiredInterfaces().get(0).isOptional());
+
+ config.create(scope);
+
+ AssertionUtils.assertEquals(new String[] { "x1(null)" },
+ AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testIgnoredNonPublic() {
+ ConstructorConfiguration config = new ConstructorConfiguration(X3.class)
+ .greedy();
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ assertEquals(0, config.getParameters().getTypes().length);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNonPublicConstructor() {
+ ConstructorConfiguration config = new ConstructorConfiguration(X3.class).setNonPublic(true)
+ .greedy();
+ ProvidedInterface provided = new DefaultProvidedInterface("arg",
+ String.class);
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+
+ assertEquals(1, required.size());
+ assertFalse(required.get(0).isOptional());
+
+ required.get(0).setProvider(provided);
+
+ scope.publishInterface(provided, "hello");
+ config.create(scope);
+
+ AssertionUtils.assertEquals(new String[] { "x3(hello)" },
+ AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
+ .toArray());
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package org.wamblee.system.adapters;
import org.wamblee.system.core.Scope;
+
import org.wamblee.test.AssertionUtils;
-public class DefaultContainerTest extends AdapterTestCase {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class DefaultContainerTest extends AdapterTestCase {
+ /**
+ * DOCUMENT ME!
+ */
public void testConstructorInjection() {
ClassConfiguration x1Config = new ClassConfiguration(X1.class);
x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
x1Config.getObjectConfig().getSetterConfig().initAllSetters();
-
+
ClassConfiguration x4Config = new ClassConfiguration(X4.class);
x4Config.getObjectConfig().getSetterConfig().initAllSetters();
- DefaultContainer container = new DefaultContainer("top").addComponent(
- "x1", x1Config).addComponent("x4", x4Config);
+ DefaultContainer container = new DefaultContainer("top").addComponent("x1",
+ x1Config).addComponent("x4", x4Config);
- Scope scope = container.start();
+ Scope scope = container.start();
AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" },
- EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+ EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
Object obj = scope.getRuntime("x1");
assertTrue(obj instanceof X1);
obj = scope.getRuntime("x4");
assertTrue(obj instanceof X4);
}
-
+
+ /**
+ * DOCUMENT ME!
+ */
public void testConstructorInjectionAndSetterInjection() {
ClassConfiguration x1Config = new ClassConfiguration(X1.class);
x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
x1Config.getObjectConfig().getSetterConfig().initAllSetters();
-
- X8 x8 = new X8(null);
+
+ X8 x8 = new X8(null);
EVENT_TRACKER.clear();
ClassConfiguration x4Config = new ClassConfiguration(X4.class);
x4Config.getObjectConfig().getSetterConfig().initAllSetters();
-
+
ObjectConfiguration x8Config = new ObjectConfiguration(X8.class);
x8Config.getSetterConfig().initAllSetters();
-
- DefaultContainer container = new DefaultContainer("top").addComponent(
- "x1", x1Config).addComponent("x4", x4Config).addComponent("x8", x8, x8Config);
- Scope scope = container.start();
- AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)",
- "x8.setX4(x4)"},
- EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+ DefaultContainer container = new DefaultContainer("top").addComponent("x1",
+ x1Config).addComponent("x4", x4Config)
+ .addComponent("x8", x8, x8Config);
+
+ Scope scope = container.start();
+ AssertionUtils.assertEquals(new String[] {
+ "x1(hello)", "x4(x1)", "x8.setX4(x4)"
+ }, EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
Object obj1 = scope.getRuntime("x1");
assertTrue(obj1 instanceof X1);
+
Object obj4 = scope.getRuntime("x4");
assertTrue(obj4 instanceof X4);
+
Object obj8 = scope.getRuntime("x8");
assertSame(x8, obj8);
assertSame(obj4, x8.getX4());
}
-
- public void testWrongObjectType() {
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testWrongObjectType() {
final DefaultContainer container = new DefaultContainer("top");
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.addComponent("x", "y", new ObjectConfiguration(Integer.class));
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ container.addComponent("x", "y",
+ new ObjectConfiguration(Integer.class));
+ }
+ }, IllegalArgumentException.class);
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
-import java.util.Collections;
-import java.util.List;
-
import org.wamblee.system.container.Container;
import org.wamblee.system.core.Component;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.RequiredInterfaceComparator;
import org.wamblee.system.core.Scope;
+
import org.wamblee.test.AssertionUtils;
+import java.util.Collections;
+import java.util.List;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class ObjectAdapterTest extends AdapterTestCase {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testSetterInjection() {
+ ClassConfiguration x1Config = new ClassConfiguration(X1.class);
+ x1Config.getObjectConfig().getSetterConfig().initAllSetters();
+ x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
- public void testSetterInjection() {
-
- ClassConfiguration x1Config = new ClassConfiguration(X1.class);
- x1Config.getObjectConfig().getSetterConfig().initAllSetters();
- x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
-
ClassConfiguration x4Config = new ClassConfiguration(X4.class);
x4Config.getObjectConfig().getSetterConfig().initAllSetters();
+
ObjectConfiguration x8Config = new ObjectConfiguration(X8.class);
x8Config.getSetterConfig().initAllSetters();
-
- X1 x1 = new X1();
- X8 x8 = new X8(x1);
-
- ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
- ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
+
+ X1 x1 = new X1();
+ X8 x8 = new X8(x1);
+
+ ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
+ ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
ObjectAdapter x8Adapter = new ObjectAdapter("x8", x8, x8Config);
-
- Container container = new Container("top", new Component[] {
- x1Adapter, x4Adapter, x8Adapter
- }, new ProvidedInterface[0], new RequiredInterface[0]);
-
+
+ Container container = new Container("top",
+ new Component[] { x1Adapter, x4Adapter, x8Adapter },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+
EVENT_TRACKER.clear();
+
Scope scope = container.start();
- AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)", "x8.setX4(x4)" },
- EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
-
+ AssertionUtils.assertEquals(new String[] {
+ "x1(hello)", "x4(x1)", "x8.setX4(x4)"
+ }, EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+
Object obj1 = scope.getRuntime(x1Adapter);
- assertTrue(obj1 instanceof X1);
+ assertTrue(obj1 instanceof X1);
+
Object obj4 = scope.getRuntime(x4Adapter);
assertTrue(obj4 instanceof X4);
+
Object obj8 = scope.getRuntime(x8Adapter);
assertSame(x8, obj8);
-
+
X4 x4 = (X4) obj4;
-
-
+
assertSame(x4, x8.getX4());
assertSame(x1, x8.getX1());
- }
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.adapters;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.RequiredInterfaceComparator;
+
+import org.wamblee.test.AssertionUtils;
+
import java.lang.reflect.Method;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.sql.DataSource;
-import org.wamblee.system.core.DefaultProvidedInterface;
-import org.wamblee.system.core.ProvidedInterface;
-import org.wamblee.system.core.RequiredInterface;
-import org.wamblee.system.core.RequiredInterfaceComparator;
-import org.wamblee.test.AssertionUtils;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class SetterConfigurationTest extends AdapterTestCase {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOneSetter() {
+ SetterConfiguration config = new SetterConfiguration(X5.class);
+ config.initAllSetters();
+
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ assertEquals(1, required.size());
+ assertEquals("setValue.0", required.get(0).getName());
+
+ ProvidedInterface provided = new DefaultProvidedInterface("janse",
+ String.class);
+ required.get(0).setProvider(provided);
+ scope.publishInterface(provided, "hello");
+
+ X5 obj = new X5();
+ assertNull(obj.getValue());
+ config.inject(scope, obj);
+ assertEquals("hello", obj.getValue());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testPrivateSetter() {
+ SetterConfiguration config = new SetterConfiguration(X5.class);
+ config.setNonPublic(true);
+ config.initAllSetters();
+
+ List<RequiredInterface> required = new ArrayList<RequiredInterface>(config
+ .getRequiredInterfaces());
+ Collections.sort(required,
+ new Comparator<RequiredInterface>() {
+ @Override
+ public int compare(RequiredInterface aO1, RequiredInterface aO2) {
+ return aO1.getName().compareTo(aO2.getName());
+ }
+ });
+ assertEquals(2, required.size());
+ assertEquals("setValue.0", required.get(0).getName());
+ assertEquals("setXyz.0", required.get(1).getName());
+
+ ProvidedInterface providedString = new DefaultProvidedInterface("janse",
+ String.class);
+ assertTrue(required.get(0).implementedBy(providedString));
+ required.get(0).setProvider(providedString);
+ scope.publishInterface(providedString, "hello");
+
+ ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
+ Integer.class);
+ assertTrue(required.get(1).implementedBy(providedInt));
+ required.get(1).setProvider(providedInt);
+ scope.publishInterface(providedInt, 100);
+
+ X5 obj = new X5();
+ assertNull(obj.getValue());
+ assertNull(obj.getXyz());
+ config.inject(scope, obj);
+ assertEquals("hello", obj.getValue());
+ assertEquals(100, obj.getXyz().intValue());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testInheritance() {
+ SetterConfiguration config = new SetterConfiguration(X9.class);
+ config.setNonPublic(true);
+ config.initAllSetters();
+
+ List<RequiredInterface> required = new ArrayList<RequiredInterface>(config
+ .getRequiredInterfaces());
+ Collections.sort(required,
+ new Comparator<RequiredInterface>() {
+ @Override
+ public int compare(RequiredInterface aO1, RequiredInterface aO2) {
+ return aO1.getName().compareTo(aO2.getName());
+ }
+ });
+ assertEquals(3, required.size());
+ assertEquals("setFlag.0", required.get(0).getName());
+ assertEquals("setValue.0", required.get(1).getName());
+ assertEquals("setXyz.0", required.get(2).getName());
+
+ ProvidedInterface providedBoolean = new DefaultProvidedInterface("janse",
+ Boolean.class);
+ assertTrue(required.get(0).implementedBy(providedBoolean));
+ required.get(0).setProvider(providedBoolean);
+ scope.publishInterface(providedBoolean, true);
+
+ ProvidedInterface providedString = new DefaultProvidedInterface("janse",
+ String.class);
+ assertTrue(required.get(1).implementedBy(providedString));
+ required.get(1).setProvider(providedString);
+ scope.publishInterface(providedString, "hello");
+
+ ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
+ Integer.class);
+ assertTrue(required.get(2).implementedBy(providedInt));
+ required.get(2).setProvider(providedInt);
+ scope.publishInterface(providedInt, 100);
+
+ X9 obj = new X9();
+ assertNull(obj.getValue());
+ assertNull(obj.getXyz());
+ assertFalse(obj.isFlag());
+ config.inject(scope, obj);
+ assertEquals("hello", obj.getValue());
+ assertEquals(100, obj.getXyz().intValue());
+ assertTrue(obj.isFlag());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testMultipleSetters() {
+ SetterConfiguration config = new SetterConfiguration(X6.class)
+ .initAllSetters();
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ Collections.sort(required, new RequiredInterfaceComparator());
+ assertEquals(2, required.size());
+ assertEquals("setHost.0", required.get(0).getName());
+ assertEquals("setPort.0", required.get(1).getName());
+
+ ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+ String.class);
+ required.get(0).setProvider(provided0);
+ scope.publishInterface(provided0, "hello");
+
+ ProvidedInterface provided1 = new DefaultProvidedInterface("port",
+ Integer.class);
+ required.get(1).setProvider(provided1);
+ scope.publishInterface(provided1, 10);
+
+ X6 obj = new X6();
+ assertNull(obj.getHost());
+ assertNull(obj.getPort());
+
+ config.inject(scope, obj);
+ assertEquals("hello", obj.getHost());
+ assertEquals(10, obj.getPort().intValue());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testInvokeWrongType() {
+ final SetterConfiguration config = new SetterConfiguration(X5.class)
+ .initAllSetters();
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ assertEquals(1, required.size());
+ assertEquals("setValue.0", required.get(0).getName());
+
+ ProvidedInterface provided = new DefaultProvidedInterface("janse",
+ String.class);
+ required.get(0).setProvider(provided);
+ scope.publishInterface(provided, "hello");
+
+ final X6 obj = new X6();
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ config.inject(scope, obj);
+ }
+ }, IllegalArgumentException.class);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testSetExplicitValue() {
+ SetterConfiguration config = new SetterConfiguration(X5.class)
+ .initAllSetters();
+ config.values("setValue").setValue(0, "bladibla");
+
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ assertEquals(0, required.size());
+
+ X5 obj = new X5();
+ assertNull(obj.getValue());
+ config.inject(scope, obj);
+ assertEquals("bladibla", obj.getValue());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testClear() {
+ SetterConfiguration config = new SetterConfiguration(X6.class);
+ config.clear();
+
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ Collections.sort(required, new RequiredInterfaceComparator());
+ assertEquals(0, required.size());
+
+ X6 obj = new X6();
+ assertNull(obj.getHost());
+ assertNull(obj.getPort());
+
+ config.inject(scope, obj);
+
+ assertNull(obj.getHost());
+ assertNull(obj.getPort());
+ }
- public void testOneSetter() {
- SetterConfiguration config = new SetterConfiguration(X5.class);
- config.initAllSetters();
- List<RequiredInterface> required = config.getRequiredInterfaces();
- assertEquals(1, required.size());
- assertEquals("setValue.0", required.get(0).getName());
-
- ProvidedInterface provided = new DefaultProvidedInterface("janse",
- String.class);
- required.get(0).setProvider(provided);
- scope.publishInterface(provided, "hello");
-
- X5 obj = new X5();
- assertNull(obj.getValue());
- config.inject(scope, obj);
- assertEquals("hello", obj.getValue());
- }
-
- public void testPrivateSetter() {
- SetterConfiguration config = new SetterConfiguration(X5.class);
- config.setNonPublic(true);
- config.initAllSetters();
- List<RequiredInterface> required = new ArrayList<RequiredInterface>(
- config.getRequiredInterfaces());
- Collections.sort(required, new Comparator<RequiredInterface>() {
- @Override
- public int compare(RequiredInterface aO1, RequiredInterface aO2) {
- return aO1.getName().compareTo(aO2.getName());
- }
- });
- assertEquals(2, required.size());
- assertEquals("setValue.0", required.get(0).getName());
- assertEquals("setXyz.0", required.get(1).getName());
-
- ProvidedInterface providedString = new DefaultProvidedInterface(
- "janse", String.class);
- assertTrue(required.get(0).implementedBy(providedString));
- required.get(0).setProvider(providedString);
- scope.publishInterface(providedString, "hello");
-
- ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
- Integer.class);
- assertTrue(required.get(1).implementedBy(providedInt));
- required.get(1).setProvider(providedInt);
- scope.publishInterface(providedInt, 100);
-
- X5 obj = new X5();
- assertNull(obj.getValue());
- assertNull(obj.getXyz());
- config.inject(scope, obj);
- assertEquals("hello", obj.getValue());
- assertEquals(100, obj.getXyz().intValue());
- }
-
- public void testInheritance() {
- SetterConfiguration config = new SetterConfiguration(X9.class);
- config.setNonPublic(true);
- config.initAllSetters();
- List<RequiredInterface> required = new ArrayList<RequiredInterface>(
- config.getRequiredInterfaces());
- Collections.sort(required, new Comparator<RequiredInterface>() {
- @Override
- public int compare(RequiredInterface aO1, RequiredInterface aO2) {
- return aO1.getName().compareTo(aO2.getName());
- }
- });
- assertEquals(3, required.size());
- assertEquals("setFlag.0", required.get(0).getName());
- assertEquals("setValue.0", required.get(1).getName());
- assertEquals("setXyz.0", required.get(2).getName());
-
- ProvidedInterface providedBoolean = new DefaultProvidedInterface(
- "janse", Boolean.class);
- assertTrue(required.get(0).implementedBy(providedBoolean));
- required.get(0).setProvider(providedBoolean);
- scope.publishInterface(providedBoolean, true);
-
- ProvidedInterface providedString = new DefaultProvidedInterface(
- "janse", String.class);
- assertTrue(required.get(1).implementedBy(providedString));
- required.get(1).setProvider(providedString);
- scope.publishInterface(providedString, "hello");
-
- ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
- Integer.class);
- assertTrue(required.get(2).implementedBy(providedInt));
- required.get(2).setProvider(providedInt);
- scope.publishInterface(providedInt, 100);
-
- X9 obj = new X9();
- assertNull(obj.getValue());
- assertNull(obj.getXyz());
- assertFalse(obj.isFlag());
- config.inject(scope, obj);
- assertEquals("hello", obj.getValue());
- assertEquals(100, obj.getXyz().intValue());
- assertTrue(obj.isFlag());
- }
-
- public void testMultipleSetters() {
- SetterConfiguration config = new SetterConfiguration(X6.class).initAllSetters();
- List<RequiredInterface> required = config.getRequiredInterfaces();
- Collections.sort(required, new RequiredInterfaceComparator());
- assertEquals(2, required.size());
- assertEquals("setHost.0", required.get(0).getName());
- assertEquals("setPort.0", required.get(1).getName());
-
- ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
- required.get(0).setProvider(provided0);
- scope.publishInterface(provided0, "hello");
-
- ProvidedInterface provided1 = new DefaultProvidedInterface("port",
- Integer.class);
- required.get(1).setProvider(provided1);
- scope.publishInterface(provided1, 10);
-
- X6 obj = new X6();
- assertNull(obj.getHost());
- assertNull(obj.getPort());
-
- config.inject(scope, obj);
- assertEquals("hello", obj.getHost());
- assertEquals(10, obj.getPort().intValue());
- }
-
- public void testInvokeWrongType() {
- final SetterConfiguration config = new SetterConfiguration(X5.class).initAllSetters();
- List<RequiredInterface> required = config.getRequiredInterfaces();
- assertEquals(1, required.size());
- assertEquals("setValue.0", required.get(0).getName());
-
- ProvidedInterface provided = new DefaultProvidedInterface("janse",
- String.class);
- required.get(0).setProvider(provided);
- scope.publishInterface(provided, "hello");
-
- final X6 obj = new X6();
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.inject(scope, obj);
- }
- }, IllegalArgumentException.class);
- }
-
- public void testSetExplicitValue() {
- SetterConfiguration config = new SetterConfiguration(X5.class).initAllSetters();
- config.values("setValue").setValue(0, "bladibla");
-
- List<RequiredInterface> required = config.getRequiredInterfaces();
- assertEquals(0, required.size());
-
- X5 obj = new X5();
- assertNull(obj.getValue());
- config.inject(scope, obj);
- assertEquals("bladibla", obj.getValue());
- }
-
- public void testClear() {
- SetterConfiguration config = new SetterConfiguration(X6.class);
- config.clear();
- List<RequiredInterface> required = config.getRequiredInterfaces();
- Collections.sort(required, new RequiredInterfaceComparator());
- assertEquals(0, required.size());
-
- X6 obj = new X6();
- assertNull(obj.getHost());
- assertNull(obj.getPort());
-
- config.inject(scope, obj);
-
- assertNull(obj.getHost());
- assertNull(obj.getPort());
- }
-
- public void testAddByName() {
- SetterConfiguration config = new SetterConfiguration(X6.class);
- config.clear().add("setHost");
- List<RequiredInterface> required = config.getRequiredInterfaces();
- Collections.sort(required, new RequiredInterfaceComparator());
- assertEquals(1, required.size());
- assertEquals("setHost.0", required.get(0).getName());
-
- ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
- required.get(0).setProvider(provided0);
- scope.publishInterface(provided0, "hello");
-
- X6 obj = new X6();
- assertNull(obj.getHost());
- assertNull(obj.getPort());
-
- config.inject(scope, obj);
- assertEquals("hello", obj.getHost());
- assertNull(obj.getPort());
- }
-
- public void testAddByType() {
- SetterConfiguration config = new SetterConfiguration(X6.class);
- config.clear().addSetter(String.class);
- List<RequiredInterface> required = config.getRequiredInterfaces();
- Collections.sort(required, new RequiredInterfaceComparator());
- assertEquals(1, required.size());
- assertEquals("setHost.0", required.get(0).getName());
-
- ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
- required.get(0).setProvider(provided0);
- scope.publishInterface(provided0, "hello");
-
- X6 obj = new X6();
- assertNull(obj.getHost());
- assertNull(obj.getPort());
-
- config.inject(scope, obj);
- assertEquals("hello", obj.getHost());
- assertNull(obj.getPort());
- }
-
- public void testAddPrivate() {
- X5 obj = new X5();
- final SetterConfiguration config = new SetterConfiguration(X5.class);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.add("xyz");
- }
- }, IllegalArgumentException.class);
-
- config.setNonPublic(true);
- config.clear();
- config.add("setXyz");
- assertEquals(1, config.getRequiredInterfaces().size());
- }
-
- public void testAddNonExisting() {
- final SetterConfiguration config = new SetterConfiguration(X6.class);
- config.clear();
-
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.add("bladibla");
- }
- }, IllegalArgumentException.class);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.addSetter(DataSource.class);
- }
- }, IllegalArgumentException.class);
- }
-
- public void testAddByTypeNonUnique() {
- final SetterConfiguration config = new SetterConfiguration(X11.class);
- config.clear();
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.addSetter(String.class);
- }
- }, IllegalArgumentException.class);
- }
-
- public void testRemove() {
- SetterConfiguration config = new SetterConfiguration(X6.class).initAllSetters();
- config.remove("setPort");
- List<RequiredInterface> required = config.getRequiredInterfaces();
- Collections.sort(required, new RequiredInterfaceComparator());
- assertEquals(1, required.size());
- assertEquals("setHost.0", required.get(0).getName());
-
- ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
- String.class);
- required.get(0).setProvider(provided0);
- scope.publishInterface(provided0, "hello");
-
- X6 obj = new X6();
- assertNull(obj.getHost());
- assertNull(obj.getPort());
-
- config.inject(scope, obj);
- assertEquals("hello", obj.getHost());
- assertNull(obj.getPort());
- }
-
- public void testRemoveByMethodObject() throws NoSuchMethodException {
- SetterConfiguration config = new SetterConfiguration(X6.class).initAllSetters();
+ /**
+ * DOCUMENT ME!
+ */
+ public void testAddByName() {
+ SetterConfiguration config = new SetterConfiguration(X6.class);
+ config.clear().add("setHost");
+
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ Collections.sort(required, new RequiredInterfaceComparator());
+ assertEquals(1, required.size());
+ assertEquals("setHost.0", required.get(0).getName());
+
+ ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+ String.class);
+ required.get(0).setProvider(provided0);
+ scope.publishInterface(provided0, "hello");
+
+ X6 obj = new X6();
+ assertNull(obj.getHost());
+ assertNull(obj.getPort());
+
+ config.inject(scope, obj);
+ assertEquals("hello", obj.getHost());
+ assertNull(obj.getPort());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testAddByType() {
+ SetterConfiguration config = new SetterConfiguration(X6.class);
+ config.clear().addSetter(String.class);
+
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ Collections.sort(required, new RequiredInterfaceComparator());
+ assertEquals(1, required.size());
+ assertEquals("setHost.0", required.get(0).getName());
+
+ ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+ String.class);
+ required.get(0).setProvider(provided0);
+ scope.publishInterface(provided0, "hello");
+
+ X6 obj = new X6();
+ assertNull(obj.getHost());
+ assertNull(obj.getPort());
+
+ config.inject(scope, obj);
+ assertEquals("hello", obj.getHost());
+ assertNull(obj.getPort());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testAddPrivate() {
+ X5 obj = new X5();
+ final SetterConfiguration config = new SetterConfiguration(X5.class);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ config.add("xyz");
+ }
+ }, IllegalArgumentException.class);
+
+ config.setNonPublic(true);
+ config.clear();
+ config.add("setXyz");
+ assertEquals(1, config.getRequiredInterfaces().size());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testAddNonExisting() {
+ final SetterConfiguration config = new SetterConfiguration(X6.class);
+ config.clear();
+
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ config.add("bladibla");
+ }
+ }, IllegalArgumentException.class);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ config.addSetter(DataSource.class);
+ }
+ }, IllegalArgumentException.class);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testAddByTypeNonUnique() {
+ final SetterConfiguration config = new SetterConfiguration(X11.class);
+ config.clear();
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ config.addSetter(String.class);
+ }
+ }, IllegalArgumentException.class);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testRemove() {
+ SetterConfiguration config = new SetterConfiguration(X6.class)
+ .initAllSetters();
+ config.remove("setPort");
+
+ List<RequiredInterface> required = config.getRequiredInterfaces();
+ Collections.sort(required, new RequiredInterfaceComparator());
+ assertEquals(1, required.size());
+ assertEquals("setHost.0", required.get(0).getName());
+
+ ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+ String.class);
+ required.get(0).setProvider(provided0);
+ scope.publishInterface(provided0, "hello");
+
+ X6 obj = new X6();
+ assertNull(obj.getHost());
+ assertNull(obj.getPort());
+
+ config.inject(scope, obj);
+ assertEquals("hello", obj.getHost());
+ assertNull(obj.getPort());
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws NoSuchMethodException DOCUMENT ME!
+ */
+ public void testRemoveByMethodObject() throws NoSuchMethodException {
+ SetterConfiguration config = new SetterConfiguration(X6.class)
+ .initAllSetters();
config.remove(X6.class.getMethod("setPort", Integer.class));
+
List<RequiredInterface> required = config.getRequiredInterfaces();
Collections.sort(required, new RequiredInterfaceComparator());
assertEquals(1, required.size());
assertNull(obj.getPort());
}
- public void testRemoveNonExisting() {
- final SetterConfiguration config = new SetterConfiguration(X6.class);
-
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- config.remove("bladibla");
- }
- }, IllegalArgumentException.class);
- }
-
- public void testOverridingSetters() {
- SetterConfiguration config = new SetterConfiguration(X10.class).initAllSetters();
- assertEquals(2, config.getRequiredInterfaces().size());
- List<Method> methods = config.getSetters();
- assertEquals(2, methods.size());
- for (Method method: methods) {
- assertEquals(X10.class, method.getDeclaringClass());
- }
-
- }
+ /**
+ * DOCUMENT ME!
+ */
+ public void testRemoveNonExisting() {
+ final SetterConfiguration config = new SetterConfiguration(X6.class);
+
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ config.remove("bladibla");
+ }
+ }, IllegalArgumentException.class);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOverridingSetters() {
+ SetterConfiguration config = new SetterConfiguration(X10.class)
+ .initAllSetters();
+ assertEquals(2, config.getRequiredInterfaces().size());
+
+ List<Method> methods = config.getSetters();
+ assertEquals(2, methods.size());
+
+ for (Method method : methods) {
+ assertEquals(X10.class, method.getDeclaringClass());
+ }
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X1 {
- public X1() {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x1()");
- }
+ /**
+ * Creates a new X1 object.
+ */
+ public X1() {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x1()");
+ }
- public X1(String aValue) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x1(" + aValue + ")");
- }
-}
\ No newline at end of file
+ /**
+ * Creates a new X1 object.
+ *
+ * @param aValue DOCUMENT ME!
+ */
+ public X1(String aValue) {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x1(" + aValue + ")");
+ }
+}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X10 extends X6 {
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aHost DOCUMENT ME!
+ */
+ @Override
+ public void setHost(String aHost) {
+ super.setHost(aHost);
+ }
-
- @Override
- public void setHost(String aHost) {
- super.setHost(aHost);
- }
-
- @Override
- public String getHost() {
- return super.getHost();
- }
-
- @Override
- public Integer getPort() {
- return super.getPort();
- }
-
- @Override
- public void setPort(Integer aPort) {
- super.setPort(aPort);
- }
-
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String getHost() {
+ return super.getHost();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public Integer getPort() {
+ return super.getPort();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPort DOCUMENT ME!
+ */
+ @Override
+ public void setPort(Integer aPort) {
+ super.setPort(aPort);
+ }
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X11 {
-
-
- public void setX(String aValue) {
-
- }
-
- public void setY(String aValue) {
-
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aValue DOCUMENT ME!
+ */
+ public void setX(String aValue) {
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aValue DOCUMENT ME!
+ */
+ public void setY(String aValue) {
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X2 {
- public X2(Integer aInteger) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aInteger + ")");
- }
+ /**
+ * Creates a new X2 object.
+ *
+ * @param aInteger DOCUMENT ME!
+ */
+ public X2(Integer aInteger) {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aInteger + ")");
+ }
- public X2(String aValue) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aValue + ")");
- }
-}
\ No newline at end of file
+ /**
+ * Creates a new X2 object.
+ *
+ * @param aValue DOCUMENT ME!
+ */
+ public X2(String aValue) {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aValue + ")");
+ }
+}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X3 {
- public X3() {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x3()");
- }
+ /**
+ * Creates a new X3 object.
+ */
+ public X3() {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x3()");
+ }
- protected X3(String aValue) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x3(" + aValue + ")");
- }
-}
\ No newline at end of file
+ /**
+ * Creates a new X3 object.
+ *
+ * @param aValue DOCUMENT ME!
+ */
+ protected X3(String aValue) {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x3(" + aValue + ")");
+ }
+}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X4 {
+ /**
+ * DOCUMENT ME!
+ */
+ private X1 x1;
- private X1 x1;
-
- public X4(X1 aX1) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x4(x1)");
- x1 = aX1;
- }
-
- public X1 getX1() {
- return x1;
- }
+ /**
+ * Creates a new X4 object.
+ *
+ * @param aX1 DOCUMENT ME!
+ */
+ public X4(X1 aX1) {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x4(x1)");
+ x1 = aX1;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public X1 getX1() {
+ return x1;
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X5 {
-
- private String value;
- private Integer xyz;
-
- public X5() {
-
- }
-
- public void setValue(String aValue) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x5.setValue(" + aValue + ")");
- value = aValue;
- }
-
- public String getValue() {
+ /**
+ * DOCUMENT ME!
+ */
+ private String value;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Integer xyz;
+
+ /**
+ * Creates a new X5 object.
+ */
+ public X5() {
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aValue DOCUMENT ME!
+ */
+ public void setValue(String aValue) {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x5.setValue(" + aValue
+ + ")");
+ value = aValue;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getValue() {
return value;
}
-
- public void doSomething() {
- // Empty.
- }
-
- private void setXyz(int aXyz) {
- xyz = aXyz;
- }
-
- public Integer getXyz() {
- return xyz;
- }
-}
\ No newline at end of file
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void doSomething() {
+ // Empty.
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aXyz DOCUMENT ME!
+ */
+ private void setXyz(int aXyz) {
+ xyz = aXyz;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Integer getXyz() {
+ return xyz;
+ }
+}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X6 {
-
- private String host;
- private Integer port;
-
- public X6() {
-
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private String host;
- public Integer getPort() {
+ /**
+ * DOCUMENT ME!
+ */
+ private Integer port;
+
+ /**
+ * Creates a new X6 object.
+ */
+ public X6() {
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Integer getPort() {
return port;
}
-
- public void setPort(Integer aPort) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPort DOCUMENT ME!
+ */
+ public void setPort(Integer aPort) {
port = aPort;
}
-
- public String getHost() {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getHost() {
return host;
}
-
- public void setHost(String aHost) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aHost DOCUMENT ME!
+ */
+ public void setHost(String aHost) {
host = aHost;
}
-}
\ No newline at end of file
+}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X7 {
-
- private String host;
+ /**
+ * DOCUMENT ME!
+ */
+ private String host;
+
+ /**
+ * DOCUMENT ME!
+ */
private Integer port;
- private Boolean flag;
-
- public X7(Boolean aBoolean) {
- flag = aBoolean;
- }
-
- public Boolean getBoolean() {
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Boolean flag;
+
+ /**
+ * Creates a new X7 object.
+ *
+ * @param aBoolean DOCUMENT ME!
+ */
+ public X7(Boolean aBoolean) {
+ flag = aBoolean;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Boolean getBoolean() {
return flag;
}
- public Integer getPort() {
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Integer getPort() {
return port;
}
-
- public void setPort(Integer aPort) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPort DOCUMENT ME!
+ */
+ public void setPort(Integer aPort) {
port = aPort;
}
-
- public String getHost() {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getHost() {
return host;
}
-
- public void setHost(String aHost) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aHost DOCUMENT ME!
+ */
+ public void setHost(String aHost) {
host = aHost;
}
-}
\ No newline at end of file
+}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X8 {
+ /**
+ * DOCUMENT ME!
+ */
+ private X1 x1;
- private X1 x1;
- private X4 x4;
-
- public X8(X1 aX1) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x8(x1)");
- x1 = aX1;
- }
-
- public void setX4(X4 aX4) {
- AdapterTestCase.EVENT_TRACKER.eventOccurred("x8.setX4(x4)");
+ /**
+ * DOCUMENT ME!
+ */
+ private X4 x4;
+
+ /**
+ * Creates a new X8 object.
+ *
+ * @param aX1 DOCUMENT ME!
+ */
+ public X8(X1 aX1) {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x8(x1)");
+ x1 = aX1;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aX4 DOCUMENT ME!
+ */
+ public void setX4(X4 aX4) {
+ AdapterTestCase.EVENT_TRACKER.eventOccurred("x8.setX4(x4)");
x4 = aX4;
}
-
- public X4 getX4() {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public X4 getX4() {
return x4;
}
-
- public X1 getX1() {
- return x1;
- }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public X1 getX1() {
+ return x1;
+ }
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.system.adapters;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class X9 extends X5 {
-
- private boolean flag;
-
- public X9() {
-
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private boolean flag;
- public boolean isFlag() {
- return flag;
- }
-
+ /**
+ * Creates a new X9 object.
+ */
+ public X9() {
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public boolean isFlag() {
+ return flag;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aFlag DOCUMENT ME!
+ */
public void setFlag(boolean aFlag) {
- flag = aFlag;
- }
+ flag = aFlag;
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.components;
-import java.util.Properties;
-
import org.wamblee.support.persistence.Database;
import org.wamblee.support.persistence.DerbyDatabase;
+
import org.wamblee.system.components.ORMappingConfig.DatabaseType;
import org.wamblee.system.core.AbstractComponent;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.Scope;
+import java.util.Properties;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DatabaseComponent extends AbstractComponent<Database> {
-
- private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface("dbProps", Properties.class);
-
- private Database database;
-
- public DatabaseComponent(String aName, Database aDatabase) {
- super(aName);
+ /**
+ * DOCUMENT ME!
+ */
+ private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface("dbProps",
+ Properties.class);
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Database database;
+
+ /**
+ * Creates a new DatabaseComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aDatabase DOCUMENT ME!
+ */
+ public DatabaseComponent(String aName, Database aDatabase) {
+ super(aName);
database = aDatabase;
addProvidedInterface(DB_PROPS);
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected Database doStart(Scope aScope) {
- database.start();
-
+ database.start();
+
Properties props = new Properties();
- if ( database instanceof DerbyDatabase ) {
+
+ if (database instanceof DerbyDatabase) {
props.put("database.type", DatabaseType.DERBY.toString());
- } else {
- throw new IllegalArgumentException("Unknown database type " + database);
+ } else {
+ throw new IllegalArgumentException("Unknown database type "
+ + database);
}
+
//props.put("database.driver", database.getDriverClassName());
props.put("database.url", database.getJdbcUrl());
props.put("database.username", database.getUsername());
props.put("database.password", database.getPassword());
addInterface(DB_PROPS, props, aScope);
- return database;
+
+ return database;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
@Override
protected void doStop(Database aRuntime) {
database.stop();
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
package org.wamblee.system.components;
import org.wamblee.support.persistence.DatabaseBuilder;
+
import org.wamblee.system.container.Container;
-public class DatabaseComponentFactory {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class DatabaseComponentFactory {
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aContainer DOCUMENT ME!
+ */
public static void addDatabaseConfig(Container aContainer) {
try {
aContainer.addComponent(new DatabaseComponent("db",
- DatabaseBuilder.getDatabase()));
+ DatabaseBuilder.getDatabase()));
} catch (Exception e) {
- throw new RuntimeException("Could not add database configuration",
- e);
+ throw new RuntimeException("Could not add database configuration", e);
}
}
-
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+
import org.wamblee.test.EventTracker;
-public class Application extends AbstractComponent<Object> {
- public static RequiredInterface[] required(boolean aOptional,
- String aPrefix) {
- return new RequiredInterface[] {
- new DefaultRequiredInterface(aPrefix + "string", String.class,
- aOptional),
- new DefaultRequiredInterface(aPrefix + "integer",
- Integer.class, aOptional) };
- }
-
- public static RequiredInterface[] required(boolean aOptional) {
- return required(aOptional, "");
- }
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class Application extends AbstractComponent<Object> {
+ /**
+ * DOCUMENT ME!
+ */
private EventTracker<String> tracker;
+
+ /**
+ * DOCUMENT ME!
+ */
private String string;
+
+ /**
+ * DOCUMENT ME!
+ */
private Integer integer;
+
+ /**
+ * DOCUMENT ME!
+ */
private double random;
+ /**
+ * Creates a new Application object.
+ */
public Application() {
this("application");
}
+ /**
+ * Creates a new Application object.
+ *
+ * @param aName DOCUMENT ME!
+ */
public Application(String aName) {
this(aName, "");
}
+ /**
+ * Creates a new Application object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aPrefix DOCUMENT ME!
+ */
public Application(String aName, String aPrefix) {
- super(aName, new ProvidedInterface[0], required(false,
- aPrefix));
+ super(aName, new ProvidedInterface[0], required(false, aPrefix));
random = Math.random();
}
+ /**
+ * Creates a new Application object.
+ *
+ * @param aIsOptinal DOCUMENT ME!
+ */
public Application(boolean aIsOptinal) {
super("application", new ProvidedInterface[0], required(true, ""));
}
+ /**
+ * Creates a new Application object.
+ *
+ * @param aTracker DOCUMENT ME!
+ */
public Application(EventTracker<String> aTracker) {
this();
tracker = aTracker;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aOptional DOCUMENT ME!
+ * @param aPrefix DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public static RequiredInterface[] required(boolean aOptional, String aPrefix) {
+ return new RequiredInterface[] {
+ new DefaultRequiredInterface(aPrefix + "string", String.class,
+ aOptional),
+ new DefaultRequiredInterface(aPrefix + "integer", Integer.class,
+ aOptional)
+ };
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aOptional DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public static RequiredInterface[] required(boolean aOptional) {
+ return required(aOptional, "");
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public Object doStart(Scope aScope) {
track("start." + getName());
- string = aScope.getInterfaceImplementation(getRequiredInterfaces()
+ string = aScope.getInterfaceImplementation(getRequiredInterfaces()
.get(0).getProvider(), String.class);
- integer = aScope.getInterfaceImplementation(getRequiredInterfaces()
+ integer = aScope.getInterfaceImplementation(getRequiredInterfaces()
.get(1).getProvider(), Integer.class);
+
return random;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public String getString() {
return string;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public Integer getInteger() {
return integer;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
@Override
public void doStop(Object aRuntime) {
track("stop." + getName());
+
if (random != (Double) aRuntime) {
throw new IllegalArgumentException("Wrong runtime: expected "
- + random + " but got " + aRuntime);
+ + random + " but got " + aRuntime);
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aString DOCUMENT ME!
+ */
private void track(String aString) {
if (tracker == null) {
return;
}
+
tracker.eventOccurred(aString);
}
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.container;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
import junit.framework.TestCase;
import org.wamblee.general.Pair;
+
import org.wamblee.system.core.Component;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.Scope;
import org.wamblee.system.core.StringComponent;
import org.wamblee.system.core.SystemAssemblyException;
+
import org.wamblee.test.AssertionUtils;
import org.wamblee.test.EventTracker;
-public class ContainerTest extends TestCase {
+import java.io.Serializable;
+
+import java.util.ArrayList;
+import java.util.List;
+
- private EventTracker<String> tracker;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- tracker = new EventTracker<String>();
- }
-
- private static class MyMultiple implements Serializable, Runnable {
- @Override
- public void run() {
- // Empty
- }
- }
-
- private List<Pair<ProvidedInterface, Component>> createProvidedInput(
- ProvidedInterface[] aProvided, Component aProvider) {
- List<Pair<ProvidedInterface, Component>> result = new ArrayList<Pair<ProvidedInterface, Component>>();
- for (ProvidedInterface provided : aProvided) {
- result.add(new Pair<ProvidedInterface, Component>(provided,
- aProvider));
- }
- return result;
- }
-
- public void testEnvironmentApplication() {
- Environment environment = new Environment(tracker);
- Application application = new Application(tracker);
- Container container = new Container("root", new Component[] {
- environment, application }, new ProvidedInterface[0],
- new RequiredInterface[0]);
- Scope scope = container.start();
- assertTrue(container.isSealed());
- AssertionUtils.assertEquals(new String[] { "start.environment",
- "start.application" }, tracker.getEvents(
- Thread.currentThread()).toArray(new String[0]));
- assertEquals(0, scope.getProvidedInterfaces().size());
-
- assertEquals(environment.getString(), application.getString());
- assertEquals(environment.getInteger(), application.getInteger());
-
- }
-
- public void testEnvironmentApplicationSimpleConstructor() {
- Environment environment = new Environment(tracker);
- Application application = new Application(tracker);
- Container container = new Container("root").addComponent(environment)
- .addComponent(application);
-
- Scope scope = container.start();
- AssertionUtils.assertEquals(new String[] { "start.environment",
- "start.application" }, tracker.getEvents(
- Thread.currentThread()).toArray(new String[0]));
- assertEquals(0, scope.getProvidedInterfaces().size());
-
- assertEquals(environment.getString(), application.getString());
- assertEquals(environment.getInteger(), application.getInteger());
-
- }
-
- public void testApplicationEnvironment() {
- try {
- Component<?> environment = new Environment();
- Component<?> application = new Application();
- Container container = new Container("root", new Component[] {
- application, environment }, new ProvidedInterface[0],
- new RequiredInterface[0]);
- container.start();
- } catch (SystemAssemblyException e) {
- // e.printStackTrace();
- return;
- }
- fail();
- }
-
- public void testComposite() {
- Component<?> environment = new Environment(tracker);
- Component<?> application = new Application(tracker);
- assertEquals(0, tracker.getEventCount());
-
- Container system = new Container("all", new Component[] { environment,
- application }, new ProvidedInterface[0],
- new RequiredInterface[0]);
- Scope runtime = system.start();
- List<RequiredInterface> required = system.getRequiredInterfaces();
- assertEquals(0, required.size());
- List<ProvidedInterface> provided = system.getProvidedInterfaces();
- assertEquals(0, provided.size());
-
- AssertionUtils.assertEquals(new String[] { "start.environment",
- "start.application" }, tracker.getEvents(
- Thread.currentThread()).toArray(new String[0]));
- tracker.clear();
-
- system.stop(runtime);
- AssertionUtils.assertEquals(new String[] { "stop.application",
- "stop.environment" }, tracker
- .getEvents(Thread.currentThread()).toArray(new String[0]));
-
- }
-
- public void testCompositeWithWrongProvidedInfo() {
- try {
- Component<?> environment = new Environment();
- Component<?> application = new Application();
- Container system = new Container("all", new Component[] {
- environment, application },
- new ProvidedInterface[] { new DefaultProvidedInterface(
- "float", Float.class) },
- new DefaultRequiredInterface[0]);
- system.validate();
- } catch (SystemAssemblyException e) {
- return;
- }
- fail();
- }
-
- public void testCompositeRequiredInterfaceNotProvided() {
- try {
- Component<?> environment = new Environment();
- Component<?> application = new Application();
- Container system = new Container("all", new Component[] {
- environment, application }, new ProvidedInterface[0],
- new RequiredInterface[] { new DefaultRequiredInterface(
- "string", String.class) });
- system.start();
- } catch (SystemAssemblyException e) {
- return;
- }
- fail();
- }
-
- public void testCompositeWithSuperfluousRequiredInfo() {
- Component<?> environment = new Environment();
- Component<?> application = new Application();
- Container system = new Container("all", new Component[] { environment,
- application }, new ProvidedInterface[0],
- new RequiredInterface[] { new DefaultRequiredInterface("float",
- Float.class) });
- system.getRequiredInterfaces().get(0).setProvider(
- new DefaultProvidedInterface("hallo", Float.class));
- system.start();
- List<RequiredInterface> required = system.getRequiredInterfaces();
- assertEquals(1, required.size());
- List<ProvidedInterface> provided = system.getProvidedInterfaces();
- assertEquals(0, provided.size());
- }
-
- public void testCompositeWithExternalDependencesNotProvided() {
- try {
- Component<?> application = new Application();
-
- Container system = new Container("all",
- new Component[] { application }, new ProvidedInterface[0],
- application.getRequiredInterfaces().toArray(
- new RequiredInterface[0]));
- system.start();
- } catch (SystemAssemblyException e) {
- return;
- }
- fail();
- }
-
- public void testDuplicateComponent() {
- try {
- Component<?> comp1 = new Application();
- Component<?> comp2 = new Application();
- Container system = new Container("top");
- system.addComponent(comp1).addComponent(comp2);
- } catch (SystemAssemblyException e) {
- return;
- }
- fail();
- }
-
- public void testInconsistentHierarchy() {
- try {
- Component<?> comp = new Application();
- Container system = new Container("top").addComponent(comp);
- Container system2 = new Container("top2").addComponent(comp);
- } catch (SystemAssemblyException e) {
- return;
- }
- fail();
- }
-
- public void testCompositeWithExternalDependencesProvided() {
-
- Component<?> environment = new Environment();
- Component<?> application = new Application();
- Container system = new Container("all",
- new Component[] { application }, new ProvidedInterface[0],
- application.getRequiredInterfaces().toArray(
- new RequiredInterface[0]));
- environment.start(new DefaultScope(new ProvidedInterface[0]));
- system.getRequiredInterfaces().get(0).setProvider(
- environment.getProvidedInterfaces().get(0));
- system.getRequiredInterfaces().get(1).setProvider(
- environment.getProvidedInterfaces().get(1));
-
- system.start();
- List<RequiredInterface> required = system.getRequiredInterfaces();
- assertEquals(2, required.size());
- List<ProvidedInterface> provided = system.getProvidedInterfaces();
- assertEquals(0, provided.size());
-
- }
-
- public void testAmbiguousInterfaces() {
- try {
- Component<?> environment1 = new Environment();
- Component<?> environment2 = new Environment();
- Component<?> application = new Application();
- Container container = new Container("root", new Component[] {
- environment1, environment2, application },
- new ProvidedInterface[0], new RequiredInterface[0]);
- container.start();
-
- } catch (SystemAssemblyException e) {
- return;
- }
- fail();
- }
-
- public void testIncompleteRequirements() {
- try {
- Component<?> application = new Application();
- Container system = new Container("all",
- new Component[] { application }, new ProvidedInterface[0],
- new RequiredInterface[0]);
- system.start();
- } catch (SystemAssemblyException e) {
- return;
- }
- fail();
- }
-
- public void testEnvironmentApplicationRollbackOnException()
- throws Exception {
- Environment environment = new Environment(tracker);
- Application application = new Application() {
- @Override
- public Object doStart(Scope aScope) {
- throw new RuntimeException();
- }
- };
-
- try {
- Container container = new Container("root", new Component[] {
- environment, application }, new ProvidedInterface[0],
- new RequiredInterface[0]);
-
- container.start();
- } catch (RuntimeException e) {
- AssertionUtils.assertEquals(new String[] { "start.environment",
- "stop.environment" }, tracker.getEvents(
- Thread.currentThread()).toArray(new String[0]));
- return;
- }
- fail();
- }
-
- public void testEnvironmentApplicationRollbackOnExceptionWithExceptionOnStop()
- throws Exception {
-
- Environment environment = new Environment(tracker);
- // Application 1 will throw an exception while stopping.
- Application application1 = new Application("app1") {
- @Override
- public void doStop(Object aRuntime) {
- throw new RuntimeException();
- }
- };
-
- // application 2 will throw an exception while starting
- Application application2 = new Application("app2") {
- public Object doStart(Scope aScope) {
- throw new RuntimeException();
- }
- };
-
- try {
- Container container = new Container("root", new Component[] {
- environment, application1, application2 },
- new ProvidedInterface[0], new RequiredInterface[0]);
-
- container.start();
- } catch (RuntimeException e) {
- AssertionUtils.assertEquals(new String[] { "start.environment",
- "stop.environment" }, tracker.getEvents(
- Thread.currentThread()).toArray(new String[0]));
- return;
- }
- fail();
- }
-
- public void testOptionalRequiredInterfaceProvidedOptionalInternal() {
- Application application = new Application(true);
- Container container = new Container("top",
- new Component[] { application }, new ProvidedInterface[0],
- Application.required(true));
- Environment env = new Environment();
- container.getRequiredInterfaces().get(0).setProvider(
- env.getProvidedInterfaces().get(0));
- container.getRequiredInterfaces().get(1).setProvider(
- env.getProvidedInterfaces().get(1));
- Scope external = new DefaultScope(env.getProvidedInterfaces());
- env.start(external);
-
- container.start(external);
- assertSame(env.getProvidedInterfaces().get(0), container
- .getRequiredInterfaces().get(0).getProvider());
- assertSame(env.getProvidedInterfaces().get(1), container
- .getRequiredInterfaces().get(1).getProvider());
- assertSame(env.getProvidedInterfaces().get(0), application
- .getRequiredInterfaces().get(0).getProvider());
- assertSame(env.getProvidedInterfaces().get(1), application
- .getRequiredInterfaces().get(1).getProvider());
- }
-
- public void testOptionalRequiredInterfaceNotProvidedOptionalInternal() {
- Application application = new Application(true);
- Container container = new Container("top",
- new Component[] { application }, new ProvidedInterface[0],
- Application.required(true));
- Environment env = new Environment();
- container.getRequiredInterfaces().get(0).setProvider(
- env.getProvidedInterfaces().get(0));
- Scope external = new DefaultScope(new ProvidedInterface[0]);
- external.publishInterface(env.getProvidedInterfaces().get(0), env
- .getString());
- container.start(external);
- assertSame(env.getProvidedInterfaces().get(0), container
- .getRequiredInterfaces().get(0).getProvider());
- assertNull(container.getRequiredInterfaces().get(1).getProvider());
- assertSame(env.getProvidedInterfaces().get(0), application
- .getRequiredInterfaces().get(0).getProvider());
- assertNull(application.getRequiredInterfaces().get(1).getProvider());
- }
-
- public void testOptionalRequiredInterfaceProvidedMandatoryInternal() {
- Application application = new Application();
- Container container = new Container("top",
- new Component[] { application }, new ProvidedInterface[0],
- Application.required(true));
- Environment env = new Environment();
- container.getRequiredInterfaces().get(0).setProvider(
- env.getProvidedInterfaces().get(0));
- container.getRequiredInterfaces().get(1).setProvider(
- env.getProvidedInterfaces().get(1));
- try {
- container.start();
- } catch (SystemAssemblyException e) {
- return;
- }
- fail();
- }
-
- public void testSealed() {
- final Container container = new Container("xx");
- assertFalse(container.isSealed());
- container.start();
- assertTrue(container.isSealed());
-
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.addComponent(new Application());
- }
- }, SystemAssemblyException.class);
-
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("x", "y", "a", "b");
- }
- }, SystemAssemblyException.class);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalRequired("x", "y", "a");
- }
- }, SystemAssemblyException.class);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalProvided("x", "y", "z");
- }
- }, SystemAssemblyException.class);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.addProvidedInterface(new DefaultProvidedInterface(
- "xx", String.class));
- }
- }, SystemAssemblyException.class);
-
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.addRequiredInterface(new DefaultRequiredInterface(
- "xx", String.class));
- }
- }, SystemAssemblyException.class);
- }
-
- public void testRestriction() {
- Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
- Application app = new Application("app");
- Container container = new Container("top").addComponent(env1)
- .addComponent(env2).addComponent(app);
- container.connectRequiredProvided("app", null, "env1", null);
- container.start();
- assertEquals(env1.getString(), app.getString());
- assertEquals(env1.getInteger(), app.getInteger());
- assertFalse(env2.getString().equals(app.getString()));
- assertFalse(env2.getInteger().equals(app.getInteger()));
- }
-
- public void testRestrictionWithFromAndToInterfaceName() {
- Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
- Application app = new Application("app");
- Container container = new Container("top").addComponent(env1)
- .addComponent(env2).addComponent(app);
- container.connectRequiredProvided("app", app.getRequiredInterfaces()
- .get(0).getName(), "env1", env1.getProvidedInterfaces().get(0)
- .getName());
- container.connectRequiredProvided("app", app.getRequiredInterfaces()
- .get(1).getName(), "env2", env2.getProvidedInterfaces().get(1)
- .getName());
- container.start();
- assertEquals(env1.getString(), app.getString());
- assertEquals(env2.getInteger(), app.getInteger());
- assertFalse(env2.getString().equals(app.getString()));
- assertFalse(env1.getInteger().equals(app.getInteger()));
- }
-
- public void testRestrictionWrongComponentNames() {
- Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
- Application app = new Application("app");
- final Container container = new Container("top").addComponent(env1)
- .addComponent(env2).addComponent(app);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("app2", null, "env1", null);
- }
- }, SystemAssemblyException.class);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("app", null, "env3", null);
- }
- }, SystemAssemblyException.class);
- }
-
- public void testRestrictionWrongInterfaceNames() {
- final Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
- final Application app = new Application("app");
- final Container container = new Container("top").addComponent(env1)
- .addComponent(env2).addComponent(app);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("app", app
- .getRequiredInterfaces().get(0).getName()
- + "xxx", "env1", null);
- }
- }, SystemAssemblyException.class);
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectRequiredProvided("app", null, "env1", env1
- .getProvidedInterfaces().get(0).getName()
- + "yyy");
- }
- }, SystemAssemblyException.class);
- }
-
- public void testProvidedInDifferentScopes() {
- // Scoping problem occurred. Externally and internally provided
- // components clashed
- // because unique id generation in the scope was wrong.
-
- StringComponent str = new StringComponent("string");
- Application app = new Application("app");
- Container container = new Container("top").addComponent(str)
- .addComponent(app);
- container.addRequiredInterface(new DefaultRequiredInterface("integer",
- Integer.class));
-
- ProvidedInterface provided = new DefaultProvidedInterface("hallo",
- Integer.class);
- container.getRequiredInterfaces().get(0).setProvider(provided);
-
- Scope external = new DefaultScope(new ProvidedInterface[0]);
- external.publishInterface(provided, 100);
- Scope scope = container.start(external);
- }
-
- public void testProvidedInterfaces() {
- Environment env = new Environment(tracker);
- Container envcontainer = new Container("0").addComponent(env)
- .addProvidedInterface(
- new DefaultProvidedInterface("string", String.class))
- .addProvidedInterface(
- new DefaultProvidedInterface("integer", Integer.class));
- Scope scope = envcontainer.start();
-
- AssertionUtils.assertEquals(new String[] { "start.environment" },
- tracker.getEvents(Thread.currentThread()).toArray(
- new String[0]));
-
- envcontainer.stop(scope);
- }
-
- public void testCoupleTwoContainers() {
- Environment env = new Environment(tracker);
- Container envcontainer = new Container("0").addComponent(env)
- .addProvidedInterface(
- new DefaultProvidedInterface("string", String.class))
- .addProvidedInterface(
- new DefaultProvidedInterface("integer", Integer.class));
-
- Application app = new Application(tracker);
- Container appcontainer = new Container("1").addComponent(app)
- .addRequiredInterface(
- new DefaultRequiredInterface("string", String.class))
- .addRequiredInterface(
- new DefaultRequiredInterface("integer", Integer.class));
-
- Container top = new Container("top");
- top.addComponent(envcontainer).addComponent(appcontainer);
-
- top.start();
- AssertionUtils.assertEquals(new String[] { "start.environment",
- "start.application" }, tracker.getEvents(
- Thread.currentThread()).toArray(new String[0]));
-
- }
-
- public void testNonUniqueRequiredInterface() {
- final Container container = new Container("top");
- container.addRequiredInterface(new DefaultRequiredInterface("i",
- Integer.class));
- container.addRequiredInterface(new DefaultRequiredInterface("x",
- String.class));
- container.addRequiredInterface(new DefaultRequiredInterface("y",
- String.class));
-
- Application app = new Application("1");
- container.addComponent(app);
-
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.start();
- }
- }, SystemAssemblyException.class);
-
- container.connectExternalRequired("1", app.getRequiredInterfaces().get(
- 0).getName(), "y");
-
- ProvidedInterface i = new DefaultProvidedInterface("i", Integer.class);
- ProvidedInterface x = new DefaultProvidedInterface("x", String.class);
- ProvidedInterface y = new DefaultProvidedInterface("y", String.class);
-
- Scope externalScope = new DefaultScope(new ProvidedInterface[0]);
-
- externalScope.publishInterface(i, 100);
- externalScope.publishInterface(x, "x-value");
- externalScope.publishInterface(y, "y-value");
-
- container.getRequiredInterfaces().get(0).setProvider(i);
- container.getRequiredInterfaces().get(1).setProvider(x);
- container.getRequiredInterfaces().get(2).setProvider(y);
-
- Scope runtime = container.start(externalScope);
-
- assertEquals("y-value", app.getString());
-
- }
-
- public void testNonUniqueRequiredInterfaceWrongNames() {
- final Container container = new Container("top");
- container.addRequiredInterface(new DefaultRequiredInterface("i",
- Integer.class));
- container.addRequiredInterface(new DefaultRequiredInterface("x",
- String.class));
- container.addRequiredInterface(new DefaultRequiredInterface("y",
- String.class));
-
- final Application app = new Application("1");
- container.addComponent(app);
-
- // wrong component name.
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalRequired("2", "x", "y");
- }
- }, SystemAssemblyException.class);
-
- // Wrong interface name of component.
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalRequired("1", app
- .getRequiredInterfaces().get(0).getName()
- + "xxx", "y");
- }
- }, SystemAssemblyException.class);
-
- // Wrong external interface name of container
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalRequired("1", app
- .getRequiredInterfaces().get(0).getName(), "z");
- }
- }, SystemAssemblyException.class);
- }
-
- public void testNonUniqueProvidedInterface() {
-
- final Container container = new Container("top")
- .addProvidedInterface(new DefaultProvidedInterface("external",
- String.class));
- Environment env1 = new Environment("env1");
- Environment env2 = new Environment("env2");
-
- container.addComponent(env1);
- container.addComponent(env2);
-
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.start();
- }
- }, SystemAssemblyException.class);
-
- // now choose env2
-
- container.connectExternalProvided(container.getProvidedInterfaces()
- .get(0).getName(), env2.getName(), env2.getProvidedInterfaces()
- .get(0).getName());
-
- Scope scope = container.start();
-
- // check the value of the provided interface of the container
-
- String value = scope.getInterfaceImplementation(container
- .getProvidedInterfaces().get(0), String.class);
- assertNotNull(value);
- assertEquals(value, env2.getString());
- assertFalse(value.equals(env1.getString()));
- }
-
- public void testNonUniqueProvidedInterfaceWrongNames() {
-
- final Container container = new Container("top")
- .addProvidedInterface(new DefaultProvidedInterface("external",
- String.class));
- final Environment env1 = new Environment("env1");
- final Environment env2 = new Environment("env2");
-
- container.addComponent(env1);
- container.addComponent(env2);
-
- // Wrong external provided interface name
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalProvided(container
- .getProvidedInterfaces().get(0).getName()
- + "xx", "env1", env1.getProvidedInterfaces().get(0)
- .getName());
- }
- }, SystemAssemblyException.class);
-
- // Wrong provided interface name.
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalProvided(container
- .getProvidedInterfaces().get(0).getName(), "env1", env1
- .getProvidedInterfaces().get(0).getName()
- + "xx");
- }
- }, SystemAssemblyException.class);
-
- // Wrong provided component
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- container.connectExternalProvided(container
- .getProvidedInterfaces().get(0).getName(), "env3", env1
- .getProvidedInterfaces().get(0).getName());
- }
- }, SystemAssemblyException.class);
- }
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ContainerTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
+ private EventTracker<String> tracker;
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ tracker = new EventTracker<String>();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aProvided DOCUMENT ME!
+ * @param aProvider DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private List<Pair<ProvidedInterface, Component>> createProvidedInput(
+ ProvidedInterface[] aProvided, Component aProvider) {
+ List<Pair<ProvidedInterface, Component>> result = new ArrayList<Pair<ProvidedInterface, Component>>();
+
+ for (ProvidedInterface provided : aProvided) {
+ result.add(new Pair<ProvidedInterface, Component>(provided,
+ aProvider));
+ }
+
+ return result;
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testEnvironmentApplication() {
+ Environment environment = new Environment(tracker);
+ Application application = new Application(tracker);
+ Container container = new Container("root",
+ new Component[] { environment, application },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+ Scope scope = container.start();
+ assertTrue(container.isSealed());
+ AssertionUtils.assertEquals(new String[] {
+ "start.environment", "start.application"
+ }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ assertEquals(0, scope.getProvidedInterfaces().size());
+
+ assertEquals(environment.getString(), application.getString());
+ assertEquals(environment.getInteger(), application.getInteger());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testEnvironmentApplicationSimpleConstructor() {
+ Environment environment = new Environment(tracker);
+ Application application = new Application(tracker);
+ Container container = new Container("root").addComponent(environment)
+ .addComponent(application);
+
+ Scope scope = container.start();
+ AssertionUtils.assertEquals(new String[] {
+ "start.environment", "start.application"
+ }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ assertEquals(0, scope.getProvidedInterfaces().size());
+
+ assertEquals(environment.getString(), application.getString());
+ assertEquals(environment.getInteger(), application.getInteger());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testApplicationEnvironment() {
+ try {
+ Component<?> environment = new Environment();
+ Component<?> application = new Application();
+ Container container = new Container("root",
+ new Component[] { application, environment },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+ container.start();
+ } catch (SystemAssemblyException e) {
+ // e.printStackTrace();
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testComposite() {
+ Component<?> environment = new Environment(tracker);
+ Component<?> application = new Application(tracker);
+ assertEquals(0, tracker.getEventCount());
+
+ Container system = new Container("all",
+ new Component[] { environment, application },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+ Scope runtime = system.start();
+ List<RequiredInterface> required = system.getRequiredInterfaces();
+ assertEquals(0, required.size());
+
+ List<ProvidedInterface> provided = system.getProvidedInterfaces();
+ assertEquals(0, provided.size());
+
+ AssertionUtils.assertEquals(new String[] {
+ "start.environment", "start.application"
+ }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ tracker.clear();
+
+ system.stop(runtime);
+ AssertionUtils.assertEquals(new String[] {
+ "stop.application", "stop.environment"
+ }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testCompositeWithWrongProvidedInfo() {
+ try {
+ Component<?> environment = new Environment();
+ Component<?> application = new Application();
+ Container system = new Container("all",
+ new Component[] { environment, application },
+ new ProvidedInterface[] {
+ new DefaultProvidedInterface("float", Float.class)
+ }, new DefaultRequiredInterface[0]);
+ system.validate();
+ } catch (SystemAssemblyException e) {
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testCompositeRequiredInterfaceNotProvided() {
+ try {
+ Component<?> environment = new Environment();
+ Component<?> application = new Application();
+ Container system = new Container("all",
+ new Component[] { environment, application },
+ new ProvidedInterface[0],
+ new RequiredInterface[] {
+ new DefaultRequiredInterface("string", String.class)
+ });
+ system.start();
+ } catch (SystemAssemblyException e) {
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testCompositeWithSuperfluousRequiredInfo() {
+ Component<?> environment = new Environment();
+ Component<?> application = new Application();
+ Container system = new Container("all",
+ new Component[] { environment, application },
+ new ProvidedInterface[0],
+ new RequiredInterface[] {
+ new DefaultRequiredInterface("float", Float.class)
+ });
+ system.getRequiredInterfaces().get(0)
+ .setProvider(new DefaultProvidedInterface("hallo", Float.class));
+ system.start();
+
+ List<RequiredInterface> required = system.getRequiredInterfaces();
+ assertEquals(1, required.size());
+
+ List<ProvidedInterface> provided = system.getProvidedInterfaces();
+ assertEquals(0, provided.size());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testCompositeWithExternalDependencesNotProvided() {
+ try {
+ Component<?> application = new Application();
+
+ Container system = new Container("all",
+ new Component[] { application }, new ProvidedInterface[0],
+ application.getRequiredInterfaces()
+ .toArray(new RequiredInterface[0]));
+ system.start();
+ } catch (SystemAssemblyException e) {
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testDuplicateComponent() {
+ try {
+ Component<?> comp1 = new Application();
+ Component<?> comp2 = new Application();
+ Container system = new Container("top");
+ system.addComponent(comp1).addComponent(comp2);
+ } catch (SystemAssemblyException e) {
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testInconsistentHierarchy() {
+ try {
+ Component<?> comp = new Application();
+ Container system = new Container("top").addComponent(comp);
+ Container system2 = new Container("top2").addComponent(comp);
+ } catch (SystemAssemblyException e) {
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testCompositeWithExternalDependencesProvided() {
+ Component<?> environment = new Environment();
+ Component<?> application = new Application();
+ Container system = new Container("all",
+ new Component[] { application }, new ProvidedInterface[0],
+ application.getRequiredInterfaces()
+ .toArray(new RequiredInterface[0]));
+ environment.start(new DefaultScope(new ProvidedInterface[0]));
+ system.getRequiredInterfaces().get(0)
+ .setProvider(environment.getProvidedInterfaces().get(0));
+ system.getRequiredInterfaces().get(1)
+ .setProvider(environment.getProvidedInterfaces().get(1));
+
+ system.start();
+
+ List<RequiredInterface> required = system.getRequiredInterfaces();
+ assertEquals(2, required.size());
+
+ List<ProvidedInterface> provided = system.getProvidedInterfaces();
+ assertEquals(0, provided.size());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testAmbiguousInterfaces() {
+ try {
+ Component<?> environment1 = new Environment();
+ Component<?> environment2 = new Environment();
+ Component<?> application = new Application();
+ Container container = new Container("root",
+ new Component[] { environment1, environment2, application },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+ container.start();
+ } catch (SystemAssemblyException e) {
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testIncompleteRequirements() {
+ try {
+ Component<?> application = new Application();
+ Container system = new Container("all",
+ new Component[] { application }, new ProvidedInterface[0],
+ new RequiredInterface[0]);
+ system.start();
+ } catch (SystemAssemblyException e) {
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ * @throws RuntimeException DOCUMENT ME!
+ */
+ public void testEnvironmentApplicationRollbackOnException()
+ throws Exception {
+ Environment environment = new Environment(tracker);
+ Application application = new Application() {
+ @Override
+ public Object doStart(Scope aScope) {
+ throw new RuntimeException();
+ }
+ };
+
+ try {
+ Container container = new Container("root",
+ new Component[] { environment, application },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+
+ container.start();
+ } catch (RuntimeException e) {
+ AssertionUtils.assertEquals(new String[] {
+ "start.environment", "stop.environment"
+ },
+ tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ * @throws RuntimeException DOCUMENT ME!
+ */
+ public void testEnvironmentApplicationRollbackOnExceptionWithExceptionOnStop()
+ throws Exception {
+ Environment environment = new Environment(tracker);
+
+ // Application 1 will throw an exception while stopping.
+ Application application1 = new Application("app1") {
+ @Override
+ public void doStop(Object aRuntime) {
+ throw new RuntimeException();
+ }
+ };
+
+ // application 2 will throw an exception while starting
+ Application application2 = new Application("app2") {
+ public Object doStart(Scope aScope) {
+ throw new RuntimeException();
+ }
+ };
+
+ try {
+ Container container = new Container("root",
+ new Component[] { environment, application1, application2 },
+ new ProvidedInterface[0], new RequiredInterface[0]);
+
+ container.start();
+ } catch (RuntimeException e) {
+ AssertionUtils.assertEquals(new String[] {
+ "start.environment", "stop.environment"
+ },
+ tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOptionalRequiredInterfaceProvidedOptionalInternal() {
+ Application application = new Application(true);
+ Container container = new Container("top",
+ new Component[] { application }, new ProvidedInterface[0],
+ Application.required(true));
+ Environment env = new Environment();
+ container.getRequiredInterfaces().get(0)
+ .setProvider(env.getProvidedInterfaces().get(0));
+ container.getRequiredInterfaces().get(1)
+ .setProvider(env.getProvidedInterfaces().get(1));
+
+ Scope external = new DefaultScope(env.getProvidedInterfaces());
+ env.start(external);
+
+ container.start(external);
+ assertSame(env.getProvidedInterfaces().get(0),
+ container.getRequiredInterfaces().get(0).getProvider());
+ assertSame(env.getProvidedInterfaces().get(1),
+ container.getRequiredInterfaces().get(1).getProvider());
+ assertSame(env.getProvidedInterfaces().get(0),
+ application.getRequiredInterfaces().get(0).getProvider());
+ assertSame(env.getProvidedInterfaces().get(1),
+ application.getRequiredInterfaces().get(1).getProvider());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOptionalRequiredInterfaceNotProvidedOptionalInternal() {
+ Application application = new Application(true);
+ Container container = new Container("top",
+ new Component[] { application }, new ProvidedInterface[0],
+ Application.required(true));
+ Environment env = new Environment();
+ container.getRequiredInterfaces().get(0)
+ .setProvider(env.getProvidedInterfaces().get(0));
+
+ Scope external = new DefaultScope(new ProvidedInterface[0]);
+ external.publishInterface(env.getProvidedInterfaces().get(0),
+ env.getString());
+ container.start(external);
+ assertSame(env.getProvidedInterfaces().get(0),
+ container.getRequiredInterfaces().get(0).getProvider());
+ assertNull(container.getRequiredInterfaces().get(1).getProvider());
+ assertSame(env.getProvidedInterfaces().get(0),
+ application.getRequiredInterfaces().get(0).getProvider());
+ assertNull(application.getRequiredInterfaces().get(1).getProvider());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOptionalRequiredInterfaceProvidedMandatoryInternal() {
+ Application application = new Application();
+ Container container = new Container("top",
+ new Component[] { application }, new ProvidedInterface[0],
+ Application.required(true));
+ Environment env = new Environment();
+ container.getRequiredInterfaces().get(0)
+ .setProvider(env.getProvidedInterfaces().get(0));
+ container.getRequiredInterfaces().get(1)
+ .setProvider(env.getProvidedInterfaces().get(1));
+
+ try {
+ container.start();
+ } catch (SystemAssemblyException e) {
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testSealed() {
+ final Container container = new Container("xx");
+ assertFalse(container.isSealed());
+ container.start();
+ assertTrue(container.isSealed());
+
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.addComponent(new Application());
+ }
+ }, SystemAssemblyException.class);
+
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("x", "y", "a", "b");
+ }
+ }, SystemAssemblyException.class);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectExternalRequired("x", "y", "a");
+ }
+ }, SystemAssemblyException.class);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectExternalProvided("x", "y", "z");
+ }
+ }, SystemAssemblyException.class);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.addProvidedInterface(new DefaultProvidedInterface(
+ "xx", String.class));
+ }
+ }, SystemAssemblyException.class);
+
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.addRequiredInterface(new DefaultRequiredInterface(
+ "xx", String.class));
+ }
+ }, SystemAssemblyException.class);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testRestriction() {
+ Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+ Application app = new Application("app");
+ Container container = new Container("top").addComponent(env1)
+ .addComponent(env2).addComponent(app);
+ container.connectRequiredProvided("app", null, "env1", null);
+ container.start();
+ assertEquals(env1.getString(), app.getString());
+ assertEquals(env1.getInteger(), app.getInteger());
+ assertFalse(env2.getString().equals(app.getString()));
+ assertFalse(env2.getInteger().equals(app.getInteger()));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testRestrictionWithFromAndToInterfaceName() {
+ Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+ Application app = new Application("app");
+ Container container = new Container("top").addComponent(env1)
+ .addComponent(env2).addComponent(app);
+ container.connectRequiredProvided("app",
+ app.getRequiredInterfaces().get(0).getName(), "env1",
+ env1.getProvidedInterfaces().get(0).getName());
+ container.connectRequiredProvided("app",
+ app.getRequiredInterfaces().get(1).getName(), "env2",
+ env2.getProvidedInterfaces().get(1).getName());
+ container.start();
+ assertEquals(env1.getString(), app.getString());
+ assertEquals(env2.getInteger(), app.getInteger());
+ assertFalse(env2.getString().equals(app.getString()));
+ assertFalse(env1.getInteger().equals(app.getInteger()));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testRestrictionWrongComponentNames() {
+ Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+ Application app = new Application("app");
+ final Container container = new Container("top").addComponent(env1)
+ .addComponent(env2).addComponent(app);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("app2", null, "env1", null);
+ }
+ }, SystemAssemblyException.class);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("app", null, "env3", null);
+ }
+ }, SystemAssemblyException.class);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testRestrictionWrongInterfaceNames() {
+ final Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+ final Application app = new Application("app");
+ final Container container = new Container("top").addComponent(env1)
+ .addComponent(env2).addComponent(app);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("app",
+ app.getRequiredInterfaces().get(0).getName() + "xxx",
+ "env1", null);
+ }
+ }, SystemAssemblyException.class);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectRequiredProvided("app", null, "env1",
+ env1.getProvidedInterfaces().get(0).getName() + "yyy");
+ }
+ }, SystemAssemblyException.class);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testProvidedInDifferentScopes() {
+ // Scoping problem occurred. Externally and internally provided
+ // components clashed
+ // because unique id generation in the scope was wrong.
+ StringComponent str = new StringComponent("string");
+ Application app = new Application("app");
+ Container container = new Container("top").addComponent(str)
+ .addComponent(app);
+ container.addRequiredInterface(new DefaultRequiredInterface("integer",
+ Integer.class));
+
+ ProvidedInterface provided = new DefaultProvidedInterface("hallo",
+ Integer.class);
+ container.getRequiredInterfaces().get(0).setProvider(provided);
+
+ Scope external = new DefaultScope(new ProvidedInterface[0]);
+ external.publishInterface(provided, 100);
+
+ Scope scope = container.start(external);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testProvidedInterfaces() {
+ Environment env = new Environment(tracker);
+ Container envcontainer = new Container("0").addComponent(env)
+ .addProvidedInterface(new DefaultProvidedInterface("string",
+ String.class))
+ .addProvidedInterface(new DefaultProvidedInterface("integer",
+ Integer.class));
+ Scope scope = envcontainer.start();
+
+ AssertionUtils.assertEquals(new String[] { "start.environment" },
+ tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+
+ envcontainer.stop(scope);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testCoupleTwoContainers() {
+ Environment env = new Environment(tracker);
+ Container envcontainer = new Container("0").addComponent(env)
+ .addProvidedInterface(new DefaultProvidedInterface("string",
+ String.class))
+ .addProvidedInterface(new DefaultProvidedInterface("integer",
+ Integer.class));
+
+ Application app = new Application(tracker);
+ Container appcontainer = new Container("1").addComponent(app)
+ .addRequiredInterface(new DefaultRequiredInterface("string",
+ String.class))
+ .addRequiredInterface(new DefaultRequiredInterface("integer",
+ Integer.class));
+
+ Container top = new Container("top");
+ top.addComponent(envcontainer).addComponent(appcontainer);
+
+ top.start();
+ AssertionUtils.assertEquals(new String[] {
+ "start.environment", "start.application"
+ }, tracker.getEvents(Thread.currentThread()).toArray(new String[0]));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNonUniqueRequiredInterface() {
+ final Container container = new Container("top");
+ container.addRequiredInterface(new DefaultRequiredInterface("i",
+ Integer.class));
+ container.addRequiredInterface(new DefaultRequiredInterface("x",
+ String.class));
+ container.addRequiredInterface(new DefaultRequiredInterface("y",
+ String.class));
+
+ Application app = new Application("1");
+ container.addComponent(app);
+
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.start();
+ }
+ }, SystemAssemblyException.class);
+
+ container.connectExternalRequired("1",
+ app.getRequiredInterfaces().get(0).getName(), "y");
+
+ ProvidedInterface i = new DefaultProvidedInterface("i",
+ Integer.class);
+ ProvidedInterface x = new DefaultProvidedInterface("x",
+ String.class);
+ ProvidedInterface y = new DefaultProvidedInterface("y",
+ String.class);
+
+ Scope externalScope = new DefaultScope(new ProvidedInterface[0]);
+
+ externalScope.publishInterface(i, 100);
+ externalScope.publishInterface(x, "x-value");
+ externalScope.publishInterface(y, "y-value");
+
+ container.getRequiredInterfaces().get(0).setProvider(i);
+ container.getRequiredInterfaces().get(1).setProvider(x);
+ container.getRequiredInterfaces().get(2).setProvider(y);
+
+ Scope runtime = container.start(externalScope);
+
+ assertEquals("y-value", app.getString());
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNonUniqueRequiredInterfaceWrongNames() {
+ final Container container = new Container("top");
+ container.addRequiredInterface(new DefaultRequiredInterface("i",
+ Integer.class));
+ container.addRequiredInterface(new DefaultRequiredInterface("x",
+ String.class));
+ container.addRequiredInterface(new DefaultRequiredInterface("y",
+ String.class));
+
+ final Application app = new Application("1");
+ container.addComponent(app);
+
+ // wrong component name.
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectExternalRequired("2", "x", "y");
+ }
+ }, SystemAssemblyException.class);
+
+ // Wrong interface name of component.
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectExternalRequired("1",
+ app.getRequiredInterfaces().get(0).getName() + "xxx",
+ "y");
+ }
+ }, SystemAssemblyException.class);
+
+ // Wrong external interface name of container
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectExternalRequired("1",
+ app.getRequiredInterfaces().get(0).getName(), "z");
+ }
+ }, SystemAssemblyException.class);
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNonUniqueProvidedInterface() {
+ final Container container = new Container("top").addProvidedInterface(new DefaultProvidedInterface(
+ "external", String.class));
+ Environment env1 = new Environment("env1");
+ Environment env2 = new Environment("env2");
+
+ container.addComponent(env1);
+ container.addComponent(env2);
+
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.start();
+ }
+ }, SystemAssemblyException.class);
+
+ // now choose env2
+ container.connectExternalProvided(container.getProvidedInterfaces()
+ .get(0).getName(), env2.getName(),
+ env2.getProvidedInterfaces().get(0).getName());
+
+ Scope scope = container.start();
+
+ // check the value of the provided interface of the container
+ String value = scope.getInterfaceImplementation(container.getProvidedInterfaces()
+ .get(0), String.class);
+ assertNotNull(value);
+ assertEquals(value, env2.getString());
+ assertFalse(value.equals(env1.getString()));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNonUniqueProvidedInterfaceWrongNames() {
+ final Container container = new Container("top").addProvidedInterface(new DefaultProvidedInterface(
+ "external", String.class));
+ final Environment env1 = new Environment("env1");
+ final Environment env2 = new Environment("env2");
+
+ container.addComponent(env1);
+ container.addComponent(env2);
+
+ // Wrong external provided interface name
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectExternalProvided(container.getProvidedInterfaces()
+ .get(0).getName() + "xx", "env1",
+ env1.getProvidedInterfaces().get(0).getName());
+ }
+ }, SystemAssemblyException.class);
+
+ // Wrong provided interface name.
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectExternalProvided(container.getProvidedInterfaces()
+ .get(0).getName(), "env1",
+ env1.getProvidedInterfaces().get(0).getName() + "xx");
+ }
+ }, SystemAssemblyException.class);
+
+ // Wrong provided component
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ container.connectExternalProvided(container.getProvidedInterfaces()
+ .get(0).getName(), "env3",
+ env1.getProvidedInterfaces().get(0).getName());
+ }
+ }, SystemAssemblyException.class);
+ }
+
+ private static class MyMultiple implements Serializable, Runnable {
+ @Override
+ public void run() {
+ // Empty
+ }
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import junit.framework.TestCase;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class AbstractComponentTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNotAllInterfacesStarted() {
+ try {
+ Component<?> component = new AbstractComponent<Object>("xx",
+ new ProvidedInterface[] {
+ new DefaultProvidedInterface("xxx", String.class)
+ }, new RequiredInterface[0]) {
+ @Override
+ protected Object doStart(Scope aScope) {
+ // Empty, not starting service.
+ return null;
+ }
- public void testNotAllInterfacesStarted() {
- try {
- Component<?> component = new AbstractComponent<Object>("xx",
- new ProvidedInterface[] { new DefaultProvidedInterface(
- "xxx", String.class) }, new RequiredInterface[0]) {
- @Override
- protected Object doStart(Scope aScope) {
- // Empty, not starting service.
- return null;
- }
+ @Override
+ protected void doStop(Object aRuntime) {
+ // Empty.
+ }
+ };
- @Override
- protected void doStop(Object aRuntime) {
- // Empty.
- }
- };
- component.start(new DefaultScope(component.getProvidedInterfaces()));
- } catch (SystemAssemblyException e) {
- //e.printStackTrace();
- return;
- }
- fail();
- }
-
- public void testUnexpectedServicesStarted() {
- try {
+ component.start(new DefaultScope(component.getProvidedInterfaces()));
+ } catch (SystemAssemblyException e) {
+ //e.printStackTrace();
+ return;
+ }
+
+ fail();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testUnexpectedServicesStarted() {
+ try {
Component<?> component = new AbstractComponent<Object>("xx",
new ProvidedInterface[0], new RequiredInterface[0]) {
- @Override
- protected Object doStart(Scope aScope) {
- addInterface(new DefaultProvidedInterface("x", Integer.class), 100, aScope);
- return null;
- }
+ @Override
+ protected Object doStart(Scope aScope) {
+ addInterface(new DefaultProvidedInterface("x",
+ Integer.class), 100, aScope);
+
+ return null;
+ }
+
+ @Override
+ protected void doStop(Object aRuntime) {
+ // Empty.
+ }
+ };
- @Override
- protected void doStop(Object aRuntime) {
- // Empty.
- }
- };
component.start(new DefaultScope(component.getProvidedInterfaces()));
} catch (SystemAssemblyException e) {
//e.printStackTrace();
return;
}
+
fail();
- }
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
-import java.io.Serializable;
+import junit.framework.TestCase;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
-import junit.framework.TestCase;
+import java.io.Serializable;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DefaultInterfaceDescriptorTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOneRequiredOneProvidedMatch() {
+ ProvidedInterface provided = new DefaultProvidedInterface("name",
+ String.class);
+ RequiredInterface required = new DefaultRequiredInterface("name",
+ String.class);
+ assertTrue(required.implementedBy(provided));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOneRequiredOneProvidedMatchSubClass() {
+ ProvidedInterface provided = new DefaultProvidedInterface("name",
+ Integer.class);
+ RequiredInterface required = new DefaultRequiredInterface("name",
+ Number.class);
+ assertTrue(required.implementedBy(provided));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOneRequiredOneProvidedNoMatch() {
+ ProvidedInterface provided = new DefaultProvidedInterface("name",
+ String.class);
+ RequiredInterface required = new DefaultRequiredInterface("name",
+ Number.class);
+ assertFalse(required.implementedBy(provided));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOneRequiredMultipleProvidedMatch() {
+ ProvidedInterface provided = new DefaultProvidedInterface("name",
+ new Class[] { String.class, Integer.class });
+ RequiredInterface required = new DefaultRequiredInterface("name",
+ String.class);
+ assertTrue(required.implementedBy(provided));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testMultipleRequiredOneProvidedMatch() {
+ ProvidedInterface provided = new DefaultProvidedInterface("name",
+ MyMultiple.class);
+ RequiredInterface required = new DefaultRequiredInterface("name",
+ new Class[] { Runnable.class, Serializable.class });
+ assertTrue(required.implementedBy(provided));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testMultipleRequiredOneProvidedNoMatch() {
+ ProvidedInterface provided = new DefaultProvidedInterface("name",
+ MyMultiple.class);
+ RequiredInterface required = new DefaultRequiredInterface("name",
+ new Class[] { String.class, Runnable.class });
+ assertFalse(required.implementedBy(provided));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testMultipleRequiredMultipleProvidedMatch() {
+ ProvidedInterface provided = new DefaultProvidedInterface("name",
+ new Class[] { Runnable.class, Serializable.class, String.class });
+ RequiredInterface required = new DefaultRequiredInterface("name",
+ new Class[] { Runnable.class, Serializable.class });
+ assertTrue(required.implementedBy(provided));
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testPrimitiveAndWrapperType() {
+ RequiredInterface req1 = new DefaultRequiredInterface("req1", int.class);
+ RequiredInterface req2 = new DefaultRequiredInterface("req1",
+ Integer.class);
+ ProvidedInterface prov1 = new DefaultProvidedInterface("prov1",
+ int.class);
+ ProvidedInterface prov2 = new DefaultProvidedInterface("prov2",
+ Integer.class);
+ assertTrue(req1.implementedBy(prov1));
+ assertTrue(req2.implementedBy(prov1));
+ assertTrue(req1.implementedBy(prov2));
+ assertTrue(req2.implementedBy(prov2));
+ }
- public void testOneRequiredOneProvidedMatch() {
- ProvidedInterface provided = new DefaultProvidedInterface("name", String.class);
- RequiredInterface required = new DefaultRequiredInterface("name", String.class);
- assertTrue(required.implementedBy(provided));
- }
-
- public void testOneRequiredOneProvidedMatchSubClass() {
- ProvidedInterface provided = new DefaultProvidedInterface("name", Integer.class);
- RequiredInterface required = new DefaultRequiredInterface("name", Number.class);
- assertTrue(required.implementedBy(provided));
- }
-
- public void testOneRequiredOneProvidedNoMatch() {
- ProvidedInterface provided = new DefaultProvidedInterface("name", String.class);
- RequiredInterface required = new DefaultRequiredInterface("name", Number.class);
- assertFalse(required.implementedBy(provided));
- }
-
- public void testOneRequiredMultipleProvidedMatch() {
- ProvidedInterface provided = new DefaultProvidedInterface("name",
- new Class[] { String.class, Integer.class} );
- RequiredInterface required = new DefaultRequiredInterface("name", String.class);
- assertTrue(required.implementedBy(provided));
- }
-
- private static class MyMultiple implements Runnable, Serializable {
- @Override
- public void run() {
- // Empty
- }
- }
-
- public void testMultipleRequiredOneProvidedMatch() {
- ProvidedInterface provided = new DefaultProvidedInterface("name",
- MyMultiple.class );
- RequiredInterface required = new DefaultRequiredInterface("name",
- new Class[] {Runnable.class, Serializable.class} );
- assertTrue(required.implementedBy(provided));
- }
-
- public void testMultipleRequiredOneProvidedNoMatch() {
- ProvidedInterface provided = new DefaultProvidedInterface("name",
- MyMultiple.class );
- RequiredInterface required = new DefaultRequiredInterface("name",
- new Class[] { String.class, Runnable.class} );
- assertFalse(required.implementedBy(provided));
- }
-
- public void testMultipleRequiredMultipleProvidedMatch() {
- ProvidedInterface provided = new DefaultProvidedInterface("name",
- new Class[] { Runnable.class, Serializable.class, String.class} );
- RequiredInterface required = new DefaultRequiredInterface("name",
- new Class[] {Runnable.class, Serializable.class} );
- assertTrue(required.implementedBy(provided));
- }
-
- public void testPrimitiveAndWrapperType() {
- RequiredInterface req1 = new DefaultRequiredInterface("req1", int.class);
- RequiredInterface req2 = new DefaultRequiredInterface("req1", Integer.class);
- ProvidedInterface prov1 = new DefaultProvidedInterface("prov1", int.class);
- ProvidedInterface prov2 = new DefaultProvidedInterface("prov2", Integer.class);
- assertTrue(req1.implementedBy(prov1));
- assertTrue(req2.implementedBy(prov1));
- assertTrue(req1.implementedBy(prov2));
- assertTrue(req2.implementedBy(prov2));
- }
-
+ private static class MyMultiple implements Runnable, Serializable {
+ @Override
+ public void run() {
+ // Empty
+ }
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import junit.framework.TestCase;
-public class DefaultRequiredInterfaceTest extends TestCase {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class DefaultRequiredInterfaceTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
public void testEquals() {
- assertFalse(new DefaultRequiredInterface("a", String.class)
- .equals(new DefaultRequiredInterface("a", String.class)));
+ assertFalse(new DefaultRequiredInterface("a", String.class).equals(
+ new DefaultRequiredInterface("a", String.class)));
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
import junit.framework.TestCase;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DefaultScopeTest extends TestCase {
-
- public void testLookup() {
- ProvidedInterface provider = new DefaultProvidedInterface("x", Integer.class);
- Scope scope = new DefaultScope(new ProvidedInterface[0]);
-
+ /**
+ * DOCUMENT ME!
+ */
+ public void testLookup() {
+ ProvidedInterface provider = new DefaultProvidedInterface("x",
+ Integer.class);
+ Scope scope = new DefaultScope(new ProvidedInterface[0]);
+
scope.publishInterface(provider, 100);
- assertEquals(100, scope.getInterfaceImplementation(provider, Integer.class).intValue());
+ assertEquals(100,
+ scope.getInterfaceImplementation(provider, Integer.class).intValue());
}
-
- public void testNestedLookup() {
- ProvidedInterface provider1 = new DefaultProvidedInterface("x", Integer.class);
- Scope parent = new DefaultScope(new ProvidedInterface[0]);
-
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNestedLookup() {
+ ProvidedInterface provider1 = new DefaultProvidedInterface("x",
+ Integer.class);
+ Scope parent = new DefaultScope(new ProvidedInterface[0]);
+
parent.publishInterface(provider1, 100);
-
- ProvidedInterface provider2 = new DefaultProvidedInterface("y", String.class);
- Scope child = new DefaultScope(new ProvidedInterface[0], parent);
-
+
+ ProvidedInterface provider2 = new DefaultProvidedInterface("y",
+ String.class);
+ Scope child = new DefaultScope(new ProvidedInterface[0],
+ parent);
+
child.publishInterface(provider2, "hallo");
-
+
assertFalse(provider1.equals(provider2));
-
- assertEquals(100, child.getInterfaceImplementation(provider1, Integer.class).intValue());
- assertEquals("hallo", child.getInterfaceImplementation(provider2, String.class));
- }
+ assertEquals(100,
+ child.getInterfaceImplementation(provider1, Integer.class).intValue());
+ assertEquals("hallo",
+ child.getInterfaceImplementation(provider2, String.class));
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.core;
-import javax.sql.DataSource;
-
import org.wamblee.system.core.AbstractComponent;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
+
import org.wamblee.test.EventTracker;
+import javax.sql.DataSource;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class Environment extends AbstractComponent<Object> {
+ /**
+ * DOCUMENT ME!
+ */
+ private static int COUNT = 0;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private EventTracker<String> tracker;
- private static final ProvidedInterface[] provided(String aPrefix) {
- return new ProvidedInterface[] {
- new DefaultProvidedInterface(aPrefix + "datasource", String.class),
- new DefaultProvidedInterface(aPrefix + "integer", Integer.class) };
- }
-
- private static int COUNT = 0;
-
- private EventTracker<String> tracker;
- private double random;
- private int integer;
-
- public Environment() {
- this("environment");
- }
-
- public Environment(String aName) {
- this(aName, "");
+ /**
+ * DOCUMENT ME!
+ */
+ private double random;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private int integer;
+
+ /**
+ * Creates a new Environment object.
+ */
+ public Environment() {
+ this("environment");
+ }
+
+ /**
+ * Creates a new Environment object.
+ *
+ * @param aName DOCUMENT ME!
+ */
+ public Environment(String aName) {
+ this(aName, "");
}
-
- public Environment(String aName, String aPrefix) {
+
+ /**
+ * Creates a new Environment object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aPrefix DOCUMENT ME!
+ */
+ public Environment(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
- random = Math.random();
- integer = COUNT++;
+ random = Math.random();
+ integer = COUNT++;
+ }
+
+ /**
+ * Creates a new Environment object.
+ *
+ * @param aTracker DOCUMENT ME!
+ */
+ public Environment(EventTracker aTracker) {
+ this();
+ tracker = aTracker;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPrefix DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private static final ProvidedInterface[] provided(String aPrefix) {
+ return new ProvidedInterface[] {
+ new DefaultProvidedInterface(aPrefix + "datasource", String.class),
+ new DefaultProvidedInterface(aPrefix + "integer", Integer.class)
+ };
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Integer getInteger() {
+ return integer;
+ }
- public Environment(EventTracker aTracker) {
- this();
- tracker = aTracker;
- }
-
- public Integer getInteger() {
- return integer;
- }
-
- public String getString() {
- return getName() + ".hello";
- }
-
- @Override
- protected Object doStart(Scope aScope) {
- addInterface(getProvidedInterfaces().get(0), getString(), aScope);
- addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
- track("start." + getName());
- return random;
- }
-
- @Override
- protected void doStop(Object aRuntime) {
- track("stop." + getName());
- if (random != (Double) aRuntime) {
- throw new IllegalArgumentException("Wrong runtime: expected "
- + random + " but got " + aRuntime);
- }
- }
-
- private void track(String aString) {
- if (tracker == null) {
- return;
- }
- tracker.eventOccurred(aString);
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getString() {
+ return getName() + ".hello";
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ protected Object doStart(Scope aScope) {
+ addInterface(getProvidedInterfaces().get(0), getString(), aScope);
+ addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
+ track("start." + getName());
+
+ return random;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
+ @Override
+ protected void doStop(Object aRuntime) {
+ track("stop." + getName());
+
+ if (random != (Double) aRuntime) {
+ throw new IllegalArgumentException("Wrong runtime: expected "
+ + random + " but got " + aRuntime);
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aString DOCUMENT ME!
+ */
+ private void track(String aString) {
+ if (tracker == null) {
+ return;
+ }
+
+ tracker.eventOccurred(aString);
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.core;
-import javax.sql.DataSource;
-
import org.wamblee.system.core.AbstractComponent;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
+
import org.wamblee.test.EventTracker;
+import javax.sql.DataSource;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class IntegerComponent extends AbstractComponent<Object> {
+ /**
+ * DOCUMENT ME!
+ */
+ private EventTracker<String> tracker;
- private static final ProvidedInterface[] provided(String aPrefix) {
- return new ProvidedInterface[] {
- new DefaultProvidedInterface(aPrefix + "integer", Integer.class) };
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private double random;
- private EventTracker<String> tracker;
- private double random;
+ /**
+ * Creates a new IntegerComponent object.
+ */
+ public IntegerComponent() {
+ this("environment");
+ }
- public IntegerComponent() {
- this("environment");
- }
-
- public IntegerComponent(String aName) {
- this(aName, "");
+ /**
+ * Creates a new IntegerComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ */
+ public IntegerComponent(String aName) {
+ this(aName, "");
}
-
- public IntegerComponent(String aName, String aPrefix) {
+
+ /**
+ * Creates a new IntegerComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aPrefix DOCUMENT ME!
+ */
+ public IntegerComponent(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
random = Math.random();
}
+ /**
+ * Creates a new IntegerComponent object.
+ *
+ * @param aTracker DOCUMENT ME!
+ */
+ public IntegerComponent(EventTracker aTracker) {
+ this();
+ tracker = aTracker;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPrefix DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private static final ProvidedInterface[] provided(String aPrefix) {
+ return new ProvidedInterface[] {
+ new DefaultProvidedInterface(aPrefix + "integer", Integer.class)
+ };
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Integer getInteger() {
+ return 2;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ protected Object doStart(Scope aScope) {
+ addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
+ track("start." + getName());
+
+ return random;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
+ @Override
+ protected void doStop(Object aRuntime) {
+ track("stop." + getName());
+ if (random != (Double) aRuntime) {
+ throw new IllegalArgumentException("Wrong runtime: expected "
+ + random + " but got " + aRuntime);
+ }
+ }
- public IntegerComponent(EventTracker aTracker) {
- this();
- tracker = aTracker;
- }
-
- public Integer getInteger() {
- return 2;
- }
-
- @Override
- protected Object doStart(Scope aScope) {
- addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
- track("start." + getName());
- return random;
- }
-
- @Override
- protected void doStop(Object aRuntime) {
- track("stop." + getName());
- if (random != (Double) aRuntime) {
- throw new IllegalArgumentException("Wrong runtime: expected "
- + random + " but got " + aRuntime);
- }
- }
-
- private void track(String aString) {
- if (tracker == null) {
- return;
- }
- tracker.eventOccurred(aString);
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aString DOCUMENT ME!
+ */
+ private void track(String aString) {
+ if (tracker == null) {
+ return;
+ }
+
+ tracker.eventOccurred(aString);
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.core;
import java.util.Comparator;
-public class RequiredInterfaceComparator implements
- Comparator<RequiredInterface> {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class RequiredInterfaceComparator implements Comparator<RequiredInterface> {
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aO1 DOCUMENT ME!
+ * @param aO2 DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public int compare(RequiredInterface aO1, RequiredInterface aO2) {
return aO1.getName().compareTo(aO2.getName());
}
-
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.core;
-import javax.sql.DataSource;
-
import org.wamblee.system.core.AbstractComponent;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
+
import org.wamblee.test.EventTracker;
+import javax.sql.DataSource;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class StringComponent extends AbstractComponent<Object> {
+ /**
+ * DOCUMENT ME!
+ */
+ private EventTracker<String> tracker;
- private static final ProvidedInterface[] provided(String aPrefix) {
- return new ProvidedInterface[] {
- new DefaultProvidedInterface(aPrefix + "datasource", String.class) };
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private double random;
- private EventTracker<String> tracker;
- private double random;
+ /**
+ * Creates a new StringComponent object.
+ */
+ public StringComponent() {
+ this("environment");
+ }
- public StringComponent() {
- this("environment");
- }
-
- public StringComponent(String aName) {
- this(aName, "");
+ /**
+ * Creates a new StringComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ */
+ public StringComponent(String aName) {
+ this(aName, "");
}
-
- public StringComponent(String aName, String aPrefix) {
+
+ /**
+ * Creates a new StringComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aPrefix DOCUMENT ME!
+ */
+ public StringComponent(String aName, String aPrefix) {
super(aName, provided(aPrefix), new RequiredInterface[0]);
random = Math.random();
}
+ /**
+ * Creates a new StringComponent object.
+ *
+ * @param aTracker DOCUMENT ME!
+ */
+ public StringComponent(EventTracker aTracker) {
+ this();
+ tracker = aTracker;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPrefix DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private static final ProvidedInterface[] provided(String aPrefix) {
+ return new ProvidedInterface[] {
+ new DefaultProvidedInterface(aPrefix + "datasource", String.class)
+ };
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Integer getInteger() {
+ return 2;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String getString() {
+ return getName() + ".hello";
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ protected Object doStart(Scope aScope) {
+ addInterface(getProvidedInterfaces().get(0), getString(), aScope);
+ track("start." + getName());
+ return random;
+ }
- public StringComponent(EventTracker aTracker) {
- this();
- tracker = aTracker;
- }
-
- public Integer getInteger() {
- return 2;
- }
-
- public String getString() {
- return getName() + ".hello";
- }
-
- @Override
- protected Object doStart(Scope aScope) {
- addInterface(getProvidedInterfaces().get(0), getString(), aScope);
- track("start." + getName());
- return random;
- }
-
- @Override
- protected void doStop(Object aRuntime) {
- track("stop." + getName());
- if (random != (Double) aRuntime) {
- throw new IllegalArgumentException("Wrong runtime: expected "
- + random + " but got " + aRuntime);
- }
- }
-
- private void track(String aString) {
- if (tracker == null) {
- return;
- }
- tracker.eventOccurred(aString);
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
+ @Override
+ protected void doStop(Object aRuntime) {
+ track("stop." + getName());
+
+ if (random != (Double) aRuntime) {
+ throw new IllegalArgumentException("Wrong runtime: expected "
+ + random + " but got " + aRuntime);
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aString DOCUMENT ME!
+ */
+ private void track(String aString) {
+ if (tracker == null) {
+ return;
+ }
+
+ tracker.eventOccurred(aString);
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
+import junit.framework.TestCase;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
-import junit.framework.TestCase;
import org.wamblee.system.container.Application;
import org.wamblee.system.core.Component;
import org.wamblee.system.graph.component.ProvidedInterfaceNode;
import org.wamblee.system.graph.component.RequiredInterfaceNode;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class CompositeEdgeFilterTest extends TestCase {
- private Application app = new Application();
+ /**
+ * DOCUMENT ME!
+ */
+ private Application app = new Application();
+
+ /**
+ * DOCUMENT ME!
+ */
private Environment env = new Environment();
-
- private Edge createEdge(Component aClient, RequiredInterface aRequired,
- Component aServer, ProvidedInterface aProvided) {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aClient DOCUMENT ME!
+ * @param aRequired DOCUMENT ME!
+ * @param aServer DOCUMENT ME!
+ * @param aProvided DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private Edge createEdge(Component aClient, RequiredInterface aRequired,
+ Component aServer, ProvidedInterface aProvided) {
Node from = new RequiredInterfaceNode(aClient, aRequired);
- Node to = new ProvidedInterfaceNode(aServer, aProvided);
+ Node to = new ProvidedInterfaceNode(aServer, aProvided);
+
return new DefaultEdge(from, to);
}
- public void testEmpty() {
- EdgeFilter restriction = new CompositeEdgeFilter();
- assertFalse(restriction.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
- env, env.getProvidedInterfaces().get(0))));
+ /**
+ * DOCUMENT ME!
+ */
+ public void testEmpty() {
+ EdgeFilter restriction = new CompositeEdgeFilter();
+ assertFalse(restriction.isViolated(createEdge(app,
+ app.getRequiredInterfaces().get(0), env,
+ env.getProvidedInterfaces().get(0))));
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param base DOCUMENT ME!
+ * @param aResult DOCUMENT ME!
+ */
private void configureRestriction(EdgeFilter base, boolean aResult) {
- stub(base.isViolated((Edge)anyObject())).toReturn(aResult);
+ stub(base.isViolated((Edge) anyObject())).toReturn(aResult);
}
-
- public void testOneRestriction() {
- EdgeFilter base = mock(EdgeFilter.class);
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testOneRestriction() {
+ EdgeFilter base = mock(EdgeFilter.class);
CompositeEdgeFilter composite = new CompositeEdgeFilter();
composite.add(base);
-
+
// First let the base return false and verify the result.
-
configureRestriction(base, false);
-
- assertFalse(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
- env, env.getProvidedInterfaces().get(0))));
-
+
+ assertFalse(composite.isViolated(createEdge(app,
+ app.getRequiredInterfaces().get(0), env,
+ env.getProvidedInterfaces().get(0))));
+
// Second let the base return true and verify the result.
configureRestriction(base, true);
-
- assertTrue(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
- env, env.getProvidedInterfaces().get(0))));
+
+ assertTrue(composite.isViolated(createEdge(app,
+ app.getRequiredInterfaces().get(0), env,
+ env.getProvidedInterfaces().get(0))));
}
-
-
- public void testTwoRestrictions() {
- EdgeFilter base1 = mock(EdgeFilter.class);
+ /**
+ * DOCUMENT ME!
+ */
+ public void testTwoRestrictions() {
+ EdgeFilter base1 = mock(EdgeFilter.class);
CompositeEdgeFilter composite = new CompositeEdgeFilter();
composite.add(base1);
+
EdgeFilter base2 = mock(EdgeFilter.class);
composite.add(base2);
-
+
// 1. base1 not violated and base 2 not violated -> not violated.
-
configureRestriction(base1, false);
configureRestriction(base2, false);
- assertFalse(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
- env, env.getProvidedInterfaces().get(0))));
-
+ assertFalse(composite.isViolated(createEdge(app,
+ app.getRequiredInterfaces().get(0), env,
+ env.getProvidedInterfaces().get(0))));
+
// 2. base 1 not violated but base 2 violated -> violated
configureRestriction(base1, false);
configureRestriction(base2, true);
-
- assertTrue(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
- env, env.getProvidedInterfaces().get(0))));
-
+
+ assertTrue(composite.isViolated(createEdge(app,
+ app.getRequiredInterfaces().get(0), env,
+ env.getProvidedInterfaces().get(0))));
+
// 3. base 1 violated -> violated and base 2 not called.
configureRestriction(base1, true);
// base 2 should not be called.
-
- assertTrue(composite.isViolated(createEdge(app, app.getRequiredInterfaces().get(0),
- env, env.getProvidedInterfaces().get(0))));
+ assertTrue(composite.isViolated(createEdge(app,
+ app.getRequiredInterfaces().get(0), env,
+ env.getProvidedInterfaces().get(0))));
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.graph;
-import java.util.Arrays;
-import java.util.List;
-
+import junit.framework.TestCase;
import static org.mockito.Mockito.*;
+
import org.wamblee.test.AssertionUtils;
+import java.util.Arrays;
+import java.util.List;
-import junit.framework.TestCase;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class GraphTest extends TestCase {
-
+ /**
+ * DOCUMENT ME!
+ */
public void testNodeMgt() {
final Graph graph = new Graph();
assertTrue(graph.getNodes().isEmpty());
// Empty node set.
assertFalse(graph.removeNode(x));
-
- Node y = new DefaultNode("y");
- graph.addNodes(Arrays.asList(new Node[] { x, y} ));
+
+ Node y = new DefaultNode("y");
+ graph.addNodes(Arrays.asList(new Node[] { x, y }));
assertEquals(2, graph.getNodes().size());
-
+
// duplicate node
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- graph.addNode(new DefaultNode("x"));
- }
- }, IllegalArgumentException.class);
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ graph.addNode(new DefaultNode("x"));
+ }
+ }, IllegalArgumentException.class);
}
- public void testEdgeMgt() {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testEdgeMgt() {
final Graph graph = new Graph();
- final Node x = new DefaultNode("x");
- final Node y = new DefaultNode("y");
+ final Node x = new DefaultNode("x");
+ final Node y = new DefaultNode("y");
graph.addNode(x);
graph.addNode(y);
- final Edge e = new DefaultEdge(x, y);
+
+ final Edge e = new DefaultEdge(x, y);
graph.addEdge(e);
assertEquals(Arrays.asList(new Edge[] { e }), graph.getEdges());
-
+
// duplicate edge.
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- graph.addEdge(e);
- }
- }, IllegalArgumentException.class);
-
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ graph.addEdge(e);
+ }
+ }, IllegalArgumentException.class);
+
// Remove node when edge is still present
- AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- graph.removeNode(x);
- }
- }, IllegalArgumentException.class);
-
-
+ AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+ @Override
+ public void run() throws Exception {
+ graph.removeNode(x);
+ }
+ }, IllegalArgumentException.class);
+
Node a = new DefaultNode("a");
graph.addNode(a);
- graph.addEdges(Arrays.asList(new Edge[] { new DefaultEdge(x, a), new DefaultEdge(y, a) }));
+ graph.addEdges(Arrays.asList(
+ new Edge[] { new DefaultEdge(x, a), new DefaultEdge(y, a) }));
assertEquals(3, graph.getEdges().size());
}
-
- public void testExtend() {
- Graph graph = new Graph();
- graph.addNode(new MyNode("x", new String[] { "a", "b"}));
- graph.addNode(new MyNode("y", new String[] { "b", "c"}));
- graph.addNode(new MyNode("z", new String[] { "a", "c"}));
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testExtend() {
+ Graph graph = new Graph();
+ graph.addNode(new MyNode("x", new String[] { "a", "b" }));
+ graph.addNode(new MyNode("y", new String[] { "b", "c" }));
+ graph.addNode(new MyNode("z", new String[] { "a", "c" }));
graph.extend(new MyEdgeFactory());
-
- List<Edge> edges = graph.getEdges();
+
+ List<Edge> edges = graph.getEdges();
assertEquals(12, edges.size()); // 2 outgoing and 2 incoming nodes.
}
-
- public void testApplyFilter() {
- Graph graph = new Graph();
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testApplyFilter() {
+ Graph graph = new Graph();
graph.addNode(new DefaultNode("x"));
graph.addNode(new DefaultNode("y"));
graph.addNode(new DefaultNode("z"));
graph.addEdge(new DefaultEdge(graph.findNode("x"), graph.findNode("y")));
graph.addEdge(new DefaultEdge(graph.findNode("y"), graph.findNode("z")));
graph.addEdge(new DefaultEdge(graph.findNode("z"), graph.findNode("x")));
-
+
assertEquals(3, graph.getEdges().size());
-
- graph.applyFilter(new EdgeFilter() {
- @Override
- public boolean isViolated(Edge aEdge) {
- if (aEdge.getFrom().getName().equals("x")) {
- return false;
+
+ graph.applyFilter(new EdgeFilter() {
+ @Override
+ public boolean isViolated(Edge aEdge) {
+ if (aEdge.getFrom().getName().equals("x")) {
+ return false;
+ }
+
+ return true;
}
- return true;
- }
- });
-
+ });
+
assertEquals(1, graph.getEdges().size());
assertEquals("x", graph.getEdges().get(0).getFrom().getName());
-
}
-
- public void testFindIncomingOutgoing() {
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testFindIncomingOutgoing() {
Graph graph = new Graph();
- Node x = new DefaultNode("x");
- Node y = new DefaultNode("y");
+ Node x = new DefaultNode("x");
+ Node y = new DefaultNode("y");
graph.addNode(x);
graph.addNode(y);
- Edge e = new DefaultEdge(x,y);
+
+ Edge e = new DefaultEdge(x, y);
graph.addEdge(e);
-
+
List<Edge> incoming = graph.findIncoming(x);
- assertTrue(incoming.isEmpty());
+ assertTrue(incoming.isEmpty());
+
List<Edge> outgoing = graph.findOutgoing(x);
assertEquals(1, outgoing.size());
assertSame(e, outgoing.get(0));
-
+
incoming = graph.findIncoming(y);
assertEquals(1, incoming.size());
assertSame(e, incoming.get(0));
-
+
outgoing = graph.findOutgoing(y);
- assertTrue(outgoing.isEmpty());
+ assertTrue(outgoing.isEmpty());
}
-
+
+ /**
+ * DOCUMENT ME!
+ */
public void testAccept() {
- Graph graph = new Graph();
- Node x = new DefaultNode("x");
- Node y = new DefaultNode("y");
- Edge e = new DefaultEdge(x, y);
+ Graph graph = new Graph();
+ Node x = new DefaultNode("x");
+ Node y = new DefaultNode("y");
+ Edge e = new DefaultEdge(x, y);
graph.addNode(x);
graph.addNode(y);
graph.addEdge(e);
- Visitor visitor = mock(Visitor.class);
-
+
+ Visitor visitor = mock(Visitor.class);
+
graph.accept(visitor);
verify(visitor).visitNode(x);
verify(visitor).visitNode(y);
verify(visitor).visitEdge(e);
-
+
verifyNoMoreInteractions(visitor);
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
import java.util.ArrayList;
import java.util.List;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class MyEdgeFactory implements EdgeFactory<MyNode> {
-
- public MyEdgeFactory() {
+ /**
+ * Creates a new MyEdgeFactory object.
+ */
+ public MyEdgeFactory() {
// Empty.
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aFrom DOCUMENT ME!
+ * @param aTo DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public List<Edge> create(MyNode aFrom, MyNode aTo) {
List<Edge> result = new ArrayList<Edge>();
- for (String fromPort: aFrom.getPorts()) {
- for (String toPort: aTo.getPorts()) {
- if ( fromPort.equals(toPort)) {
+
+ for (String fromPort : aFrom.getPorts()) {
+ for (String toPort : aTo.getPorts()) {
+ if (fromPort.equals(toPort)) {
result.add(new DefaultEdge(aFrom, aTo));
}
}
}
-
- return result;
- }
+ return result;
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class MyNode extends DefaultNode {
+ /**
+ * DOCUMENT ME!
+ */
+ private String[] ports;
- private String[] ports;
-
+ /**
+ * Creates a new MyNode object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aPorts DOCUMENT ME!
+ */
public MyNode(String aName, String[] aPorts) {
super(aName);
- ports = aPorts;
+ ports = aPorts;
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public String[] getPorts() {
return ports;
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
-public class ConnectExternalProvidedProvidedEdgeFilterTest extends TestCase {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ConnectExternalProvidedProvidedEdgeFilterTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
private Container container;
+
+ /**
+ * DOCUMENT ME!
+ */
private Component<Object> internal;
+
+ /**
+ * DOCUMENT ME!
+ */
private String externalInterfaceName;
+
+ /**
+ * DOCUMENT ME!
+ */
private String internalComponentName;
+
+ /**
+ * DOCUMENT ME!
+ */
private String internalInterfaceName;
+
+ /**
+ * DOCUMENT ME!
+ */
private Edge edge;
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
- container = new Container("container")
- .addProvidedInterface(new DefaultProvidedInterface("string",
- String.class));
- internal = new Environment("env1");
-
- externalInterfaceName = container.getProvidedInterfaces().get(0)
- .getName();
- internalComponentName = internal.getName();
- internalInterfaceName = internal.getProvidedInterfaces().get(0).getName();
-
- edge = new DefaultEdge(new ExternalProvidedInterfaceNode(container,
- container.getProvidedInterfaces().get(0)),
- new ProvidedInterfaceNode(internal, internal
- .getProvidedInterfaces().get(0)));
+ container = new Container("container")
+ .addProvidedInterface(new DefaultProvidedInterface("string",
+ String.class));
+ internal = new Environment("env1");
+
+ externalInterfaceName = container.getProvidedInterfaces().get(0)
+ .getName();
+ internalComponentName = internal.getName();
+ internalInterfaceName = internal.getProvidedInterfaces().get(0)
+ .getName();
+
+ edge = new DefaultEdge(new ExternalProvidedInterfaceNode(
+ container, container.getProvidedInterfaces().get(0)),
+ new ProvidedInterfaceNode(internal,
+ internal.getProvidedInterfaces().get(0)));
}
+ /**
+ * DOCUMENT ME!
+ */
public void testWrongExternal() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- externalInterfaceName + "x", internalComponentName,
- internalInterfaceName);
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName
+ + "x", internalComponentName, internalInterfaceName);
assertFalse(filter.isViolated(edge));
}
+ /**
+ * DOCUMENT ME!
+ */
public void testRightExternalWrongComponent() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- externalInterfaceName, internalComponentName + "x",
- internalInterfaceName);
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName,
+ internalComponentName + "x", internalInterfaceName);
assertTrue(filter.isViolated(edge));
}
+ /**
+ * DOCUMENT ME!
+ */
public void testRightExternalWrongInternal() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- externalInterfaceName, internalComponentName,
- internalInterfaceName + "x");
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName,
+ internalComponentName, internalInterfaceName + "x");
assertTrue(filter.isViolated(edge));
}
-
- public void testEverythingRight() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- externalInterfaceName, internalComponentName,
- internalInterfaceName);
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testEverythingRight() {
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName,
+ internalComponentName, internalInterfaceName);
assertFalse(filter.isViolated(edge));
}
-
+ /**
+ * DOCUMENT ME!
+ */
public void testWrongEdgeType() {
- EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
- externalInterfaceName, internalComponentName,
- internalInterfaceName);
- DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
+ EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName,
+ internalComponentName, internalInterfaceName);
+ DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
new DefaultNode("y"));
assertFalse(filter.isViolated(edge));
}
-
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import org.wamblee.system.graph.EdgeFilter;
import org.wamblee.system.graph.Node;
-public class ConnectRequiredExternallyRequiredEdgeFilterTest extends TestCase {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ConnectRequiredExternallyRequiredEdgeFilterTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
private Component<?> comp;
+
+ /**
+ * DOCUMENT ME!
+ */
private Container container;
+
+ /**
+ * DOCUMENT ME!
+ */
private Edge edge;
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
- comp = new Application();
- container = new Container("container")
- .addRequiredInterface(new DefaultRequiredInterface("x",
- String.class));
- Node req = new RequiredInterfaceNode(comp, comp
- .getRequiredInterfaces().get(0));
+ comp = new Application();
+ container = new Container("container").addRequiredInterface(new DefaultRequiredInterface(
+ "x", String.class));
+
+ Node req = new RequiredInterfaceNode(comp,
+ comp.getRequiredInterfaces().get(0));
Node external = new ExternalRequiredInterfaceNode(container,
container.getRequiredInterfaces().get(0));
- edge = new DefaultEdge(req, external);
+ edge = new DefaultEdge(req, external);
}
+ /**
+ * DOCUMENT ME!
+ */
public void testRightComponentRightInterface() {
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- comp.getName(), comp.getRequiredInterfaces().get(0).getName(),
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
+ .getName(), comp.getRequiredInterfaces().get(0).getName(),
container.getRequiredInterfaces().get(0).getName());
assertFalse(filter.isViolated(edge));
}
+ /**
+ * DOCUMENT ME!
+ */
public void testWrongInterface() {
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- comp.getName(), comp.getRequiredInterfaces().get(0).getName()
- + "xx", container.getRequiredInterfaces().get(0).getName());
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
+ .getName(),
+ comp.getRequiredInterfaces().get(0).getName() + "xx",
+ container.getRequiredInterfaces().get(0).getName());
assertFalse(filter.isViolated(edge));
}
+ /**
+ * DOCUMENT ME!
+ */
public void testWrongComponent() {
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- comp.getName() + "xx", comp.getRequiredInterfaces().get(0)
- .getName(), container.getRequiredInterfaces().get(0)
- .getName());
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
+ .getName() + "xx",
+ comp.getRequiredInterfaces().get(0).getName(),
+ container.getRequiredInterfaces().get(0).getName());
assertFalse(filter.isViolated(edge));
}
+ /**
+ * DOCUMENT ME!
+ */
public void testWrongExternalInterface() {
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- comp.getName(), comp.getRequiredInterfaces().get(0).getName(),
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
+ .getName(), comp.getRequiredInterfaces().get(0).getName(),
container.getRequiredInterfaces().get(0).getName() + "xx");
assertTrue(filter.isViolated(edge));
}
+ /**
+ * DOCUMENT ME!
+ */
public void testWrongEdgeType() {
- DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
+ DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
new DefaultNode("y"));
- EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
- comp.getName(), comp.getRequiredInterfaces().get(0).getName(),
+ EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp
+ .getName(), comp.getRequiredInterfaces().get(0).getName(),
container.getRequiredInterfaces().get(0).getName());
assertFalse(filter.isViolated(edge));
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.graph.component;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
+import junit.framework.TestCase;
import org.wamblee.system.container.Application;
import org.wamblee.system.core.Environment;
import org.wamblee.system.graph.Edge;
import org.wamblee.system.graph.EdgeFilter;
import org.wamblee.system.graph.Node;
+
import org.wamblee.test.AssertionUtils;
-import junit.framework.TestCase;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
-public class ConnectRequiredProvidedEdgeFilterTest extends TestCase {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ConnectRequiredProvidedEdgeFilterTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
private Application app1 = new Application("app1", "pf1.");
+
+ /**
+ * DOCUMENT ME!
+ */
private Application app2 = new Application("app2", "pf2.");
-
+
+ /**
+ * DOCUMENT ME!
+ */
private Environment env1 = new Environment("env1", "pf3.");
+
+ /**
+ * DOCUMENT ME!
+ */
private Environment env2 = new Environment("env2", "pf4.");
-
-
- private void compare(Boolean[] aExpected, EdgeFilter aRestriction) {
- List<Boolean> result = new ArrayList<Boolean>();
-
-
-
- // order will be:
- // env1, app1
- // env1, app2
- // env2, app1
- // env2, app2
- for (Environment env: new Environment[] { env1, env2} ) {
- for (Application app: new Application[] { app1, app2} ) {
- Node from = new RequiredInterfaceNode(
- app, app.getRequiredInterfaces().get(0));
- Node to = new ProvidedInterfaceNode(
- env, env.getProvidedInterfaces().get(0));
- Edge edge = new DefaultEdge(from, to);
- result.add(aRestriction.isViolated(edge));
- }
- }
-
-
- assertEquals(Arrays.asList(aExpected), result);
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aExpected DOCUMENT ME!
+ * @param aRestriction DOCUMENT ME!
+ */
+ private void compare(Boolean[] aExpected, EdgeFilter aRestriction) {
+ List<Boolean> result = new ArrayList<Boolean>();
+
+ // order will be:
+ // env1, app1
+ // env1, app2
+ // env2, app1
+ // env2, app2
+ for (Environment env : new Environment[] { env1, env2 }) {
+ for (Application app : new Application[] { app1, app2 }) {
+ Node from = new RequiredInterfaceNode(app,
+ app.getRequiredInterfaces().get(0));
+ Node to = new ProvidedInterfaceNode(env,
+ env.getProvidedInterfaces().get(0));
+ Edge edge = new DefaultEdge(from, to);
+ result.add(aRestriction.isViolated(edge));
+ }
+ }
+
+ assertEquals(Arrays.asList(aExpected), result);
}
- public void testNoRestriction() {
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNoRestriction() {
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null, null, null, null);
-
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null,
+ null, null, null);
+ }
+ }, IllegalArgumentException.class);
AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
- @Override
- public void run() throws Exception {
- EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null, null, "x", "y");
- }
- }, IllegalArgumentException.class);
+ @Override
+ public void run() throws Exception {
+ EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null,
+ null, "x", "y");
+ }
+ }, IllegalArgumentException.class);
}
-
- public void testClientServer() {
- EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1", null, "env1", null);
- compare(new Boolean[] { false, false, true, false}, restriction);
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testClientServer() {
+ EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1",
+ null, "env1", null);
+ compare(new Boolean[] { false, false, true, false }, restriction);
}
-
- public void testNoConnectionsAtAll() {
- EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1", null, null, null);
- compare(new Boolean[] { true, false, true, false}, restriction);
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testNoConnectionsAtAll() {
+ EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1",
+ null, null, null);
+ compare(new Boolean[] { true, false, true, false }, restriction);
}
-
- public void testExplicitConfig() {
- app1 = new Application("app1");
- app2 = new Application("app2");
- env1 = new Environment("env1");
- env2 = new Environment("env2");
-
- EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(
- "app2", "string", "env1", "datasource");
- compare(new Boolean[] { false, false, false, true}, restriction);
-
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void testExplicitConfig() {
+ app1 = new Application("app1");
+ app2 = new Application("app2");
+ env1 = new Environment("env1");
+ env2 = new Environment("env2");
+
+ EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app2",
+ "string", "env1", "datasource");
+ compare(new Boolean[] { false, false, false, true }, restriction);
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
+
import java.util.Properties;
-public class ConfiguredProperties extends Properties {
- public ConfiguredProperties(String aProps) throws IOException {
- InputStream is = new ByteArrayInputStream(aProps.getBytes());
- load(is);
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ConfiguredProperties extends Properties {
+/**
+ * Creates a new ConfiguredProperties object.
+ *
+ * @param aProps DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ public ConfiguredProperties(String aProps) throws IOException {
+ InputStream is = new ByteArrayInputStream(aProps.getBytes());
+ load(is);
is.close();
}
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
-import java.util.Properties;
-
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
+import java.util.Properties;
+
+
/**
- * Bean that provides postprocessing of the bean factory based on
- * a given set of properties.
- *
+ * Bean that provides postprocessing of the bean factory based on a given
+ * set of properties.
+ *
* @author Erik Brakkee
*/
class PropertySetter extends PropertyPlaceholderConfigurer {
+/**
+ * Constructs the property setter.
+ * @param aProps Properties.
+ */
+ public PropertySetter(Properties aProps) {
+ String propFile = createPropertyFile(aProps);
+ setLocation(new StringResource(propFile));
+ }
- /**
- * Constructs the property setter.
- * @param aProps Properties.
- */
- public PropertySetter(Properties aProps) {
- String propFile = createPropertyFile(aProps);
- setLocation(new StringResource(propFile));
- }
-
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aProps DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
public static String createPropertyFile(Properties aProps) {
- StringBuffer buf = new StringBuffer();
- for (Object key: aProps.keySet()) {
- buf.append(key);
- buf.append("=");
- buf.append(aProps.get(key));
- buf.append("\n");
- }
+ StringBuffer buf = new StringBuffer();
+
+ for (Object key : aProps.keySet()) {
+ buf.append(key);
+ buf.append("=");
+ buf.append(aProps.get(key));
+ buf.append("\n");
+ }
+
return buf.toString();
}
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
-import java.util.List;
-
import org.springframework.beans.factory.FactoryBean;
+
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.SystemAssemblyException;
+import java.util.List;
+
+
/**
- * Bean which adds a service required by the spring component to
- * the application context so that other spring beans can use it.
- *
+ * Bean which adds a service required by the spring component to the
+ * application context so that other spring beans can use it.
+ *
* @author Erik Brakkee
*/
class RequiredServiceBean implements FactoryBean {
-
- private RequiredInterface _required;
-
- /**
- * Constructs the bean.
- * @param aId Id of the bean in the service registry.
- */
- public RequiredServiceBean(String aId) {
- List<RequiredInterface> required = SpringComponent.THIS.get().getRequiredInterfaces();
- for ( RequiredInterface intf: required) {
- if ( intf.getName().equals(aId)) {
- _required = intf;
- return;
- }
- }
- throw new SystemAssemblyException("Cannot resolve required component '" + aId + "'");
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private RequiredInterface _required;
+
+/**
+ * Constructs the bean.
+ * @param aId Id of the bean in the service registry.
+ */
+ public RequiredServiceBean(String aId) {
+ List<RequiredInterface> required = SpringComponent.THIS.get()
+ .getRequiredInterfaces();
+
+ for (RequiredInterface intf : required) {
+ if (intf.getName().equals(aId)) {
+ _required = intf;
+
+ return;
+ }
+ }
- @Override
- public Object getObject() throws Exception {
- return SpringComponent.SCOPE.get().getInterfaceImplementation(
- _required.getProvider(), Object.class);
- }
+ throw new SystemAssemblyException("Cannot resolve required component '"
+ + aId + "'");
+ }
- @Override
- public Class getObjectType() {
- return null;
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
+ @Override
+ public Object getObject() throws Exception {
+ return SpringComponent.SCOPE.get()
+ .getInterfaceImplementation(_required.getProvider(), Object.class);
+ }
- @Override
- public boolean isSingleton() {
- return true;
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public Class getObjectType() {
+ return null;
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean isSingleton() {
+ return true;
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.RootBeanDefinition;
+
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
+
import org.wamblee.system.core.AbstractComponent;
import org.wamblee.system.core.DefaultScope;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.Scope;
import org.wamblee.system.core.SystemAssemblyException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+
/**
- * Represents a system configured based on spring. The spring config files that
- * are configured should not contain any PropertyPlaceholderConfigurer objects.
- *
+ * Represents a system configured based on spring. The spring config files
+ * that are configured should not contain any PropertyPlaceholderConfigurer
+ * objects.
+ *
* @author Erik Brakkee
*/
public class SpringComponent extends AbstractComponent<Scope> {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final String CONTEXT_KEY = "context";
+
+ /**
+ * DOCUMENT ME!
+ */
+ static final ThreadLocal<SpringComponent> THIS = new ThreadLocal<SpringComponent>();
+
+ /**
+ * DOCUMENT ME!
+ */
+ static final ThreadLocal<Scope> SCOPE = new ThreadLocal<Scope>();
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Properties properties;
- private static final String CONTEXT_KEY = "context";
-
- static final ThreadLocal<SpringComponent> THIS = new ThreadLocal<SpringComponent>();
- static final ThreadLocal<Scope> SCOPE = new ThreadLocal<Scope>();
-
- private Properties properties;
- private String[] configFiles;
- private Map<String, ProvidedInterface> provided;
- private Map<RequiredInterface, String> required;
- private Map<String, Properties> propertyObjects;
-
- /**
- * Constructs a spring system.
- *
- * @param aName
- * Name of the system.
- * @param aConfigFil
- * Spring config files to read.
- * @param aProvided
- * Map of bean name to service descriptor describing the bean
- * names that the spring config files use for each required
- * service.
- * @param aRequired
- * Map of bean name to service descriptor describing the bean
- * names that the spring config files use for each required
- * service.
- */
- public SpringComponent(String aName, String[] aConfigFiles,
- Map<String, ProvidedInterface> aProvided,
- Map<RequiredInterface, String> aRequired) {
- super(aName, aProvided.values().toArray(new ProvidedInterface[0]),
- aRequired.keySet().toArray(new RequiredInterface[0]));
- properties = new Properties();
- configFiles = aConfigFiles;
- provided = aProvided;
- required = aRequired;
- propertyObjects = new HashMap<String, Properties>();
-
- }
-
- /**
- * Must be called to make a property available in the application context.
- *
- * @param aKey
- * Property key.
- * @param aValue
- * Property value.
- */
- public void setProperty(String aKey, String aValue) {
- properties.put(aKey, aValue);
- }
-
- public void addProperties(Properties aProperties) {
- for (Object key : aProperties.keySet()) {
- setProperty((String) key, aProperties.getProperty((String) key));
- }
- }
-
- public void addProperties(String aBeanname, Properties aProperties) {
- propertyObjects.put(aBeanname, aProperties);
- }
-
- public Properties getProperties(String aBeanname) {
- return propertyObjects.get(aBeanname);
- }
-
- @Override
- protected Scope doStart(Scope aExternalScope) {
-
- SpringComponent old = THIS.get();
- Scope oldScope = SCOPE.get();
- THIS.set(this);
- Scope scope = new DefaultScope(getProvidedInterfaces().toArray(new ProvidedInterface[0]), aExternalScope);
- SCOPE.set(scope);
- try {
- GenericApplicationContext parentContext = new GenericApplicationContext();
-
- registerRequiredServices(parentContext);
- registerPropertyObjects(parentContext);
-
- parentContext.refresh();
-
- System.out.println("Parent context " + parentContext);
-
- AbstractApplicationContext context = parseConfigFiles(parentContext);
-
- context
- .addBeanFactoryPostProcessor(new PropertySetter(properties));
- context.refresh();
-
- exposeProvidedServices(context, aExternalScope);
-
- scope.put(CONTEXT_KEY, context);
- return scope;
- } catch (Exception e) {
- throw new SystemAssemblyException(
- "Failed to assemble spring system " + getName(), e);
- } finally {
- THIS.set(old);
- SCOPE.set(oldScope);
- }
- }
-
- private void exposeProvidedServices(AbstractApplicationContext aContext, Scope aScope) {
- // Call addService for each provided service.
-
- for (String name : provided.keySet()) {
- Object svc = aContext.getBean(name);
- if (svc == null) {
- throw new IllegalArgumentException(getQualifiedName() + ": service '"
- + name + "' is null");
- }
- addInterface(provided.get(name), svc, aScope);
- System.out.println("addService " + provided.get(name) + " " + svc);
- }
- }
-
- private AbstractApplicationContext parseConfigFiles(GenericApplicationContext aParentContext) {
- // Parse spring config files
-
- return new ClassPathXmlApplicationContext((String[]) configFiles,
- false, aParentContext);
- }
-
- private void registerRequiredServices(GenericApplicationContext aParentContext) {
- // Register required services in a parent context
- for (RequiredInterface requiredIntf: getRequiredInterfaces()) {
- String beanName = required.get(requiredIntf);
- if ( beanName != null && beanName.length() > 0) {
- ConstructorArgumentValues cargs = new ConstructorArgumentValues();
- cargs.addGenericArgumentValue(requiredIntf.getName());
- BeanDefinition definition = new RootBeanDefinition(
- RequiredServiceBean.class, cargs,
- new MutablePropertyValues());
- aParentContext.registerBeanDefinition(beanName, definition);
- } else {
- // The required interface is not required by the spring config but by the sub-class directly.
- }
- }
- }
-
- private void registerPropertyObjects(GenericApplicationContext aParentContext) {
- for (String beanName: propertyObjects.keySet()) {
+ /**
+ * DOCUMENT ME!
+ */
+ private String[] configFiles;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<String, ProvidedInterface> provided;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<RequiredInterface, String> required;
+
+ /**
+ * DOCUMENT ME!
+ */
+ private Map<String, Properties> propertyObjects;
+
+/**
+ * Constructs a spring system.
+ *
+ * @param aName
+ * Name of the system.
+ * @param aConfigFil
+ * Spring config files to read.
+ * @param aProvided
+ * Map of bean name to service descriptor describing the bean
+ * names that the spring config files use for each required
+ * service.
+ * @param aRequired
+ * Map of bean name to service descriptor describing the bean
+ * names that the spring config files use for each required
+ * service.
+ */
+ public SpringComponent(String aName, String[] aConfigFiles,
+ Map<String, ProvidedInterface> aProvided,
+ Map<RequiredInterface, String> aRequired) {
+ super(aName, aProvided.values().toArray(new ProvidedInterface[0]),
+ aRequired.keySet().toArray(new RequiredInterface[0]));
+ properties = new Properties();
+ configFiles = aConfigFiles;
+ provided = aProvided;
+ required = aRequired;
+ propertyObjects = new HashMap<String, Properties>();
+ }
+
+ /**
+ * Must be called to make a property available in the application
+ * context.
+ *
+ * @param aKey Property key.
+ * @param aValue Property value.
+ */
+ public void setProperty(String aKey, String aValue) {
+ properties.put(aKey, aValue);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aProperties DOCUMENT ME!
+ */
+ public void addProperties(Properties aProperties) {
+ for (Object key : aProperties.keySet()) {
+ setProperty((String) key, aProperties.getProperty((String) key));
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aBeanname DOCUMENT ME!
+ * @param aProperties DOCUMENT ME!
+ */
+ public void addProperties(String aBeanname, Properties aProperties) {
+ propertyObjects.put(aBeanname, aProperties);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aBeanname DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Properties getProperties(String aBeanname) {
+ return propertyObjects.get(aBeanname);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aExternalScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws SystemAssemblyException DOCUMENT ME!
+ */
+ @Override
+ protected Scope doStart(Scope aExternalScope) {
+ SpringComponent old = THIS.get();
+ Scope oldScope = SCOPE.get();
+ THIS.set(this);
+
+ Scope scope = new DefaultScope(getProvidedInterfaces()
+ .toArray(new ProvidedInterface[0]), aExternalScope);
+ SCOPE.set(scope);
+
+ try {
+ GenericApplicationContext parentContext = new GenericApplicationContext();
+
+ registerRequiredServices(parentContext);
+ registerPropertyObjects(parentContext);
+
+ parentContext.refresh();
+
+ System.out.println("Parent context " + parentContext);
+
+ AbstractApplicationContext context = parseConfigFiles(parentContext);
+
+ context.addBeanFactoryPostProcessor(new PropertySetter(properties));
+ context.refresh();
+
+ exposeProvidedServices(context, aExternalScope);
+
+ scope.put(CONTEXT_KEY, context);
+
+ return scope;
+ } catch (Exception e) {
+ throw new SystemAssemblyException(
+ "Failed to assemble spring system " + getName(), e);
+ } finally {
+ THIS.set(old);
+ SCOPE.set(oldScope);
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aContext DOCUMENT ME!
+ * @param aScope DOCUMENT ME!
+ *
+ * @throws IllegalArgumentException DOCUMENT ME!
+ */
+ private void exposeProvidedServices(AbstractApplicationContext aContext,
+ Scope aScope) {
+ // Call addService for each provided service.
+ for (String name : provided.keySet()) {
+ Object svc = aContext.getBean(name);
+
+ if (svc == null) {
+ throw new IllegalArgumentException(getQualifiedName()
+ + ": service '" + name + "' is null");
+ }
+
+ addInterface(provided.get(name), svc, aScope);
+ System.out.println("addService " + provided.get(name) + " " + svc);
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aParentContext DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private AbstractApplicationContext parseConfigFiles(
+ GenericApplicationContext aParentContext) {
+ // Parse spring config files
+ return new ClassPathXmlApplicationContext((String[]) configFiles,
+ false, aParentContext);
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aParentContext DOCUMENT ME!
+ */
+ private void registerRequiredServices(
+ GenericApplicationContext aParentContext) {
+ // Register required services in a parent context
+ for (RequiredInterface requiredIntf : getRequiredInterfaces()) {
+ String beanName = required.get(requiredIntf);
+
+ if ((beanName != null) && (beanName.length() > 0)) {
+ ConstructorArgumentValues cargs = new ConstructorArgumentValues();
+ cargs.addGenericArgumentValue(requiredIntf.getName());
+
+ BeanDefinition definition = new RootBeanDefinition(RequiredServiceBean.class,
+ cargs, new MutablePropertyValues());
+ aParentContext.registerBeanDefinition(beanName, definition);
+ } else {
+ // The required interface is not required by the spring config but by the sub-class directly.
+ }
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aParentContext DOCUMENT ME!
+ */
+ private void registerPropertyObjects(
+ GenericApplicationContext aParentContext) {
+ for (String beanName : propertyObjects.keySet()) {
ConstructorArgumentValues cargs = new ConstructorArgumentValues();
- cargs.addGenericArgumentValue(PropertySetter.createPropertyFile(propertyObjects.get(beanName)));
- BeanDefinition definition = new RootBeanDefinition(
- ConfiguredProperties.class, cargs,
- new MutablePropertyValues());
+ cargs.addGenericArgumentValue(PropertySetter.createPropertyFile(
+ propertyObjects.get(beanName)));
+
+ BeanDefinition definition = new RootBeanDefinition(ConfiguredProperties.class,
+ cargs, new MutablePropertyValues());
aParentContext.registerBeanDefinition(beanName, definition);
}
}
-
- @Override
- protected void doStop(Scope aRuntime) {
- AbstractApplicationContext context = (AbstractApplicationContext)aRuntime.get(CONTEXT_KEY);
- context.close();
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
+ @Override
+ protected void doStop(Scope aRuntime) {
+ AbstractApplicationContext context = (AbstractApplicationContext) aRuntime
+ .get(CONTEXT_KEY);
+ context.close();
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
+import org.springframework.core.io.Resource;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
+
import java.net.URL;
-import org.springframework.core.io.Resource;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
class StringResource implements Resource {
-
- private String _value;
-
- public StringResource(String aValue) {
- _value = aValue;
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private String _value;
- @Override
- public Resource createRelative(String aRelativePath) throws IOException {
- throw new IOException("No relative resource possible");
- }
+/**
+ * Creates a new StringResource object.
+ *
+ * @param aValue DOCUMENT ME!
+ */
+ public StringResource(String aValue) {
+ _value = aValue;
+ }
- @Override
- public boolean exists() {
- return false;
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRelativePath DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ @Override
+ public Resource createRelative(String aRelativePath)
+ throws IOException {
+ throw new IOException("No relative resource possible");
+ }
- @Override
- public String getDescription() {
- return "Properties of a spring component";
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean exists() {
+ return false;
+ }
- @Override
- public File getFile() throws IOException {
- throw new IOException();
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String getDescription() {
+ return "Properties of a spring component";
+ }
- @Override
- public String getFilename() {
- return "springcomponent.properties";
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ @Override
+ public File getFile() throws IOException {
+ throw new IOException();
+ }
- @Override
- public URL getURL() throws IOException {
- throw new IOException();
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public String getFilename() {
+ return "springcomponent.properties";
+ }
- @Override
- public boolean isOpen() {
- return false;
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ @Override
+ public URL getURL() throws IOException {
+ throw new IOException();
+ }
- @Override
- public InputStream getInputStream() throws IOException {
- return new ByteArrayInputStream(_value.getBytes());
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ @Override
+ public boolean isOpen() {
+ return false;
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return new ByteArrayInputStream(_value.getBytes());
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.spring.component;
-import java.io.IOException;
-import java.util.Map;
-import java.util.Properties;
-import java.util.TreeMap;
-
-import javax.sql.DataSource;
-
import org.springframework.core.io.ClassPathResource;
+
import org.springframework.jdbc.datasource.DriverManagerDataSource;
+
import org.wamblee.system.components.ORMappingConfig;
import org.wamblee.system.components.ORMappingConfig.DatabaseType;
import org.wamblee.system.core.AbstractComponent;
import org.wamblee.system.core.Scope;
import org.wamblee.system.spring.SpringComponent;
+import java.io.IOException;
+
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+
+import javax.sql.DataSource;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DatasourceComponent extends AbstractComponent<DataSource> {
+ /**
+ * DOCUMENT ME!
+ */
+ private static RequiredInterface PROPS = new DefaultRequiredInterface("dbprops",
+ Properties.class);
- private static RequiredInterface PROPS = new DefaultRequiredInterface("dbprops", Properties.class);
- private static ProvidedInterface DATASOURCE = new DefaultProvidedInterface("datasource",
+ /**
+ * DOCUMENT ME!
+ */
+ private static ProvidedInterface DATASOURCE = new DefaultProvidedInterface("datasource",
DataSource.class);
+
+ /**
+ * DOCUMENT ME!
+ */
private static ProvidedInterface ORM_CONFIG = new DefaultProvidedInterface("ormconfig",
ORMappingConfig.class);
-
+
+/**
+ * Creates a new DatasourceComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public DatasourceComponent(String aName) throws IOException {
- super(aName);
-
+ super(aName);
+
addRequiredInterface(PROPS);
addProvidedInterface(DATASOURCE);
addProvidedInterface(ORM_CONFIG);
}
-
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected DataSource doStart(Scope aScope) {
- Properties dbProps = aScope.getInterfaceImplementation(
- PROPS.getProvider(), Properties.class);
- DriverManagerDataSource ds = new DriverManagerDataSource(
- dbProps.getProperty("database.url"),
+ Properties dbProps = aScope.getInterfaceImplementation(PROPS
+ .getProvider(), Properties.class);
+ DriverManagerDataSource ds = new DriverManagerDataSource(dbProps
+ .getProperty("database.url"),
dbProps.getProperty("database.username"),
dbProps.getProperty("database.password"));
- addInterface(DATASOURCE, ds, aScope);
- DatabaseType type = DatabaseType.valueOf(dbProps.getProperty("database.type"));
-
- ORMappingConfig config = new ORMappingConfig(true, type);
-
- addInterface(ORM_CONFIG, config, aScope);
-
- return ds;
+ addInterface(DATASOURCE, ds, aScope);
+
+ DatabaseType type = DatabaseType.valueOf(dbProps.getProperty(
+ "database.type"));
+
+ ORMappingConfig config = new ORMappingConfig(true, type);
+
+ addInterface(ORM_CONFIG, config, aScope);
+
+ return ds;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aRuntime DOCUMENT ME!
+ */
@Override
protected void doStop(DataSource aRuntime) {
- // Empty.
+ // Empty.
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring.component;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.sql.DataSource;
-
import org.hibernate.SessionFactory;
+
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.MySQLInnoDBDialect;
+
import org.springframework.orm.hibernate3.HibernateTemplate;
+
import org.springframework.transaction.PlatformTransactionManager;
+
import org.wamblee.persistence.hibernate.HibernateMappingFiles;
+
import org.wamblee.system.components.ORMappingConfig;
import org.wamblee.system.components.ORMappingConfig.DatabaseType;
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.Scope;
import org.wamblee.system.spring.SpringComponent;
-public class HibernateComponent extends SpringComponent {
+import java.io.IOException;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.sql.DataSource;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class HibernateComponent extends SpringComponent {
+ /**
+ * DOCUMENT ME!
+ */
private static final String HIBERNATE_DIALECT_PROP = "hibernate.dialect";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String HIBERNATE_SCHEMAUPDATE_PROP = "hibernate.schemaupdate";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String HIBERNATE_PROPS_KEY = "hibernateProperties";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String HIBERNATE_SPRING_CONFIG = "spring/org.wamblee.system.spring.component.hibernate.xml";
-
- private final RequiredInterface CONFIG = new DefaultRequiredInterface("config", ORMappingConfig.class);
-
- public HibernateComponent(String aName) throws IOException {
- super(aName, new String[] { HIBERNATE_SPRING_CONFIG},
- createProvided(), createRequired());
-
- Properties props = new Properties();
+
+ /**
+ * DOCUMENT ME!
+ */
+ private final RequiredInterface CONFIG = new DefaultRequiredInterface("config",
+ ORMappingConfig.class);
+
+/**
+ * Creates a new HibernateComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ public HibernateComponent(String aName) throws IOException {
+ super(aName, new String[] { HIBERNATE_SPRING_CONFIG },
+ createProvided(), createRequired());
+
+ Properties props = new Properties();
addProperties(HIBERNATE_PROPS_KEY, props);
-
+
addRequiredInterface(CONFIG);
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aExternalScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected Scope doStart(Scope aExternalScope) {
-
- ORMappingConfig config = aExternalScope.getInterfaceImplementation(CONFIG.getProvider(), ORMappingConfig.class);
+ ORMappingConfig config = aExternalScope.getInterfaceImplementation(CONFIG
+ .getProvider(), ORMappingConfig.class);
setProperty(HIBERNATE_SCHEMAUPDATE_PROP, "" + config.isSchemaUpdate());
-
- DatabaseType db = config.getType();
- String dialect = db.handleCases(new DatabaseType.Switch<String>() {
- @Override
- public String handleMySqlInnoDb() {
- return MySQLInnoDBDialect.class.getName();
- }
- @Override
- public String handleDerby() {
- return DerbyDialect.class.getName();
- }
- });
+
+ DatabaseType db = config.getType();
+ String dialect = db.handleCases(new DatabaseType.Switch<String>() {
+ @Override
+ public String handleMySqlInnoDb() {
+ return MySQLInnoDBDialect.class.getName();
+ }
+
+ @Override
+ public String handleDerby() {
+ return DerbyDialect.class.getName();
+ }
+ });
+
getHibernateProperties().put(HIBERNATE_DIALECT_PROP, dialect);
-
-
+
return super.doStart(aExternalScope);
}
-
- private Properties getHibernateProperties() {
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ private Properties getHibernateProperties() {
return getProperties(HIBERNATE_PROPS_KEY);
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private static Map<RequiredInterface, String> createRequired() {
- Map<RequiredInterface,String> required = new HashMap<RequiredInterface, String>();
- required.put(new DefaultRequiredInterface("datasource", DataSource.class), "dataSource");
- required.put(new DefaultRequiredInterface("mappingFiles", HibernateMappingFiles.class),
- "hibernateMappingFiles");
+ Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
+ required.put(new DefaultRequiredInterface("datasource", DataSource.class),
+ "dataSource");
+ required.put(new DefaultRequiredInterface("mappingFiles",
+ HibernateMappingFiles.class), "hibernateMappingFiles");
+
return required;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private static Map<String, ProvidedInterface> createProvided() {
- Map<String,ProvidedInterface> provided = new HashMap<String,ProvidedInterface>();
-
- provided.put("transactionManager", new DefaultProvidedInterface(
- "transactionMgr", PlatformTransactionManager.class));
- provided.put("sessionFactory", new DefaultProvidedInterface(
- "sessionFactory", SessionFactory.class));
- provided.put("org.springframework.orm.hibernate3.HibernateTemplate", new DefaultProvidedInterface(
- "hibernateTemplate", HibernateTemplate.class));
+ Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+
+ provided.put("transactionManager",
+ new DefaultProvidedInterface("transactionMgr",
+ PlatformTransactionManager.class));
+ provided.put("sessionFactory",
+ new DefaultProvidedInterface("sessionFactory", SessionFactory.class));
+ provided.put("org.springframework.orm.hibernate3.HibernateTemplate",
+ new DefaultProvidedInterface("hibernateTemplate",
+ HibernateTemplate.class));
+
return provided;
}
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class BlaService {
- private HelloService hello;
-
- public BlaService(HelloService aService) {
- if ( aService == null ) {
- throw new IllegalArgumentException("helloService is null");
- }
- hello = aService;
- }
-
- public String execute() {
- return hello.say();
- }
-
- public void stop() {
- System.out.println("Blaservice stopping");
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private HelloService hello;
+
+/**
+ * Creates a new BlaService object.
+ *
+ * @param aService DOCUMENT ME!
+ */
+ public BlaService(HelloService aService) {
+ if (aService == null) {
+ throw new IllegalArgumentException("helloService is null");
+ }
+
+ hello = aService;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String execute() {
+ return hello.say();
+ }
+
+ /**
+ * DOCUMENT ME!
+ */
+ public void stop() {
+ System.out.println("Blaservice stopping");
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
+import junit.framework.TestCase;
+
import java.io.IOException;
+
import java.util.Properties;
-import junit.framework.TestCase;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class ConfiguredPropertiesTest extends TestCase {
-
- public void testProps() throws IOException {
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
+ public void testProps() throws IOException {
Properties props = new Properties();
props.put("x", "y");
- props.put("a", "b");
-
- ConfiguredProperties props2 = new ConfiguredProperties(
- PropertySetter.createPropertyFile(props));
-
- assertEquals(props.size(), props2.size());
+ props.put("a", "b");
+
+ ConfiguredProperties props2 = new ConfiguredProperties(PropertySetter
+ .createPropertyFile(props));
+
+ assertEquals(props.size(), props2.size());
assertEquals(props.get("x"), props2.get("x"));
assertEquals(props.get("a"), props2.get("a"));
}
}
-
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class HelloService {
-
- private String msg;
-
- public HelloService(String aMsg) {
- SpringComponentTest.EVENT_TRACKER.eventOccurred(aMsg);
- msg = aMsg;
- }
-
- public String say() {
- return msg;
- }
+ /**
+ * DOCUMENT ME!
+ */
+ private String msg;
+
+/**
+ * Creates a new HelloService object.
+ *
+ * @param aMsg DOCUMENT ME!
+ */
+ public HelloService(String aMsg) {
+ SpringComponentTest.EVENT_TRACKER.eventOccurred(aMsg);
+ msg = aMsg;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public String say() {
+ return msg;
+ }
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import java.util.Properties;
-public class HelloService2 {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class HelloService2 {
+ /**
+ * DOCUMENT ME!
+ */
private Properties props;
+/**
+ * Creates a new HelloService2 object.
+ *
+ * @param aProps DOCUMENT ME!
+ */
public HelloService2(Properties aProps) {
props = aProps;
}
- public Properties getProperties() {
- return props;
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Properties getProperties() {
+ return props;
}
}
/*
* Copyright 2007 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package org.wamblee.system.spring;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
import junit.framework.TestCase;
import org.wamblee.io.ClassPathResource;
+
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.DefaultScope;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
import org.wamblee.system.core.SystemAssemblyException;
+
import org.wamblee.test.EventTracker;
-public class SpringComponentTest extends TestCase {
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class SpringComponentTest extends TestCase {
+ /**
+ * DOCUMENT ME!
+ */
private static final String HELLO_SERVICE_SPRING_XML = "test.org.wamblee.system.spring.xml";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String HELLO_SERVICE_SPRING_WITH_REQS_XML = "test.org.wamblee.system.springWithRequirements.xml";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML = "test.org.wamblee.system.springWithProperties.xml";
+
+ /**
+ * DOCUMENT ME!
+ */
private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 = "test.org.wamblee.system.springWithProperties2.xml";
+ /**
+ * DOCUMENT ME!
+ */
private static final String PROPERTY_FILE = "test.org.wamblee.system.spring.properties";
+ /**
+ * DOCUMENT ME!
+ */
public static EventTracker<String> EVENT_TRACKER;
+ /**
+ * DOCUMENT ME!
+ */
private Scope externalScope;
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
@Override
protected void setUp() throws Exception {
super.setUp();
- EVENT_TRACKER = new EventTracker<String>();
- externalScope = new DefaultScope(new ProvidedInterface[0]);
+ EVENT_TRACKER = new EventTracker<String>();
+ externalScope = new DefaultScope(new ProvidedInterface[0]);
}
+ /**
+ * DOCUMENT ME!
+ */
public void testBlackboxSystem() {
- SpringComponent system = new SpringComponent("system",
+ SpringComponent system = new SpringComponent("system",
new String[] { HELLO_SERVICE_SPRING_XML },
new HashMap<String, ProvidedInterface>(),
new HashMap<RequiredInterface, String>());
- Scope runtime = system.start(externalScope);
- assertEquals(0, externalScope.getProvidedInterfaces().size());
+ Scope runtime = system.start(externalScope);
+ assertEquals(0, externalScope.getProvidedInterfaces().size());
system.stop(runtime);
}
+ /**
+ * DOCUMENT ME!
+ */
public void testOneProvidedService() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("helloService", new DefaultProvidedInterface("hello",
- HelloService.class));
+ provided.put("helloService",
+ new DefaultProvidedInterface("hello", HelloService.class));
- SpringComponent system = new SpringComponent("system",
+ SpringComponent system = new SpringComponent("system",
new String[] { HELLO_SERVICE_SPRING_XML }, provided,
new HashMap<RequiredInterface, String>());
- Scope runtime = system.start(externalScope);
+ Scope runtime = system.start(externalScope);
List<ProvidedInterface> services = runtime.getProvidedInterfaces();
assertEquals(1, services.size());
+
Object service = runtime.getInterfaceImplementation(services.get(0),
Object.class);
assertTrue(service instanceof HelloService);
// BUG; Provided services should be made available in the external
// scope.
- Object service2 = externalScope.getInterfaceImplementation(provided
- .get("helloService"), Object.class);
+ Object service2 = externalScope.getInterfaceImplementation(provided.get(
+ "helloService"), Object.class);
assertSame(service, service2);
assertEquals("Hello world!", ((HelloService) service).say());
system.stop(runtime);
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public void testWithProperties() throws IOException {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("helloService", new DefaultProvidedInterface("hello",
- HelloService.class));
+ provided.put("helloService",
+ new DefaultProvidedInterface("hello", HelloService.class));
+
SpringComponent system = new SpringComponent("system",
new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML },
provided, new HashMap<RequiredInterface, String>());
- Properties props = new Properties();
+ Properties props = new Properties();
props.load(new ClassPathResource(PROPERTY_FILE).getInputStream());
system.addProperties(props);
// unprocessed property
// and another time with the processed property.
assertEquals(1, EVENT_TRACKER.getEventCount());
+
List<ProvidedInterface> services = scope.getProvidedInterfaces();
- assertEquals("Property Value", scope.getInterfaceImplementation(
- services.get(0), HelloService.class).say());
+ assertEquals("Property Value",
+ scope.getInterfaceImplementation(services.get(0), HelloService.class)
+ .say());
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws IOException DOCUMENT ME!
+ */
public void testWithPropertiesAsBean() throws IOException {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("helloService", new DefaultProvidedInterface("hello",
- HelloService2.class));
+ provided.put("helloService",
+ new DefaultProvidedInterface("hello", HelloService2.class));
+
SpringComponent system = new SpringComponent("system",
new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 },
provided, new HashMap<RequiredInterface, String>());
- Properties props = new Properties();
+ Properties props = new Properties();
props.load(new ClassPathResource(PROPERTY_FILE).getInputStream());
system.addProperties("properties", props);
- Scope scope = system.start(externalScope);
+ Scope scope = system.start(externalScope);
List<ProvidedInterface> services = scope.getProvidedInterfaces();
- Properties props2 = scope.getInterfaceImplementation(services.get(0),
- HelloService2.class).getProperties();
+ Properties props2 = scope.getInterfaceImplementation(services
+ .get(0), HelloService2.class).getProperties();
assertEquals(props, props2);
}
+ /**
+ * DOCUMENT ME!
+ */
public void testWithMissingRequirement() {
try {
SpringComponent system = new SpringComponent("system",
// e.printStackTrace();
return;
}
+
fail();
}
+ /**
+ * DOCUMENT ME!
+ */
public void testWithRequirement() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("hello", HelloService.class),
- "helloService");
- SpringComponent system = new SpringComponent("system",
+ "helloService");
+
+ SpringComponent system = new SpringComponent("system",
new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
new HashMap<String, ProvidedInterface>(), required);
- HelloService helloObject = new HelloService("ladida");
+ HelloService helloObject = new HelloService("ladida");
ProvidedInterface helloService = new DefaultProvidedInterface("hello",
HelloService.class);
- Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
+ Scope scope = new DefaultScope(new ProvidedInterface[] {
+ helloService
+ });
scope.publishInterface(helloService, helloObject);
system.getRequiredInterfaces().get(0).setProvider(helloService);
system.stop(runtime);
}
+ /**
+ * DOCUMENT ME!
+ */
public void testWithRequirementAndProvidedService() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("hello", HelloService.class),
- "helloService");
+ "helloService");
+
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("blaService", new DefaultProvidedInterface("bla",
- BlaService.class));
+ provided.put("blaService",
+ new DefaultProvidedInterface("bla", BlaService.class));
- SpringComponent system = new SpringComponent("system",
+ SpringComponent system = new SpringComponent("system",
new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, provided,
required);
- HelloService helloObject = new HelloService("ladida");
+ HelloService helloObject = new HelloService("ladida");
ProvidedInterface helloService = new DefaultProvidedInterface("hello",
HelloService.class);
- Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
+ Scope scope = new DefaultScope(new ProvidedInterface[] {
+ helloService
+ });
scope.publishInterface(helloService, helloObject);
system.getRequiredInterfaces().get(0).setProvider(helloService);
- Scope runtime = system.start(scope);
+
+ Scope runtime = system.start(scope);
ProvidedInterface started = runtime.getProvidedInterfaces().get(0);
- Object impl = runtime.getInterfaceImplementation(started,
+ Object impl = runtime.getInterfaceImplementation(started,
BlaService.class);
assertNotNull(impl);
assertTrue(impl instanceof BlaService);
}
/**
- * Tests a scenario where a subclass of SpringComponent adds a new provided
- * interface where the interface is provided by the subclass itself and not
- * by the spring configs inside.
+ * Tests a scenario where a subclass of SpringComponent adds a new
+ * provided interface where the interface is provided by the subclass
+ * itself and not by the spring configs inside.
*/
public void testWithProvidedFromSubClassNotFromConfig() {
Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
- provided.put("helloService", new DefaultProvidedInterface("hello",
- HelloService.class));
+ provided.put("helloService",
+ new DefaultProvidedInterface("hello", HelloService.class));
- SubSpringComponent system = new SubSpringComponent("system",
+ SubSpringComponent system = new SubSpringComponent("system",
new String[] { HELLO_SERVICE_SPRING_XML }, provided,
new HashMap<RequiredInterface, String>());
- Scope runtime = system.start(externalScope);
+ Scope runtime = system.start(externalScope);
List<ProvidedInterface> services = runtime.getProvidedInterfaces();
assertEquals(2, services.size());
+
Object service = runtime.getInterfaceImplementation(services.get(0),
Object.class);
assertTrue(service instanceof HelloService);
// BUG; Provided services should be made available in the external
// scope.
- Object service2 = externalScope.getInterfaceImplementation(provided
- .get("helloService"), Object.class);
+ Object service2 = externalScope.getInterfaceImplementation(provided.get(
+ "helloService"), Object.class);
assertSame(service, service2);
- Object floatsvc = externalScope.getInterfaceImplementation(system
- .getProvidedInterfaces().get(1), Object.class);
+ Object floatsvc = externalScope.getInterfaceImplementation(system.getProvidedInterfaces()
+ .get(1), Object.class);
assertTrue(floatsvc instanceof Float);
assertTrue((((Float) floatsvc).floatValue() - 100.345f) < 0.00001);
}
/**
- * Tests the spring component with an additional requirement from the subclass
- * which is not required by the spring config files inside.
+ * Tests the spring component with an additional requirement from
+ * the subclass which is not required by the spring config files inside.
*/
public void testWithRequirementFromSubClass() {
Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
required.put(new DefaultRequiredInterface("hello", HelloService.class),
- "helloService");
- SpringComponent system = new SubSpringComponent2("system",
+ "helloService");
+
+ SpringComponent system = new SubSpringComponent2("system",
new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
new HashMap<String, ProvidedInterface>(), required);
- HelloService helloObject = new HelloService("ladida");
+ HelloService helloObject = new HelloService("ladida");
ProvidedInterface helloService = new DefaultProvidedInterface("hello",
HelloService.class);
-
- ProvidedInterface floatService = new DefaultProvidedInterface("float", Float.class);
-
- Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
+
+ ProvidedInterface floatService = new DefaultProvidedInterface("float",
+ Float.class);
+
+ Scope scope = new DefaultScope(new ProvidedInterface[] {
+ helloService
+ });
scope.publishInterface(helloService, helloObject);
scope.publishInterface(floatService, 100.234f);
system.getRequiredInterfaces().get(0).setProvider(helloService);
Scope runtime = system.start(scope);
system.stop(runtime);
-
- assertEquals(100.234f, ((Float)runtime.get("floatValue")).floatValue(), 0.0001f);
- }
+ assertEquals(100.234f,
+ ((Float) runtime.get("floatValue")).floatValue(), 0.0001f);
+ }
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
-import java.util.Map;
-
-
import org.wamblee.system.core.DefaultProvidedInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+import java.util.Map;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class SubSpringComponent extends SpringComponent {
-
- private static ProvidedInterface PROVIDED = new DefaultProvidedInterface("provided", Float.class);
+ /**
+ * DOCUMENT ME!
+ */
+ private static ProvidedInterface PROVIDED = new DefaultProvidedInterface("provided",
+ Float.class);
+/**
+ * Creates a new SubSpringComponent object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aConfigFiles DOCUMENT ME!
+ * @param aProvided DOCUMENT ME!
+ * @param aRequired DOCUMENT ME!
+ */
public SubSpringComponent(String aName, String[] aConfigFiles,
- Map<String, ProvidedInterface> aProvided,
- Map<RequiredInterface, String> aRequired) {
+ Map<String, ProvidedInterface> aProvided,
+ Map<RequiredInterface, String> aRequired) {
super(aName, aConfigFiles, aProvided, aRequired);
addProvidedInterface(PROVIDED);
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aExternalScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected Scope doStart(Scope aExternalScope) {
-
Scope scope = super.doStart(aExternalScope);
addInterface(PROVIDED, 100.345f, aExternalScope);
+
return scope;
}
}
/*
* Copyright 2008 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.wamblee.system.spring;
-import java.util.Map;
-
import org.wamblee.system.core.DefaultRequiredInterface;
import org.wamblee.system.core.ProvidedInterface;
import org.wamblee.system.core.RequiredInterface;
import org.wamblee.system.core.Scope;
+import java.util.Map;
+
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class SubSpringComponent2 extends SpringComponent {
-
- private static RequiredInterface REQUIRED = new DefaultRequiredInterface("required", Float.class);
+ /**
+ * DOCUMENT ME!
+ */
+ private static RequiredInterface REQUIRED = new DefaultRequiredInterface("required",
+ Float.class);
+/**
+ * Creates a new SubSpringComponent2 object.
+ *
+ * @param aName DOCUMENT ME!
+ * @param aConfigFiles DOCUMENT ME!
+ * @param aProvided DOCUMENT ME!
+ * @param aRequired DOCUMENT ME!
+ */
public SubSpringComponent2(String aName, String[] aConfigFiles,
- Map<String, ProvidedInterface> aProvided,
- Map<RequiredInterface, String> aRequired) {
+ Map<String, ProvidedInterface> aProvided,
+ Map<RequiredInterface, String> aRequired) {
super(aName, aConfigFiles, aProvided, aRequired);
addRequiredInterface(REQUIRED);
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aExternalScope DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected Scope doStart(Scope aExternalScope) {
-
Scope scope = super.doStart(aExternalScope);
-
- float value = aExternalScope.getInterfaceImplementation(REQUIRED.getProvider(), Float.class);
+
+ float value = aExternalScope.getInterfaceImplementation(REQUIRED
+ .getProvider(), Float.class);
scope.put("floatValue", value);
+
return scope;
}
}
/*
* Copyright 2005 the original author or authors.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.wamblee.system.spring.component;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-import javax.sql.DataSource;
-
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.dbunit.DatabaseUnitException;
+
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.DatabaseSequenceFilter;
import org.dbunit.database.IDatabaseConnection;
+
import org.dbunit.dataset.FilteredDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.filter.ITableFilter;
+
import org.dbunit.operation.DatabaseOperation;
+
import org.hibernate.SessionFactory;
+
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
+
import org.springframework.context.ApplicationContext;
+
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
+
import org.springframework.orm.hibernate3.HibernateTemplate;
+
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
+
import org.wamblee.test.spring.TestTransactionCallback;
import org.wamblee.test.spring.TestTransactionCallbackWithoutResult;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import javax.sql.DataSource;
+
+
/**
- * Test support class for database testing. Currently, this still requires the
- * spring platform transaction manager and hibernate template.
+ * Test support class for database testing. Currently, this still requires
+ * the spring platform transaction manager and hibernate template.
*/
public class DatabaseTesterComponent {
-
- private static final Log LOG = LogFactory
- .getLog(DatabaseTesterComponent.class);
+ /**
+ * DOCUMENT ME!
+ */
+ private static final Log LOG = LogFactory.getLog(DatabaseTesterComponent.class);
/**
* Schema pattern.
*/
private ApplicationContext context;
+ /**
+ * DOCUMENT ME!
+ */
private HibernateTemplate hibernateTemplate;
+ /**
+ * DOCUMENT ME!
+ */
private PlatformTransactionManager transactionManager;
+ /**
+ * DOCUMENT ME!
+ */
private DataSource dataSource;
+/**
+ * Creates a new DatabaseTesterComponent object.
+ *
+ * @param aHibernateTemplate DOCUMENT ME!
+ * @param aTransactionManager DOCUMENT ME!
+ * @param aDataSource DOCUMENT ME!
+ */
public DatabaseTesterComponent(HibernateTemplate aHibernateTemplate,
- PlatformTransactionManager aTransactionManager,
- DataSource aDataSource) {
- hibernateTemplate = aHibernateTemplate;
- transactionManager = aTransactionManager;
- dataSource = aDataSource;
+ PlatformTransactionManager aTransactionManager, DataSource aDataSource) {
+ hibernateTemplate = aHibernateTemplate;
+ transactionManager = aTransactionManager;
+ dataSource = aDataSource;
}
/**
+ * DOCUMENT ME!
+ *
* @return Hibernate session factory.
*/
protected SessionFactory getSessionFactory() {
/**
* Performs common initialization for test cases:
- * <ul>
- * <li>Cleaning the database. </li>
- * </ul>
- *
+ * <ul>
+ * <li>Cleaning the database.</li>
+ * </ul>
+ *
* @throws Exception
*/
public void setUp() throws Exception {
}
/**
- * Performs common tear down after execution of a test case. Currenlty this
- * method does nothing.
- *
+ * Performs common tear down after execution of a test case.
+ * Currenlty this method does nothing.
+ *
* @throws Exception
*/
protected void tearDown() throws Exception {
}
/**
+ * DOCUMENT ME!
+ *
* @return Transaction manager
*/
protected PlatformTransactionManager getTransactionManager() {
}
/**
+ * DOCUMENT ME!
+ *
* @return Starts a new transaction.
*/
protected TransactionStatus getTransaction() {
/**
* Returns the hibernate template for executing hibernate-specific
* functionality.
- *
+ *
* @return Hibernate template.
*/
public HibernateTemplate getTemplate() {
}
/**
- * Flushes the session. Should be called after some Hibernate work and
- * before JDBC is used to check results.
- *
+ * Flushes the session. Should be called after some Hibernate work
+ * and before JDBC is used to check results.
*/
public void flush() {
getTemplate().flush();
}
/**
- * Flushes the session first and then removes all objects from the Session
- * cache. Should be called after some Hibernate work and before JDBC is used
- * to check results.
- *
+ * Flushes the session first and then removes all objects from the
+ * Session cache. Should be called after some Hibernate work and before
+ * JDBC is used to check results.
*/
public void clear() {
flush();
/**
* Evicts the object from the session. This is essential for the
* implementation of unit tests where first an object is saved and is
- * retrieved later. By removing the object from the session, Hibernate must
- * retrieve the object again from the database.
- *
+ * retrieved later. By removing the object from the session, Hibernate
+ * must retrieve the object again from the database.
+ *
* @param aObject
*/
protected void evict(Object aObject) {
/**
* Gets the connection.
- *
+ *
* @return Connection.
*/
public Connection getConnection() {
return DataSourceUtils.getConnection(getDataSource());
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
public void cleanDatabase() throws SQLException {
-
if (!isDatabaseConfigured()) {
return;
}
String[] tables = getTableNames();
try {
- IDatabaseConnection connection = new DatabaseConnection(
- getConnection());
- ITableFilter filter = new DatabaseSequenceFilter(connection, tables);
- IDataSet dataset = new FilteredDataSet(filter, connection
- .createDataSet(tables));
+ IDatabaseConnection connection = new DatabaseConnection(getConnection());
+ ITableFilter filter = new DatabaseSequenceFilter(connection,
+ tables);
+ IDataSet dataset = new FilteredDataSet(filter,
+ connection.createDataSet(tables));
DatabaseOperation.DELETE_ALL.execute(connection, dataset);
} catch (DatabaseUnitException e) {
}
/**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
* @throws SQLException
*/
public String[] getTableNames() throws SQLException {
-
List<String> result = new ArrayList<String>();
LOG.debug("Getting database table names to clean (schema: '"
- + SCHEMA_PATTERN + "'");
+ + SCHEMA_PATTERN + "'");
+
+ ResultSet tables = getConnection().getMetaData()
+ .getTables(null, SCHEMA_PATTERN, "%", new String[] { "TABLE" });
- ResultSet tables = getConnection().getMetaData().getTables(null,
- SCHEMA_PATTERN, "%", new String[] { "TABLE" });
while (tables.next()) {
String table = tables.getString("TABLE_NAME");
+
// Make sure we do not touch hibernate's specific
// infrastructure tables.
if (!table.toLowerCase().startsWith("hibernate")) {
result.add(table);
LOG.debug("Adding " + table
- + " to list of tables to be cleaned.");
+ + " to list of tables to be cleaned.");
}
}
+
return (String[]) result.toArray(new String[0]);
}
/**
- * @return
+ * DOCUMENT ME!
+ *
+ * @param aTableList DOCUMENT ME!
+ *
* @throws SQLException
*/
public void emptyTables(List aTableList) throws SQLException {
Iterator liTable = aTableList.iterator();
+
while (liTable.hasNext()) {
emptyTable((String) liTable.next());
}
}
/**
- * @return
+ * DOCUMENT ME!
+ *
+ * @param aTable DOCUMENT ME!
+ *
* @throws SQLException
*/
public void emptyTable(String aTable) throws SQLException {
}
/**
- * @return
+ * DOCUMENT ME!
+ *
+ * @param aTable DOCUMENT ME!
+ *
* @throws SQLException
*/
public void dropTable(String aTable) throws SQLException {
/**
* Executes an SQL statement within a transaction.
- *
- * @param aSql
- * SQL statement.
+ *
+ * @param aSql SQL statement.
+ *
* @return Return code of the corresponding JDBC call.
*/
public int executeSql(final String aSql) {
}
/**
- * Executes an SQL statement within a transaction. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * Executes an SQL statement within a transaction. See {@link
+ * #setPreparedParam(int, PreparedStatement, Object)}for details on
* supported argument types.
- *
- * @param aSql
- * SQL statement.
- * @param aArg
- * Argument of the sql statement.
+ *
+ * @param aSql SQL statement.
+ * @param aArg Argument of the sql statement.
+ *
* @return Return code of the corresponding JDBC call.
*/
public int executeSql(final String aSql, final Object aArg) {
}
/**
- * Executes an sql statement. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
- * supported argument types.
- *
- * @param aSql
- * SQL query to execute.
- * @param aArgs
- * Arguments.
+ * Executes an sql statement. See {@link #setPreparedParam(int,
+ * PreparedStatement, Object)}for details on supported argument types.
+ *
+ * @param aSql SQL query to execute.
+ * @param aArgs Arguments.
+ *
* @return Number of rows updated.
*/
public int executeSql(final String aSql, final Object[] aArgs) {
Map results = executeTransaction(new TestTransactionCallback() {
- public Map execute() throws Exception {
- JdbcTemplate template = new JdbcTemplate(getDataSource());
- int result = template.update(aSql, aArgs);
+ public Map execute() throws Exception {
+ JdbcTemplate template = new JdbcTemplate(getDataSource());
+ int result = template.update(aSql,
+ aArgs);
- Map<String, Integer> map = new TreeMap<String, Integer>();
- map.put("result", new Integer(result));
+ Map<String, Integer> map = new TreeMap<String, Integer>();
+ map.put("result", new Integer(result));
- return map;
- }
- });
+ return map;
+ }
+ });
return ((Integer) results.get("result")).intValue();
}
/**
* Executes a transaction with a result.
- *
- * @param aCallback
- * Callback to do your transactional work.
+ *
+ * @param aCallback Callback to do your transactional work.
+ *
* @return Result.
*/
public Object executeTransaction(TransactionCallback aCallback) {
- TransactionTemplate lTemplate = new TransactionTemplate(
- getTransactionManager());
+ TransactionTemplate lTemplate = new TransactionTemplate(getTransactionManager());
+
return lTemplate.execute(aCallback);
}
/**
* Executes a transaction without a result.
- *
- * @param aCallback
- * Callback to do your transactional work. .
+ *
+ * @param aCallback Callback to do your transactional work. .
*/
public void executeTransaction(TransactionCallbackWithoutResult aCallback) {
- TransactionTemplate template = new TransactionTemplate(
- getTransactionManager());
+ TransactionTemplate template = new TransactionTemplate(getTransactionManager());
template.execute(aCallback);
}
/**
- * Executes a transaction with a result, causing the testcase to fail if any
- * type of exception is thrown.
- *
- * @param aCallback
- * Code to be executed within the transaction.
+ * Executes a transaction with a result, causing the testcase to
+ * fail if any type of exception is thrown.
+ *
+ * @param aCallback Code to be executed within the transaction.
+ *
* @return Result.
+ *
+ * @throws RuntimeException DOCUMENT ME!
*/
public Map executeTransaction(final TestTransactionCallback aCallback) {
return (Map) executeTransaction(new TransactionCallback() {
- public Object doInTransaction(TransactionStatus aArg) {
- try {
- return aCallback.execute();
- } catch (Exception e) {
- // test case must fail.
- e.printStackTrace();
- throw new RuntimeException(e);
+ public Object doInTransaction(TransactionStatus aArg) {
+ try {
+ return aCallback.execute();
+ } catch (Exception e) {
+ // test case must fail.
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
}
- }
- });
+ });
}
/**
- * Executes a transaction with a result, causing the testcase to fail if any
- * type of exception is thrown.
- *
- * @param aCallback
- * Code to be executed within the transaction.
+ * Executes a transaction with a result, causing the testcase to
+ * fail if any type of exception is thrown.
+ *
+ * @param aCallback Code to be executed within the transaction.
+ *
+ * @throws RuntimeException DOCUMENT ME!
*/
public void executeTransaction(
- final TestTransactionCallbackWithoutResult aCallback) {
+ final TestTransactionCallbackWithoutResult aCallback) {
executeTransaction(new TransactionCallbackWithoutResult() {
- public void doInTransactionWithoutResult(TransactionStatus aArg) {
- try {
- aCallback.execute();
- } catch (Exception e) {
- // test case must fail.
- throw new RuntimeException(e.getMessage(), e);
+ public void doInTransactionWithoutResult(TransactionStatus aArg) {
+ try {
+ aCallback.execute();
+ } catch (Exception e) {
+ // test case must fail.
+ throw new RuntimeException(e.getMessage(), e);
+ }
}
- }
- });
+ });
}
/**
* Executes an SQL query.
- *
- * @param aSql
- * Query to execute.
+ *
+ * @param aSql Query to execute.
+ *
* @return Result set.
*/
public ResultSet executeQuery(String aSql) {
}
/**
- * Executes a query with a single argument. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * Executes a query with a single argument. See {@link
+ * #setPreparedParam(int, PreparedStatement, Object)}for details on
* supported argument types.
- *
- * @param aSql
- * Query.
- * @param aArg
- * Argument.
+ *
+ * @param aSql Query.
+ * @param aArg Argument.
+ *
* @return Result set.
*/
public ResultSet executeQuery(String aSql, Object aArg) {
}
/**
- * Executes a query. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
- * supported argument types.
- *
- * @param aSql
- * Sql query.
- * @param aArgs
- * Arguments to the query.
+ * Executes a query. See {@link #setPreparedParam(int,
+ * PreparedStatement, Object)}for details on supported argument types.
+ *
+ * @param aSql Sql query.
+ * @param aArgs Arguments to the query.
+ *
* @return Result set.
+ *
+ * @throws RuntimeException DOCUMENT ME!
*/
public ResultSet executeQuery(final String aSql, final Object[] aArgs) {
try {
- Connection connection = getConnection();
+ Connection connection = getConnection();
- PreparedStatement statement = connection.prepareStatement(aSql);
+ PreparedStatement statement = connection.prepareStatement(aSql);
setPreparedParams(aArgs, statement);
return statement.executeQuery();
}
/**
- * Sets the values of a prepared statement. See
- * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+ * Sets the values of a prepared statement. See {@link
+ * #setPreparedParam(int, PreparedStatement, Object)}for details on
* supported argument types.
- *
- * @param aArgs
- * Arguments to the prepared statement.
- * @param aStatement
- * Prepared statement
+ *
+ * @param aArgs Arguments to the prepared statement.
+ * @param aStatement Prepared statement
+ *
* @throws SQLException
*/
private void setPreparedParams(final Object[] aArgs,
- PreparedStatement aStatement) throws SQLException {
+ PreparedStatement aStatement) throws SQLException {
for (int i = 1; i <= aArgs.length; i++) {
setPreparedParam(i, aStatement, aArgs[i - 1]);
}
/**
* Sets a prepared statement parameter.
- *
- * @param aIndex
- * Index of the parameter.
- * @param aStatement
- * Prepared statement.
- * @param aObject
- * Value Must be of type Integer, Long, or String.
+ *
+ * @param aIndex Index of the parameter.
+ * @param aStatement Prepared statement.
+ * @param aObject Value Must be of type Integer, Long, or String.
+ *
* @throws SQLException
*/
private void setPreparedParam(int aIndex, PreparedStatement aStatement,
- Object aObject) throws SQLException {
+ Object aObject) throws SQLException {
if (aObject instanceof Integer) {
aStatement.setInt(aIndex, ((Integer) aObject).intValue());
} else if (aObject instanceof Long) {
aStatement.setString(aIndex, (String) aObject);
} else {
TestCase.fail("Unsupported object type for prepared statement: "
- + aObject.getClass() + " value: " + aObject
- + " statement: " + aStatement);
+ + aObject.getClass() + " value: " + aObject + " statement: "
+ + aStatement);
}
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
private boolean isDatabaseConfigured() {
try {
getDataSource();
} catch (NoSuchBeanDefinitionException e) {
return false;
}
+
return true;
}
/**
+ * DOCUMENT ME!
+ *
* @return Returns the dataSource.
*/
public DataSource getDataSource() {
}
/**
+ * DOCUMENT ME!
+ *
+ * @param aTable DOCUMENT ME!
+ *
* @return
+ *
* @throws SQLException
*/
public int getTableSize(final String aTable) throws SQLException {
-
ResultSet resultSet = executeQuery("select * from " + aTable);
- int count = 0;
+ int count = 0;
while (resultSet.next()) {
count++;
}
+
return count;
}
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aResultSet DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws SQLException DOCUMENT ME!
+ */
public int countResultSet(ResultSet aResultSet) throws SQLException {
int count = 0;
return count;
}
-
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.eclipselink;
-import java.util.Map;
-
import org.dbunit.dataset.filter.ITableFilterSimple;
+
import org.wamblee.support.persistence.JpaCustomizer;
import org.wamblee.support.persistence.PersistenceUnitDescription;
-public class EclipselinkJpaCustomizer implements JpaCustomizer {
+import java.util.Map;
+
- public EclipselinkJpaCustomizer() {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class EclipselinkJpaCustomizer implements JpaCustomizer {
+/**
+ * Creates a new EclipselinkJpaCustomizer object.
+ */
+ public EclipselinkJpaCustomizer() {
// Empty
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPersistenceUnit DOCUMENT ME!
+ * @param aJpaProperties DOCUMENT ME!
+ */
@Override
- public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
+ public void customize(PersistenceUnitDescription aPersistenceUnit,
+ Map<String, String> aJpaProperties) {
// Hack to make JNDI lookup of the datasource work with toplink
- aJpaProperties.put("eclipselink.session.customizer", JndiSessionCustomizer.class
- .getName());
-
+ aJpaProperties.put("eclipselink.session.customizer",
+ JndiSessionCustomizer.class.getName());
+
// DDL generation for toplink
- aJpaProperties.put("eclipselink.ddl-generation", "create-tables");
+ aJpaProperties.put("eclipselink.ddl-generation", "create-tables");
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public ITableFilterSimple getJpaTables() {
return new EclipselinkTables();
}
-
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.eclipselink;
+import org.dbunit.dataset.DataSetException;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
import java.util.Arrays;
import java.util.List;
-import org.dbunit.dataset.DataSetException;
-import org.dbunit.dataset.filter.ITableFilterSimple;
/**
- * Toplink-specific tables.
+ * Toplink-specific tables.
*/
public class EclipselinkTables implements ITableFilterSimple {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final List<String> TABLES = Arrays.asList(new String[] {
+ "SEQUENCE"
+ });
- private static final List<String> TABLES = Arrays.asList(new String[] { "SEQUENCE" } );
-
- public boolean accept(String aTableName) throws DataSetException {
- return TABLES.contains(aTableName);
- }
-
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aTableName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws DataSetException DOCUMENT ME!
+ */
+ public boolean accept(String aTableName) throws DataSetException {
+ return TABLES.contains(aTableName);
+ }
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.eclipselink;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.sessions.DatabaseLogin;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.sessions.server.ServerSession;
-
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+
+
/**
- * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use for clients that would like to use a
- * JTA SE pu instead of a RESOURCE_LOCAL SE pu.
- *
- * This utility also makes sure that using a persistence.xml with a JTA datasource works in a standalone Java SE
- * environment together with our JNDI stub.
+ * See
+ * http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use
+ * for clients that would like to use a JTA SE pu instead of a RESOURCE_LOCAL
+ * SE pu. This utility also makes sure that using a persistence.xml with a
+ * JTA datasource works in a standalone Java SE environment together with our
+ * JNDI stub.
*/
-public class JndiSessionCustomizer
- implements SessionCustomizer {
-
- public JndiSessionCustomizer() {
- // Empty.
- }
-
- /**
- * Get a dataSource connection and set it on the session with lookupType=STRING_LOOKUP
- */
- public void customize(Session session) throws Exception {
- JNDIConnector connector = null;
- Context context = null;
- try {
- context = new InitialContext();
- if(null != context) {
- connector = (JNDIConnector)session.getLogin().getConnector(); // possible CCE
- // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
- // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
- // the COMPOSITE_NAME_LOOKUP being set
- // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
- connector.setLookupType(JNDIConnector.STRING_LOOKUP);
-
- // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
- JNDIConnector writeConnector = (JNDIConnector)session.getLogin().getConnector();
- writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
- JNDIConnector readConnector =
- (JNDIConnector)((DatabaseLogin)((ServerSession)session).getReadConnectionPool().getLogin()).getConnector();
- readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
-
- System.out.println("JndiSessionCustomizer: configured " + connector.getName());
- }
- else {
- throw new Exception("JndiSessionCustomizer: Context is null");
- }
+public class JndiSessionCustomizer implements SessionCustomizer {
+/**
+ * Creates a new JndiSessionCustomizer object.
+ */
+ public JndiSessionCustomizer() {
+ // Empty.
}
- catch(Exception e) {
- e.printStackTrace();
+
+ /**
+ * Get a dataSource connection and set it on the session with
+ * lookupType=STRING_LOOKUP
+ *
+ * @param session DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
+ public void customize(Session session) throws Exception {
+ JNDIConnector connector = null;
+ Context context = null;
+
+ try {
+ context = new InitialContext();
+
+ if (null != context) {
+ connector = (JNDIConnector) session.getLogin().getConnector(); // possible CCE
+ // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
+ // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
+ // the COMPOSITE_NAME_LOOKUP being set
+ // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
+
+ connector.setLookupType(JNDIConnector.STRING_LOOKUP);
+
+ // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
+ JNDIConnector writeConnector = (JNDIConnector) session.getLogin()
+ .getConnector();
+ writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
+
+ JNDIConnector readConnector = (JNDIConnector) ((DatabaseLogin) ((ServerSession) session).getReadConnectionPool()
+ .getLogin()).getConnector();
+ readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
+
+ System.out.println("JndiSessionCustomizer: configured "
+ + connector.getName());
+ } else {
+ throw new Exception("JndiSessionCustomizer: Context is null");
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
- }
-}
\ No newline at end of file
+}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.eclipselink;
import static junit.framework.Assert.assertEquals;
-import javax.persistence.EntityManager;
-import javax.sql.DataSource;
-
import org.dbunit.IDatabaseTester;
+
import org.dbunit.dataset.ITable;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+
import org.wamblee.support.persistence.Database;
import org.wamblee.support.persistence.DatabaseBuilder;
import org.wamblee.support.persistence.DatabaseUtils;
import org.wamblee.support.persistence.DatabaseUtilsTestBase;
import org.wamblee.support.persistence.JpaBuilder;
-import org.wamblee.support.persistence.PersistenceUnitDescription;
import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+
+import javax.persistence.EntityManager;
+
+import javax.sql.DataSource;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DatabaseUtilsTest extends DatabaseUtilsTestBase {
- // Empty, all tests inherited
+ // Empty, all tests inherited
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.eclipselink;
-import javax.persistence.EntityManager;
-import javax.persistence.Persistence;
-import javax.sql.DataSource;
+import static junit.framework.Assert.*;
import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.DatabaseTestCase;
import org.dbunit.IDatabaseTester;
+
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.filter.ITableFilterSimple;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+
import org.wamblee.support.persistence.DatabaseUtils;
import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
import org.wamblee.support.persistence.JpaTester;
import org.wamblee.support.persistence.MyEntityExampleTestBase;
-import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
-import static junit.framework.Assert.*;
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+
+import javax.sql.DataSource;
/**
- * This class shows an example of how to test an entity using jpa.
+ * This class shows an example of how to test an entity using jpa.
*/
public class MyEntityExampleTest extends MyEntityExampleTestBase {
// Empty, all tests are inherited
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence;
import java.util.Arrays;
import java.util.List;
-public class DerbyDatabaseProvider extends AbstractDatabaseProvider {
-
- /**
- * Capabilities of this type of database.
- */
- public static final List<String> CAPABILIITIES =
- Arrays.asList(DatabaseProvider.CAPABILITY_IN_MEMORY, "DERBY");
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class DerbyDatabaseProvider extends AbstractDatabaseProvider {
+ /**
+ * Capabilities of this type of database.
+ */
+ public static final List<String> CAPABILIITIES = Arrays.asList(DatabaseProvider.CAPABILITY_IN_MEMORY,
+ "DERBY");
- public DerbyDatabaseProvider() {
- // Empty
- }
+/**
+ * Creates a new DerbyDatabaseProvider object.
+ */
+ public DerbyDatabaseProvider() {
+ // Empty
+ }
- public Database create() {
- return new DerbyDatabase();
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public Database create() {
+ return new DerbyDatabase();
+ }
- public DatabaseDescription getDescription() {
- return new DatabaseDescription(CAPABILIITIES.toArray(new String[0]),
- "Derby", "In-memory, volatile, set breakpoint to debug");
- }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ public DatabaseDescription getDescription() {
+ return new DatabaseDescription(CAPABILIITIES.toArray(new String[0]),
+ "Derby", "In-memory, volatile, set breakpoint to debug");
+ }
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
protected List<String> getCapabilities() {
- return CAPABILIITIES;
+ return CAPABILIITIES;
}
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.hibernate;
-import java.util.Map;
-
import org.dbunit.dataset.filter.ITableFilterSimple;
+
import org.wamblee.support.persistence.JpaCustomizer;
import org.wamblee.support.persistence.PersistenceUnitDescription;
-public class HibernateJpaCustomizer implements JpaCustomizer {
+import java.util.Map;
+
- public HibernateJpaCustomizer() {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class HibernateJpaCustomizer implements JpaCustomizer {
+/**
+ * Creates a new HibernateJpaCustomizer object.
+ */
+ public HibernateJpaCustomizer() {
// Empty
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPersistenceUnit DOCUMENT ME!
+ * @param aJpaProperties DOCUMENT ME!
+ */
@Override
- public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
+ public void customize(PersistenceUnitDescription aPersistenceUnit,
+ Map<String, String> aJpaProperties) {
// Hibernate: Override transaction type and datasource
aJpaProperties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
aJpaProperties.put("javax.persistence.jtaDataSource", null);
- aJpaProperties.put("javax.persistence.nonJtaDataSource", aPersistenceUnit.getJndiName());
-
+ aJpaProperties.put("javax.persistence.nonJtaDataSource",
+ aPersistenceUnit.getJndiName());
+
// Hibernate schema generation
- aJpaProperties.put("hibernate.hbm2ddl.auto", "create");
+ aJpaProperties.put("hibernate.hbm2ddl.auto", "create");
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public ITableFilterSimple getJpaTables() {
return new HibernateTables();
}
-
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.hibernate;
+import org.dbunit.dataset.DataSetException;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
import java.util.Arrays;
import java.util.List;
-import org.dbunit.dataset.DataSetException;
-import org.dbunit.dataset.filter.ITableFilterSimple;
/**
- * Toplink-specific tables.
+ * Toplink-specific tables.
*/
public class HibernateTables implements ITableFilterSimple {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final List<String> TABLES = Arrays.asList(new String[] { "" });
- private static final List<String> TABLES = Arrays.asList(new String[] { "" } );
-
- public boolean accept(String aTableName) throws DataSetException {
- return TABLES.contains(aTableName);
- }
-
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aTableName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws DataSetException DOCUMENT ME!
+ */
+ public boolean accept(String aTableName) throws DataSetException {
+ return TABLES.contains(aTableName);
+ }
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.hibernate;
import static junit.framework.Assert.assertEquals;
-import javax.persistence.EntityManager;
-import javax.sql.DataSource;
-
import org.dbunit.IDatabaseTester;
+
import org.dbunit.dataset.ITable;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+
import org.wamblee.support.persistence.Database;
import org.wamblee.support.persistence.DatabaseBuilder;
import org.wamblee.support.persistence.DatabaseUtils;
import org.wamblee.support.persistence.DatabaseUtilsTestBase;
import org.wamblee.support.persistence.JpaBuilder;
-import org.wamblee.support.persistence.PersistenceUnitDescription;
import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+
+import javax.persistence.EntityManager;
+
+import javax.sql.DataSource;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DatabaseUtilsTest extends DatabaseUtilsTestBase {
- // Empty, all tests inherited
+ // Empty, all tests inherited
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.hibernate;
-import javax.persistence.EntityManager;
-import javax.persistence.Persistence;
-import javax.sql.DataSource;
+import static junit.framework.Assert.*;
import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.DatabaseTestCase;
import org.dbunit.IDatabaseTester;
+
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.filter.ITableFilterSimple;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+
import org.wamblee.support.persistence.DatabaseUtils;
import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
import org.wamblee.support.persistence.JpaTester;
import org.wamblee.support.persistence.MyEntityExampleTestBase;
-import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
-import static junit.framework.Assert.*;
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+
+import javax.sql.DataSource;
/**
- * This class shows an example of how to test an entity using jpa.
+ * This class shows an example of how to test an entity using jpa.
*/
public class MyEntityExampleTest extends MyEntityExampleTestBase {
// Empty, all tests are inherited
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.toplink;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-
import oracle.toplink.essentials.jndi.JNDIConnector;
import oracle.toplink.essentials.sessions.DatabaseLogin;
import oracle.toplink.essentials.sessions.Session;
import oracle.toplink.essentials.threetier.ServerSession;
import oracle.toplink.essentials.tools.sessionconfiguration.SessionCustomizer;
-
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+
+
/**
- * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use for clients that would like to use a
- * JTA SE pu instead of a RESOURCE_LOCAL SE pu.
- *
- * This utility also makes sure that using a persistence.xml with a JTA datasource works in a standalone Java SE
- * environment together with our JNDI stub.
+ * See
+ * http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use
+ * for clients that would like to use a JTA SE pu instead of a RESOURCE_LOCAL
+ * SE pu. This utility also makes sure that using a persistence.xml with a
+ * JTA datasource works in a standalone Java SE environment together with our
+ * JNDI stub.
*/
-public class JndiSessionCustomizer
- implements SessionCustomizer {
-
- public JndiSessionCustomizer() {
- // Empty.
- }
-
- /**
- * Get a dataSource connection and set it on the session with lookupType=STRING_LOOKUP
- */
- public void customize(Session session) throws Exception {
- JNDIConnector connector = null;
- Context context = null;
- try {
- context = new InitialContext();
- if(null != context) {
- connector = (JNDIConnector)session.getLogin().getConnector(); // possible CCE
- // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
- // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
- // the COMPOSITE_NAME_LOOKUP being set
- // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
- connector.setLookupType(JNDIConnector.STRING_LOOKUP);
-
- // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
- JNDIConnector writeConnector = (JNDIConnector)session.getLogin().getConnector();
- writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
- JNDIConnector readConnector =
- (JNDIConnector)((DatabaseLogin)((ServerSession)session).getReadConnectionPool().getLogin()).getConnector();
- readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
-
- System.out.println("JndiSessionCustomizer: configured " + connector.getName());
- }
- else {
- throw new Exception("JndiSessionCustomizer: Context is null");
- }
+public class JndiSessionCustomizer implements SessionCustomizer {
+/**
+ * Creates a new JndiSessionCustomizer object.
+ */
+ public JndiSessionCustomizer() {
+ // Empty.
}
- catch(Exception e) {
- e.printStackTrace();
+
+ /**
+ * Get a dataSource connection and set it on the session with
+ * lookupType=STRING_LOOKUP
+ *
+ * @param session DOCUMENT ME!
+ *
+ * @throws Exception DOCUMENT ME!
+ */
+ public void customize(Session session) throws Exception {
+ JNDIConnector connector = null;
+ Context context = null;
+
+ try {
+ context = new InitialContext();
+
+ if (null != context) {
+ connector = (JNDIConnector) session.getLogin().getConnector(); // possible CCE
+ // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
+ // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
+ // the COMPOSITE_NAME_LOOKUP being set
+ // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
+
+ connector.setLookupType(JNDIConnector.STRING_LOOKUP);
+
+ // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
+ JNDIConnector writeConnector = (JNDIConnector) session.getLogin()
+ .getConnector();
+ writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
+
+ JNDIConnector readConnector = (JNDIConnector) ((DatabaseLogin) ((ServerSession) session).getReadConnectionPool()
+ .getLogin()).getConnector();
+ readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
+
+ System.out.println("JndiSessionCustomizer: configured "
+ + connector.getName());
+ } else {
+ throw new Exception("JndiSessionCustomizer: Context is null");
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
- }
-}
\ No newline at end of file
+}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.toplink;
-import java.util.Map;
-
import org.dbunit.dataset.filter.ITableFilterSimple;
+
import org.wamblee.support.persistence.JpaCustomizer;
import org.wamblee.support.persistence.PersistenceUnitDescription;
-public class ToplinkJpaCustomizer implements JpaCustomizer {
+import java.util.Map;
+
- public ToplinkJpaCustomizer() {
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
+public class ToplinkJpaCustomizer implements JpaCustomizer {
+/**
+ * Creates a new ToplinkJpaCustomizer object.
+ */
+ public ToplinkJpaCustomizer() {
// Empty
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aPersistenceUnit DOCUMENT ME!
+ * @param aJpaProperties DOCUMENT ME!
+ */
@Override
- public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
+ public void customize(PersistenceUnitDescription aPersistenceUnit,
+ Map<String, String> aJpaProperties) {
// Hack to make JNDI lookup of the datasource work with toplink
- aJpaProperties.put("toplink.session.customizer", JndiSessionCustomizer.class
- .getName());
-
+ aJpaProperties.put("toplink.session.customizer",
+ JndiSessionCustomizer.class.getName());
+
// DDL generation for toplink
- aJpaProperties.put("toplink.ddl-generation", "create-tables");
+ aJpaProperties.put("toplink.ddl-generation", "create-tables");
}
-
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
@Override
public ITableFilterSimple getJpaTables() {
return new ToplinkTables();
}
-
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.toplink;
+import org.dbunit.dataset.DataSetException;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
import java.util.Arrays;
import java.util.List;
-import org.dbunit.dataset.DataSetException;
-import org.dbunit.dataset.filter.ITableFilterSimple;
/**
- * Toplink-specific tables.
+ * Toplink-specific tables.
*/
public class ToplinkTables implements ITableFilterSimple {
+ /**
+ * DOCUMENT ME!
+ */
+ private static final List<String> TABLES = Arrays.asList(new String[] {
+ "SEQUENCE"
+ });
- private static final List<String> TABLES = Arrays.asList(new String[] { "SEQUENCE" } );
-
- public boolean accept(String aTableName) throws DataSetException {
- return TABLES.contains(aTableName);
- }
-
+ /**
+ * DOCUMENT ME!
+ *
+ * @param aTableName DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ *
+ * @throws DataSetException DOCUMENT ME!
+ */
+ public boolean accept(String aTableName) throws DataSetException {
+ return TABLES.contains(aTableName);
+ }
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.toplink;
import static junit.framework.Assert.assertEquals;
-import javax.persistence.EntityManager;
-import javax.sql.DataSource;
-
import org.dbunit.IDatabaseTester;
+
import org.dbunit.dataset.ITable;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+
import org.wamblee.support.persistence.Database;
import org.wamblee.support.persistence.DatabaseBuilder;
import org.wamblee.support.persistence.DatabaseUtils;
import org.wamblee.support.persistence.DatabaseUtilsTestBase;
import org.wamblee.support.persistence.JpaBuilder;
-import org.wamblee.support.persistence.PersistenceUnitDescription;
import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+
+import javax.persistence.EntityManager;
+
+import javax.sql.DataSource;
+
+/**
+ * DOCUMENT ME!
+ *
+ * @author $author$
+ * @version $Revision$
+ */
public class DatabaseUtilsTest extends DatabaseUtilsTestBase {
- // Empty, all tests inherited
+ // Empty, all tests inherited
}
+/*
+ * SCJD assignment, URLyBird, Erik Brakkee.
+ * Candidate ID: sr1399267.
+ */
package org.wamblee.support.persistence.toplink;
-import javax.persistence.EntityManager;
-import javax.persistence.Persistence;
-import javax.sql.DataSource;
+import static junit.framework.Assert.*;
import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.DatabaseTestCase;
import org.dbunit.IDatabaseTester;
+
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.filter.ITableFilterSimple;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+
import org.wamblee.support.persistence.DatabaseUtils;
import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
import org.wamblee.support.persistence.JpaTester;
import org.wamblee.support.persistence.MyEntityExampleTestBase;
-import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
-import static junit.framework.Assert.*;
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+
+import javax.sql.DataSource;
/**
- * This class shows an example of how to test an entity using jpa.
+ * This class shows an example of how to test an entity using jpa.
*/
public class MyEntityExampleTest extends MyEntityExampleTestBase {
// Empty, all tests are inherited