public synchronized void add(RuleCounter counter) {
		countOwlThingContextInitRule += counter.countOwlThingContextInitRule;
		countRootContextInitializationRule += counter.countRootContextInitializationRule;
		countDisjointSubsumerFromMemberRule += counter.countDisjointSubsumerFromMemberRule;
		countContradictionFromNegationRule += counter.countContradictionFromNegationRule;
		countObjectIntersectionFromFirstConjunctRule += counter.countObjectIntersectionFromFirstConjunctRule;
		countObjectIntersectionFromSecondConjunctRule += counter.countObjectIntersectionFromSecondConjunctRule;
		countSuperClassFromSubClassRule += counter.countSuperClassFromSubClassRule;
		countPropagationFromExistentialFillerRule += counter.countPropagationFromExistentialFillerRule;
		countObjectUnionFromDisjunctRule += counter.countObjectUnionFromDisjunctRule;
		countBackwardLinkChainFromBackwardLinkRule += counter.countBackwardLinkChainFromBackwardLinkRule;
		countSubsumerBackwardLinkRule += counter.countSubsumerBackwardLinkRule;
		countContradictionOverBackwardLinkRule += counter.countContradictionOverBackwardLinkRule;
		countContradictionPropagationRule += counter.countContradictionPropagationRule;
		countContradictionCompositionRule += counter.countContradictionCompositionRule;
		countNonReflexiveBackwardLinkCompositionRule += counter.countNonReflexiveBackwardLinkCompositionRule;
		countIndexedObjectIntersectionOfDecomposition += counter.countIndexedObjectIntersectionOfDecomposition;
		countIndexedObjectSomeValuesFromDecomposition += counter.countIndexedObjectSomeValuesFromDecomposition;
		countIndexedObjectComplementOfDecomposition += counter.countIndexedObjectComplementOfDecomposition;
		countIndexedObjectHasSelfDecomposition += counter.countIndexedObjectHasSelfDecomposition;
		countContradictionFromOwlNothingRule += counter.countContradictionFromOwlNothingRule;
		countSubsumerPropagationRule += counter.countSubsumerPropagationRule;
		countReflexiveBackwardLinkCompositionRule += counter.countReflexiveBackwardLinkCompositionRule;
		countPropagationInitializationRule += counter.countPropagationInitializationRule;
		countBackwardLinkFromForwardLinkRule += counter.countBackwardLinkFromForwardLinkRule;
		countComposedFromDecomposedSubsumerRule += counter.countComposedFromDecomposedSubsumerRule;
		countIndexedClassDecompositionRule += counter.countIndexedClassDecompositionRule;
		countIndexedClassFromDefinitionRule += counter.countIndexedClassFromDefinitionRule;
		countEquivalentClassFirstFromSecondRule += counter.countEquivalentClassFirstFromSecondRule;
		countEquivalentClassSecondFromFirstRule += counter.countEquivalentClassSecondFromFirstRule;
	}

Add the values the corresponding values of the given counter

@param counter


private void writeResource(XhtmlWriter writer, Object object) {
        if (object == null) {
            return;
        }
        try {
            if (object instanceof Resource) {
                Resource<?> resource = (Resource<?>) object;
                writer.beginListItem();

                writeResource(writer, resource.getContent());
                writer.writeLinks(resource.getLinks());

                writer.endListItem();
            } else if (object instanceof Resources) {
                Resources<?> resources = (Resources<?>) object;
                // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar

                writer.beginListItem();

                writer.beginUnorderedList();
                Collection<?> content = resources.getContent();
                writeResource(writer, content);
                writer.endUnorderedList();

                writer.writeLinks(resources.getLinks());

                writer.endListItem();
            } else if (object instanceof ResourceSupport) {
                ResourceSupport resource = (ResourceSupport) object;
                writer.beginListItem();

                writeObject(writer, resource);
                writer.writeLinks(resource.getLinks());

                writer.endListItem();
            } else if (object instanceof Collection) {
                Collection<?> collection = (Collection<?>) object;
                for (Object item : collection) {
                    writeResource(writer, item);
                }
            } else { // TODO: write li for simple objects in Resources Collection
                writeObject(writer, object);
            }
        } catch (Exception ex) {
            throw new RuntimeException("failed to transform object " + object, ex);
        }
    }

Recursively converts object to xhtml data.

@param object
to convert
@param writer
to write to

Recursively converts object to xhtml data .


@Override
    public ActionInputParameter getActionInputParameter(String name) {
        ActionInputParameter ret = requestParams.get(name);
        if (ret == null) {
            ret = pathVariables.get(name);
        }
        if (ret == null) {
            for (ActionInputParameter annotatedParameter : getInputParameters()) {
                // TODO create ActionInputParameter for bean property at property path
                // TODO field access in addition to bean?
                PropertyDescriptor pd = getPropertyDescriptorForPropertyPath(name,
                        annotatedParameter.getParameterType());
                if (pd != null) {
                    if (pd.getWriteMethod() != null) {

                        Object callValue = annotatedParameter.getValue();
                        Object propertyValue = null;
                        if (callValue != null) {
                            BeanWrapper beanWrapper = PropertyAccessorFactory
                                    .forBeanPropertyAccess(callValue);
                            propertyValue = beanWrapper.getPropertyValue(name);
                        }
                        ret = new SpringActionInputParameter(new MethodParameter(pd
                                .getWriteMethod(), 0), propertyValue);
                    }
                    break;
                }
            }
        }
        return ret;
    }

Gets input parameter info which is part of the URL mapping, be it request parameters, path variables or request
body attributes.

@param name
to retrieve
@return parameter descriptor or null

Gets input parameter info which is part of the URL mapping be it request parameters path variables or request body attributes .


PropertyDescriptor getPropertyDescriptorForPropertyPath(String propertyPath, Class<?> propertyType) {
        int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
        // Handle nested properties recursively.
        if (pos > -1) {
            String nestedProperty = propertyPath.substring(0, pos);
            String nestedPath = propertyPath.substring(pos + 1);
            PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(propertyType, nestedProperty);
//            BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty);
            return getPropertyDescriptorForPropertyPath(nestedPath, propertyDescriptor.getPropertyType());
        } else {
            return BeanUtils.getPropertyDescriptor(propertyType, propertyPath);
        }
    }

Recursively navigate to return a BeanWrapper for the nested property path.

@param propertyPath
property property path, which may be nested
@return a BeanWrapper for the target bean

Recursively navigate to return a BeanWrapper for the nested property path .


@Override
    public Map<String, ActionInputParameter> getRequiredParameters() {
        Map<String, ActionInputParameter> ret = new HashMap<String, ActionInputParameter>();
        for (Map.Entry<String, ActionInputParameter> entry : requestParams.entrySet()) {
            ActionInputParameter annotatedParameter = entry.getValue();
            if (annotatedParameter.isRequired()) {
                ret.put(entry.getKey(), annotatedParameter);
            }
        }
        for (Map.Entry<String, ActionInputParameter> entry : pathVariables.entrySet()) {
            ActionInputParameter annotatedParameter = entry.getValue();
            ret.put(entry.getKey(), annotatedParameter);
        }
        // requestBody not supported, would have to use exploded modifier
        return ret;
    }

Determines action input parameters for required url variables.

@return required url variables

Determines action input parameters for required url variables .


public static boolean isSingleValueType(Class<?> clazz) {
        boolean ret;
        if (isNumber(clazz)
                || isBoolean(clazz)
                || isString(clazz)
                || isEnum(clazz)
                || isDate(clazz)
                || isCalendar(clazz)
                || isCurrency(clazz)
                ) {
            ret = true;
        } else {
            ret = false;
        }
        return ret;
    }

public static boolean isSingleValueType ( Class < ? > clazz ) { boolean ret ; if ( isNumber ( clazz ) || isBoolean ( clazz ) || isString ( clazz ) || isEnum ( clazz ) || isDate ( clazz ) || isCalendar ( clazz ) || isCurrency ( clazz ) ) { ret = true ; } else { ret = false ; } return ret ; }

Determines if the given class holds only one data item. Can be useful to determine if a value should be rendered
as scalar.

@param clazz
to check
@return true if class is scalar

Determines if the given class holds only one data item . Can be useful to determine if a value should be rendered as scalar .


public void addRel(String rel) {
        Assert.hasLength(rel);
        linkParams.add(REL.paramName, rel);
    }

public void addRel ( String rel ) { Assert . hasLength ( rel ) ; linkParams . add ( REL . paramName , rel ) ; }

The relation type of the link.

@param rel IANA-registered type or extension relation type.


public void setType(String mediaType) {
        if (mediaType != null)
            linkParams.set(TYPE.paramName, mediaType);
        else
            linkParams.remove(TYPE.paramName);
    }

public void setType ( String mediaType ) { if ( mediaType != null ) linkParams . set ( TYPE . paramName , mediaType ) ; else linkParams . remove ( TYPE . paramName ) ; }

The "type" parameter, when present, is a hint indicating what the media type of the result of dereferencing the
link should be.  Note that this is only a hint; for example, it does not override the Content-Type header of a
HTTP response obtained by actually following the link.  There MUST NOT be more than one type parameter in a link-
value.

@param mediaType to set

The type parameter when present is a hint indicating what the media type of the result of dereferencing the link should be . Note that this is only a hint ; for example it does not override the Content - Type header of a HTTP response obtained by actually following the link . There MUST NOT be more than one type parameter in a link - value .


public void addHreflang(String hreflang) {
        Assert.hasLength(hreflang);
        linkParams.add(HREFLANG.paramName, hreflang);
    }

public void addHreflang ( String hreflang ) { Assert . hasLength ( hreflang ) ; linkParams . add ( HREFLANG . paramName , hreflang ) ; }

The "hreflang" parameter, when present, is a hint indicating what the language of the result of dereferencing the
link should be.  Note that this is only a hint; for example, it does not override the Content-Language header of
a HTTP response obtained by actually following the link.  Multiple "hreflang" parameters on a single link- value
indicate that multiple languages are available from the indicated resource.

@param hreflang to add

The hreflang parameter when present is a hint indicating what the language of the result of dereferencing the link should be . Note that this is only a hint ; for example it does not override the Content - Language header of a HTTP response obtained by actually following the link . Multiple hreflang parameters on a single link - value indicate that multiple languages are available from the indicated resource .


public void addRev(String rev) {
        Assert.hasLength(rev);
        linkParams.add(REV.paramName, rev);
    }

public void addRev ( String rev ) { Assert . hasLength ( rev ) ; linkParams . add ( REV . paramName , rev ) ; }

The "rev" parameter has been used in the past to indicate that the semantics of the relationship are in the
reverse direction.  That is, a link from A to B with REL="X" expresses the same relationship as a link from B to
A with REV="X". "rev" is deprecated by this specification because it often confuses authors and readers; in most
cases, using a separate relation type is preferable.

@param rev to add

The rev parameter has been used in the past to indicate that the semantics of the relationship are in the reverse direction . That is a link from A to B with REL = X expresses the same relationship as a link from B to A with REV = X . rev is deprecated by this specification because it often confuses authors and readers ; in most cases using a separate relation type is preferable .


public void addLinkParam(String paramName, String... values) {
        Assert.notEmpty(values);
        for (String value : values) {
            Assert.hasLength(value);
            linkParams.add(paramName, value);
        }
    }

public void addLinkParam ( String paramName , String ... values ) { Assert . notEmpty ( values ) ; for ( String value : values ) { Assert . hasLength ( value ) ; linkParams . add ( paramName , value ) ; } }

Adds link-extension params, i.e. custom params which are not described in the web linking rfc.

@param paramName of link-extension
@param values    one or more values to add

Adds link - extension params i . e . custom params which are not described in the web linking rfc .


@Override
    public Affordance expand(Map<String, ? extends Object> arguments) {
        UriTemplate template = new UriTemplate(partialUriTemplate.asComponents()
                .toString());
        String expanded = template.expand(arguments)
                .toASCIIString();
        return new Affordance(expanded, linkParams, actionDescriptors);
    }

@ Override public Affordance expand ( Map < String , ? extends Object > arguments ) { UriTemplate template = new UriTemplate ( partialUriTemplate . asComponents ( ) . toString ( ) ) ; String expanded = template . expand ( arguments ) . toASCIIString ( ) ; return new Affordance ( expanded , linkParams , actionDescriptors ) ; }

Expands template variables, arguments must satisfy all required template variables, unsatisfied optional
arguments will be removed.

@param arguments to expansion
@return expanded affordance

Expands template variables arguments must satisfy all required template variables unsatisfied optional arguments will be removed .


@JsonIgnore
    public List<String> getRels() {
        final List<String> rels = linkParams.get(REL.paramName);
        return rels == null ? Collections.<String>emptyList() : Collections.unmodifiableList(rels);
    }

@ JsonIgnore public List < String > getRels ( ) { final List < String > rels = linkParams . get ( REL . paramName ) ; return rels == null ? Collections . < String > emptyList ( ) : Collections . unmodifiableList ( rels ) ; }

Allows to retrieve all rels defined for this affordance.

@return rels

Allows to retrieve all rels defined for this affordance .


@JsonIgnore
    public List<String> getRevs() {
        final List<String> revs = linkParams.get(REV.paramName);
        return revs == null ? Collections.<String>emptyList() : Collections.unmodifiableList(revs);
    }

@ JsonIgnore public List < String > getRevs ( ) { final List < String > revs = linkParams . get ( REV . paramName ) ; return revs == null ? Collections . < String > emptyList ( ) : Collections . unmodifiableList ( revs ) ; }

Retrieves all revs for this affordance.

@return revs

Retrieves all revs for this affordance .


@JsonIgnore
    public boolean hasUnsatisfiedRequiredVariables() {

        for (ActionDescriptor actionDescriptor : actionDescriptors) {
            Map<String, ActionInputParameter> requiredParameters =
                    actionDescriptor.getRequiredParameters();
            for (ActionInputParameter annotatedParameter : requiredParameters.values()) {
                if (!annotatedParameter.hasValue()) {
                    return true;
                }
            }
        }
        return false;
    }

@ JsonIgnore public boolean hasUnsatisfiedRequiredVariables ( ) { for ( ActionDescriptor actionDescriptor : actionDescriptors ) { Map < String , ActionInputParameter > requiredParameters = actionDescriptor . getRequiredParameters ( ) ; for ( ActionInputParameter annotatedParameter : requiredParameters . values ( ) ) { if ( ! annotatedParameter . hasValue ( ) ) { return true ; } } } return false ; }

Determines if the affordance has unsatisfied required variables. This allows to decide if the affordance can also
be treated as a plain Link without template variables if the caller omits all optional variables. Serializers can
use this to render it as a resource with optional search features.

@return true if the affordance has unsatisfied required variables

Determines if the affordance has unsatisfied required variables . This allows to decide if the affordance can also be treated as a plain Link without template variables if the caller omits all optional variables . Serializers can use this to render it as a resource with optional search features .


public String getValueFormatted() {
        String ret;
        if (value == null) {
            ret = null;
        } else {
            ret = (String) conversionService.convert(value, typeDescriptor, TypeDescriptor.valueOf(String.class));
        }
        return ret;
    }

public String getValueFormatted ( ) { String ret ; if ( value == null ) { ret = null ; } else { ret = ( String ) conversionService . convert ( value , typeDescriptor , TypeDescriptor . valueOf ( String . class ) ) ; } return ret ; }

The value of the parameter at sample invocation time, formatted according to conversion configuration.

@return value, may be null

The value of the parameter at sample invocation time formatted according to conversion configuration .


@Override
    public boolean isHidden(String property) {
        Annotation[] paramAnnotations = methodParameter.getParameterAnnotations();
        Input inputAnnotation = methodParameter.getParameterAnnotation(Input.class);
        return inputAnnotation != null && arrayContains(inputAnnotation.hidden(), property);
    }

@ Override public boolean isHidden ( String property ) { Annotation [ ] paramAnnotations = methodParameter . getParameterAnnotations ( ) ; Input inputAnnotation = methodParameter . getParameterAnnotation ( Input . class ) ; return inputAnnotation != null && arrayContains ( inputAnnotation . hidden ( ) , property ) ; }

Determines if request body input parameter has a hidden input property.

@param property name or property path
@return true if hidden

Determines if request body input parameter has a hidden input property .


private boolean containsPropertyIncludeValue(String property) {
        return arrayContains(inputAnnotation.readOnly(), property)
                || arrayContains(inputAnnotation.hidden(), property)
                || arrayContains(inputAnnotation.include(), property);
    }

private boolean containsPropertyIncludeValue ( String property ) { return arrayContains ( inputAnnotation . readOnly ( ) , property ) || arrayContains ( inputAnnotation . hidden ( ) , property ) || arrayContains ( inputAnnotation . include ( ) , property ) ; }

Find out if property is included by searching through all annotations.

@param property
@return

Find out if property is included by searching through all annotations .


private boolean hasExplicitOrImplicitPropertyIncludeValue() {
        // TODO maybe not a useful optimization
        return inputAnnotation != null && inputAnnotation.readOnly().length > 0
                || inputAnnotation.hidden().length > 0
                || inputAnnotation.include().length > 0;
    }

Has any explicit include value or might have implicit includes because there is a hidden or readOnly flag.

@return true if explicitly or implicitly included.

Has any explicit include value or might have implicit includes because there is a hidden or readOnly flag .


public boolean isRequired() {
        boolean ret;
        if (isRequestBody()) {
            ret = requestBody.required();
        } else if (isRequestParam()) {
            ret = !(isDefined(requestParam.defaultValue()) || !requestParam.required());
        } else if (isRequestHeader()) {
            ret = !(isDefined(requestHeader.defaultValue()) || !requestHeader.required());
        } else {
            ret = true;
        }
        return ret;
    }

public boolean isRequired ( ) { boolean ret ; if ( isRequestBody ( ) ) { ret = requestBody . required ( ) ; } else if ( isRequestParam ( ) ) { ret = ! ( isDefined ( requestParam . defaultValue ( ) ) || ! requestParam . required ( ) ) ; } else if ( isRequestHeader ( ) ) { ret = ! ( isDefined ( requestHeader . defaultValue ( ) ) || ! requestHeader . required ( ) ) ; } else { ret = true ; } return ret ; }

Is this action input parameter required, based on the presence of a default value, the parameter annotations and
the kind of input parameter.

@return true if required

Is this action input parameter required based on the presence of a default value the parameter annotations and the kind of input parameter .


public String getDefaultValue() {
        String ret;
        if (isRequestParam()) {
            ret = isDefined(requestParam.defaultValue()) ?
                    requestParam.defaultValue() : null;
        } else if (isRequestHeader()) {
            ret = !(ValueConstants.DEFAULT_NONE.equals(requestHeader.defaultValue())) ?
                    requestHeader.defaultValue() : null;
        } else {
            ret = null;
        }
        return ret;
    }

public String getDefaultValue ( ) { String ret ; if ( isRequestParam ( ) ) { ret = isDefined ( requestParam . defaultValue ( ) ) ? requestParam . defaultValue ( ) : null ; } else if ( isRequestHeader ( ) ) { ret = ! ( ValueConstants . DEFAULT_NONE . equals ( requestHeader . defaultValue ( ) ) ) ? requestHeader . defaultValue ( ) : null ; } else { ret = null ; } return ret ; }

Determines default value of request param or request header, if available.

@return value or null

Determines default value of request param or request header if available .


@Override
    public String getParameterName() {
        String ret = null;
        if (requestParam != null) {
            String requestParamName = requestParam.value();
            if (!requestParamName.isEmpty())
                ret = requestParamName;
        }
        if (pathVariable != null) {
            String pathVariableName = pathVariable.value();
            if (!pathVariableName.isEmpty())
                ret = pathVariableName;
        }
        if (ret == null) {
            String parameterName = methodParameter.getParameterName();
            if (parameterName == null) {
                methodParameter.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
                ret = methodParameter.getParameterName();
            } else {
                ret = parameterName;
            }
        }
        return ret;
    }

Gets request parameter name of this action input parameter.

@return name

Gets request parameter name of this action input parameter .


private String getExposedPropertyOrParamName(ActionInputParameter inputParameter) {
        final Expose expose = inputParameter.getAnnotation(Expose.class);
        String property;
        if (expose != null) {
            property = expose.value();
        } else {
            property = inputParameter.getParameterName();
        }
        return property;
    }

private String getExposedPropertyOrParamName ( ActionInputParameter inputParameter ) { final Expose expose = inputParameter . getAnnotation ( Expose . class ) ; String property ; if ( expose != null ) { property = expose . value ( ) ; } else { property = inputParameter . getParameterName ( ) ; } return property ; }

Gets exposed property or parameter name.

@param inputParameter for exposure
@return property name

Gets exposed property or parameter name .


public String getVocab(MixinSource mixinSource, Object bean, Class<?> mixInClass) {
        if (proxyUnwrapper != null) {
            bean = proxyUnwrapper.unwrapProxy(bean);
        }

        // determine vocab in context
        String classVocab = bean == null ? null : vocabFromClassOrPackage(bean.getClass());

        final Vocab mixinVocab = findAnnotation(mixInClass, Vocab.class);

        Object nestedContextProviderFromMixin = getNestedContextProviderFromMixin(mixinSource, bean, mixInClass);
        String contextProviderVocab = null;
        if (nestedContextProviderFromMixin != null) {
            contextProviderVocab = getVocab(mixinSource, nestedContextProviderFromMixin, null);
        }

        String vocab;
        if (mixinVocab != null) {
            vocab = mixinVocab.value(); // wins over class
        } else if (classVocab != null) {
            vocab = classVocab; // wins over context provider
        } else if (contextProviderVocab != null) {
            vocab = contextProviderVocab; // wins over last resort
        } else {
            vocab = HTTP_SCHEMA_ORG;
        }
        return vocab;
    }

public
String
getVocab
(
MixinSource
mixinSource
,
Object
bean
,
Class
<
>
mixInClass
)
{
if
(
proxyUnwrapper
!=
)
{
bean
=
proxyUnwrapper
.
unwrapProxy
(
bean
)
;
}
// determine vocab in context
String
classVocab
=
bean
==
:
vocabFromClassOrPackage
(
bean
.
getClass
(
)
)
;
final
Vocab
mixinVocab
=
findAnnotation
(
mixInClass
,
Vocab
.
class
)
;
Object
nestedContextProviderFromMixin
=
getNestedContextProviderFromMixin
(
mixinSource
,
bean
,
mixInClass
)
;
String
contextProviderVocab
=
;
if
(
nestedContextProviderFromMixin
!=
)
{
contextProviderVocab
=
getVocab
(
mixinSource
,
nestedContextProviderFromMixin
,
)
;
}
String
vocab
;
if
(
mixinVocab
!=
)
{
vocab
=
mixinVocab
.
value
(
)
;
// wins over class
}
else
if
(
classVocab
!=
)
{
vocab
=
classVocab
;
// wins over context provider
}
else
if
(
contextProviderVocab
!=
)
{
vocab
=
contextProviderVocab
;
// wins over last resort
}
else
{
vocab
=
HTTP_SCHEMA_ORG
;
}
return
vocab
;
}

Gets vocab for given bean.

@param bean
to inspect for vocab
@param mixInClass
for bean which might define a vocab or has a context provider
@return explicitly defined vocab or http://schema.org


public String getQuery() {
        StringBuilder query = new StringBuilder();
        if (queryTail.length() > 0) {
            if (queryHead.length() == 0) {
                query.append("{?")
                        .append(queryTail)
                        .append("}");
            } else if (queryHead.length() > 0) {
                query.append(queryHead)
                        .append("{&")
                        .append(queryTail)
                        .append("}");
            }
        } else {
            query.append(queryHead);
        }
        return query.toString();
    }

public String getQuery ( ) { StringBuilder query = new StringBuilder ( ) ; if ( queryTail . length ( ) > 0 ) { if ( queryHead . length ( ) == 0 ) { query . append ( "{?" ) . append ( queryTail ) . append ( "}" ) ; } else if ( queryHead . length ( ) > 0 ) { query . append ( queryHead ) . append ( "{&" ) . append ( queryTail ) . append ( "}" ) ; } } else { query . append ( queryHead ) ; } return query . toString ( ) ; }

Query consisting of expanded parameters and unexpanded parameters.

@return query, may be empty

Query consisting of expanded parameters and unexpanded parameters .


private void appendForm(Affordance affordance, ActionDescriptor actionDescriptor) throws IOException {
        String formName = actionDescriptor.getActionName();
        RequestMethod httpMethod = RequestMethod.valueOf(actionDescriptor.getHttpMethod());

        // Link's expand method removes non-required variables from URL
        String actionUrl = affordance.expand()
                .getHref();
        beginForm(OptionalAttributes.attr("action", actionUrl)
                .and("method", getHtmlConformingHttpMethod(httpMethod))
                .and("name", formName));
        write("<h4>");
        write("Form " + formName);
        write("</h4>");

        writeHiddenHttpMethodField(httpMethod);
        // build the form
        if (actionDescriptor.hasRequestBody()) { // parameter bean
            ActionInputParameter requestBody = actionDescriptor.getRequestBody();
            Class<?> parameterType = requestBody.getParameterType();
            recurseBeanProperties(parameterType, actionDescriptor, requestBody, requestBody.getValue(), "");
        } else { // plain parameter list
            Collection<String> requestParams = actionDescriptor.getRequestParamNames();
            for (String requestParamName : requestParams) {
                ActionInputParameter actionInputParameter = actionDescriptor.getActionInputParameter(requestParamName);

                Object[] possibleValues = actionInputParameter.getPossibleValues(actionDescriptor);
                // TODO duplication with appendInputOrSelect
                if (possibleValues.length > 0) {
                    if (actionInputParameter.isArrayOrCollection()) {
                        appendSelectMulti(requestParamName, possibleValues, actionInputParameter);
                    } else {
                        appendSelectOne(requestParamName, possibleValues, actionInputParameter);
                    }
                } else {
                    if (actionInputParameter.isArrayOrCollection()) {
                        // have as many inputs as there are call values, list of 5 nulls gives you five input fields
                        // TODO support for free list input instead, code on demand?
                        Object[] callValues = actionInputParameter.getValues();
                        int items = callValues.length;
                        for (int i = 0; i < items; i++) {
                            Object value;
                            if (i < callValues.length) {
                                value = callValues[i];
                            } else {
                                value = null;
                            }
                            appendInput(requestParamName, actionInputParameter, value, actionInputParameter
									.isReadOnly(requestParamName)); // not readonly
                        }
                    } else {
                        String callValueFormatted = actionInputParameter.getValueFormatted();
                        appendInput(requestParamName, actionInputParameter, callValueFormatted, actionInputParameter
								.isReadOnly(requestParamName)); // not readonly
                    }
                }
            }
        }
        inputButton(Type.SUBMIT, capitalize(httpMethod.name()
                .toLowerCase()));
        endForm();
    }

Appends form and squashes non-GET or POST to POST. If required, adds _method field for handling by an
appropriate
filter such as Spring's HiddenHttpMethodFilter.

@param affordance
to make into a form
@param actionDescriptor
describing the form action
@throws IOException
@see

Spring
MVC HiddenHttpMethodFilter

Appends form and squashes non - GET or POST to POST . If required adds _method field for handling by an appropriate filter such as Spring s HiddenHttpMethodFilter .


private void inputButton(Type type, String value) throws IOException {
        write("<input type=\"");
        write(type.toString());
        write("\" ");
        write("value");
        write("=");
        quote();
        write(value);
        quote();
        write("/>");
    }

private
void
inputButton
(
Type
type
,
String
value
)
throws
IOException
{
write
(
"<input type=\""
)
;
write
(
type
.
toString
(
)
)
;
write
(
"\" "
)
;
write
(
"value"
)
;
write
(
"="
)
;
quote
(
)
;
write
(
value
)
;
quote
(
)
;
write
(
"/>"
)
;
}

Classic submit or reset button.

@param type
submit or reset
@param value
caption on the button
@throws IOException


private void appendInputOrSelect(ActionInputParameter parentInputParameter, String paramName, ActionInputParameter
            childInputParameter, Object[] possibleValues) throws IOException {
        if (possibleValues.length > 0) {
            if (childInputParameter.isArrayOrCollection()) {
                // TODO multiple formatted callvalues
                appendSelectMulti(paramName, possibleValues,
                        childInputParameter);
            } else {
                appendSelectOne(paramName, possibleValues,
                        childInputParameter);
            }
        } else {
            appendInput(paramName, childInputParameter,
                    childInputParameter.getValue(),
                    parentInputParameter.isReadOnly(paramName));
        }
    }

private
void
appendInputOrSelect
(
ActionInputParameter
parentInputParameter
,
String
paramName
,
ActionInputParameter
childInputParameter
,
Object
[
]
possibleValues
)
throws
IOException
{
if
(
possibleValues
.
length
>
0
)
{
if
(
childInputParameter
.
isArrayOrCollection
(
)
)
{
// TODO multiple formatted callvalues
appendSelectMulti
(
paramName
,
possibleValues
,
childInputParameter
)
;
}
else
{
appendSelectOne
(
paramName
,
possibleValues
,
childInputParameter
)
;
}
}
else
{
appendInput
(
paramName
,
childInputParameter
,
childInputParameter
.
getValue
(
)
,
parentInputParameter
.
isReadOnly
(
paramName
)
)
;
}
}

Appends simple input or select, depending on availability of possible values.

@param parentInputParameter
the parent during bean recursion
@param paramName
of the child input parameter
@param childInputParameter
the current input to be rendered
@param possibleValues
suitable for childInputParameter
@throws IOException

Appends simple input or select depending on availability of possible values .


public AffordanceBuilder and(AffordanceBuilder affordanceBuilder) {
        for (ActionDescriptor actionDescriptor : affordanceBuilder.actionDescriptors) {
            this.actionDescriptors.add(actionDescriptor);
        }
        return this;
    }

public AffordanceBuilder and ( AffordanceBuilder affordanceBuilder ) { for ( ActionDescriptor actionDescriptor : affordanceBuilder . actionDescriptors ) { this . actionDescriptors . add ( actionDescriptor ) ; } return this ; }

Adds actionDescriptors of the given AffordanceBuilder to this affordanceBuilder.

@param affordanceBuilder
whose action descriptors should be added to this one
@return builder

Adds actionDescriptors of the given AffordanceBuilder to this affordanceBuilder .


public PartialUriTemplateComponents asComponents() {
        return getUriTemplateComponents(Collections.<String, Object>emptyMap(), Collections.<String>emptyList());
    }

public PartialUriTemplateComponents asComponents ( ) { return getUriTemplateComponents ( Collections . < String , Object > emptyMap ( ) , Collections . < String > emptyList ( ) ) ; }

Returns the template as uri components, without variable expansion.

@return components of the Uri

Returns the template as uri components without variable expansion .


public PartialUriTemplateComponents stripOptionalVariables(List<ActionDescriptor> actionDescriptors) {
        return getUriTemplateComponents(Collections.<String, Object>emptyMap(), getRequiredArgNames(actionDescriptors));
    }

public PartialUriTemplateComponents stripOptionalVariables ( List < ActionDescriptor > actionDescriptors ) { return getUriTemplateComponents ( Collections . < String , Object > emptyMap ( ) , getRequiredArgNames ( actionDescriptors ) ) ; }

Strips all variables which are not required by any of the given action descriptors. If no action descriptors are
given, nothing will be stripped.

@param actionDescriptors
to decide which variables are optional, may be empty
@return partial uri template components without optional variables, if actionDescriptors was not empty

Strips all variables which are not required by any of the given action descriptors . If no action descriptors are given nothing will be stripped .


public UberNode getFirstByName(String name) {
        // TODO consider less naive impl
        UberNode ret = null;
        for (UberNode node : data) {
            if (name.equals(node.getName())) {
                ret = node;
                break;
            }
        }
        return ret;
    }

public
UberNode
getFirstByName
(
String
name
)
{
// TODO consider less naive impl
UberNode
ret
=
;
for
(
UberNode
node
:
data
)
{
if
(
name
.
equals
(
node
.
getName
(
)
)
)
{
ret
=
node
;
break
;
}
}
return
ret
;
}

Gets first child of this uber node having the given name attribute.

@param name
to look up
@return found child or null

Gets first child of this uber node having the given name attribute .


public UberNode getFirstByRel(String rel) {
        // TODO consider less naive impl
        for (UberNode node : data) {
            List<String> myRels = node.getRel();
            if (myRels != null) {
                for (String myRel : myRels) {
                    if (rel.equals(myRel)) {
                        return node;
                    }
                }
            }
        }
        return null;
    }

public
UberNode
getFirstByRel
(
String
rel
)
{
// TODO consider less naive impl
for
(
UberNode
node
:
data
)
{
List
<
String
>
myRels
=
node
.
getRel
(
)
;
if
(
myRels
!=
)
{
for
(
String
myRel
:
myRels
)
{
if
(
rel
.
equals
(
myRel
)
)
{
return
node
;
}
}
}
}
return
;
}

Gets first child of this uber node having the given rel attribute.

@param rel
to look up
@return found child or null

Gets first child of this uber node having the given rel attribute .


@Override
    public Iterator<UberNode> iterator() {

        return new Iterator<UberNode>() {

            int index = 0;

            @Override
            public void remove() {
                throw new UnsupportedOperationException("removing from uber node is not supported");
            }

            @Override
            public UberNode next() {
                index = findNextChildWithData();
                return data.get(index++);
            }

            @Override
            public boolean hasNext() {
                return findNextChildWithData() != -1;
            }

            private int findNextChildWithData() {
                for (int i = index; i < data.size(); i++) {
                    if (!data.get(i)
                            .getData()
                            .isEmpty()) {
                        return i;
                    }
                }
                return -1;
            }
        };
    }

Allows iterating over children of this uber node which have a data attribute.

Allows iterating over children of this uber node which have a data attribute .


@SuppressWarnings("WeakerAccess")
    public static <K,V> PersistentHashMap<K,V> ofEq(Equator<K> eq, Iterable<Map.Entry<K,V>> es) {
        if (es == null) { return empty(eq); }
        MutableHashMap<K,V> map = emptyMutable(eq);
        for (Map.Entry<K,V> entry : es) {
            if (entry != null) {
                map.assoc(entry.getKey(), entry.getValue());
            }
        }
        return map.immutable();
    }

@ SuppressWarnings ( "WeakerAccess" ) public static < K , V > PersistentHashMap < K , V > ofEq ( Equator < K > eq , Iterable < Map . Entry < K , V > > es ) { if ( es == null ) { return empty ( eq ) ; } MutableHashMap < K , V > map = emptyMutable ( eq ) ; for ( Map . Entry < K , V > entry : es ) { if ( entry != null ) { map . assoc ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return map . immutable ( ) ; }

Returns a new PersistentHashMap of the given keys and their paired values, skipping any null
Entries.

Returns a new PersistentHashMap of the given keys and their paired values skipping any null Entries .


public static <K extends Comparable<K>,V> PersistentTreeMap<K,V>
    of(Iterable<Map.Entry<K,V>> es) {
        if (es == null) { return empty(); }
        PersistentTreeMap<K,V> map = new PersistentTreeMap<>(Equator.defaultComparator(), null, 0);
        for (Map.Entry<K,V> entry : es) {
            if (entry != null) {
                map = map.assoc(entry.getKey(), entry.getValue());
            }
        }
        return map;
    }

public static < K extends Comparable < K > , V > PersistentTreeMap < K , V > of ( Iterable < Map . Entry < K , V > > es ) { if ( es == null ) { return empty ( ) ; } PersistentTreeMap < K , V > map = new PersistentTreeMap <> ( Equator . defaultComparator ( ) , null , 0 ) ; for ( Map . Entry < K , V > entry : es ) { if ( entry != null ) { map = map . assoc ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return map ; }

Returns a new PersistentTreeMap of the given comparable keys and their paired values, skipping
any null Entries.

Returns a new PersistentTreeMap of the given comparable keys and their paired values skipping any null Entries .


public static <K,V> PersistentTreeMap<K,V> empty(Comparator<? super K> c) {
        return new PersistentTreeMap<>(c, null, 0);
    }

public static < K , V > PersistentTreeMap < K , V > empty ( Comparator < ? super K > c ) { return new PersistentTreeMap <> ( c , null , 0 ) ; }

Returns a new empty PersistentTreeMap that will use the specified comparator.

Returns a new empty PersistentTreeMap that will use the specified comparator .


@Override public ImSortedSet<Entry<K,V>> entrySet() {
        // This is the pretty way to do it.
        return this.fold(PersistentTreeSet.ofComp(new KeyComparator<>(comp)),
                         PersistentTreeSet::put);
    }

@
Override
public
ImSortedSet
<
Entry
<
K
,
V
>
>
entrySet
(
)
{
// This is the pretty way to do it.
return
this
.
fold
(
PersistentTreeSet
.
ofComp
(
new
KeyComparator
<>
(
comp
)
)
,
PersistentTreeSet
::
put
)
;
}

Returns a view of the mappings contained in this map.  The set should actually contain
UnmodMap.UnEntry items, but that return signature is illegal in Java, so you'll just have to
remember.

Returns a view of the mappings contained in this map . The set should actually contain UnmodMap . UnEntry items but that return signature is illegal in Java so you ll just have to remember .


@Override public K lastKey() {
        UnEntry<K,V> max = last();
        if (max == null) {
            throw new NoSuchElementException("this map is empty");
        }
        return max.getKey();
    }

@
Override
public
K
lastKey
(
)
{
UnEntry
<
K
,
V
>
max
=
last
(
)
;
if
(
max
==
)
{
throw
new
NoSuchElementException
(
"this map is empty"
)
;
}
return
max
.
getKey
(
)
;
}

Returns the last key in this map or throws a NoSuchElementException if the map is empty.

Returns the last key in this map or throws a NoSuchElementException if the map is empty .


public static <T> Xform<T> of(Iterable<? extends T> list) {
        if (list == null) { return empty(); }
        return new SourceProviderIterableDesc<>(list);
    }

public static < T > Xform < T > of ( Iterable < ? extends T > list ) { if ( list == null ) { return empty ( ) ; } return new SourceProviderIterableDesc <> ( list ) ; }


@SuppressWarnings("unchecked")
    private static <H> H _fold(Iterable source, Operation[] ops, int opIdx, H ident, Fn2 reducer) {
        Object ret = ident;

        // This is a label - the first one I have used in Java in years, or maybe ever.
        // I'm assuming this is fast, but will have to test to confirm it.
        sourceLoop:
        for (Object o : source) {
            for (int j = opIdx; j < ops.length; j++) {
                Operation op = ops[j];
                if ( (op.filter != null) && !op.filter.apply(o) ) {
                    // stop processing this source item and go to the next one.
                    continue sourceLoop;
                }
                if (op.map != null) {
                    o = op.map.apply(o);
                    // This is how map can handle takeWhile, take, and other termination marker
                    // roles.  Remember, the fewer functions we have to check for, the faster this
                    // will execute.
                    if (o == TERMINATE) {
                        return (H) ret;
                    }
                } else if (op.flatMap != null) {
                    ret = _fold(op.flatMap.apply(o), ops, j + 1, (H) ret, reducer);
                    // stop processing this source item and go to the next one.
                    continue sourceLoop;
                }
//                    if ( (op.terminate != null) && op.terminate.apply(o) ) {
//                        return (G) ret;
//                    }
            }
            // Here, the item made it through all the operations.  Combine it with the result.
            ret = reducer.apply(ret, o);
        }
        return (H) ret;
    }

//                        return (G) ret;

than lazily evaluated and cached linked-list, Sequence model.

than lazily evaluated and cached linked - list Sequence model .


@Override public Xform<A> dropWhile(Fn1<? super A,Boolean> predicate) {
        if (predicate == null) { throw new IllegalArgumentException("Can't dropWhile without a function."); }
        return new DropWhileDesc<>(this, predicate);
    }

@
Override
public
Xform
<
A
>
dropWhile
(
Fn1
<
super
A
,
Boolean
>
predicate
)
{
if
(
predicate
==
)
{
throw
new
IllegalArgumentException
(
"Can't dropWhile without a function."
)
;
}
return
new
DropWhileDesc
<>
(
this
,
predicate
)
;
}

The number of items to drop from the beginning of the output.

The number of items to drop from the beginning of the output .


@Override public <B> B fold(B ident, Fn2<? super B,? super A,B> reducer) {
        if (reducer == null) {
            throw new IllegalArgumentException("Can't fold with a null reduction function.");
        }

        // Construct an optimized array of OpRuns (mutable operations for this run)
        RunList runList = toRunList();
        return _fold(runList, runList.opArray(), 0, ident, reducer);
    }

Provides a way to collect the results of the transformation.

Provides a way to collect the results of the transformation .


public static <K,V> Tuple2<K,V> of(Map.Entry<K,V> entry) {
        // Protect against multiple-instantiation
        if (entry instanceof Tuple2) {
            return (Tuple2<K,V>) entry;
        }
        return new Tuple2<>(entry.getKey(), entry.getValue());
    }


@SuppressWarnings("unchecked")
    public <R> R match(Fn1<A, R> fa,
                       Fn1<B, R> fb,
                       Fn1<C, R> fc) {
        if (sel == 0) {
            return fa.apply((A) item);
        } else if (sel == 1) {
            return fb.apply((B) item);
        } else {
            return fc.apply((C) item);
        }
    }

@ SuppressWarnings ( "unchecked" ) public < R > R match ( Fn1 < A , R > fa , Fn1 < B , R > fb , Fn1 < C , R > fc ) { if ( sel == 0 ) { return fa . apply ( ( A ) item ) ; } else if ( sel == 1 ) { return fb . apply ( ( B ) item ) ; } else { return fc . apply ( ( C ) item ) ; } }

If sel is managed correctly, it ensures that the cast is accurate.

If sel is managed correctly it ensures that the cast is accurate .


public static ImList<Class> registerClasses(Class... cs) {
        if (cs == null) {
            throw new IllegalArgumentException("Can't register a null type array");
        }
        if (cs.length == 0) {
            throw new IllegalArgumentException("Can't register a zero-length type array");
        }
        for (Class c : cs) {
            if (c == null) {
                throw new IllegalArgumentException("There shouldn't be any null types in this array!");
            }
        }

        ArrayHolder<Class> ah = new ArrayHolder<>(cs);
        ImList<Class> registeredTypes;
        synchronized (Lock.INSTANCE) {
            registeredTypes = typeMap.get(ah);
            if (registeredTypes == null) {
                ImList<Class> vecCs = vec(cs);
                typeMap.put(ah, vecCs);
                registeredTypes = vecCs;
            }
        }
        // We are returning the original array.  If we returned our safe copy, it could be modified!
        return registeredTypes;
    }

Use this to prevent duplicate runtime types.
@param cs an immutable vector of classes to register

Use this to prevent duplicate runtime types .


@Override public E get(int i) {
        E[] node = leafNodeArrayFor(i);
        return node[i & LOW_BITS];
    }

@ Override public E get ( int i ) { E [ ] node = leafNodeArrayFor ( i ) ; return node [ i & LOW_BITS ] ; }

Returns the item specified by the given index.

Returns the item specified by the given index .


@SuppressWarnings("unchecked")
    @Override public PersistentVector<E> append(E val) {
        //room in tail?
        //	if(tail.length < MAX_NODE_LENGTH)
        if (size - tailoff() < MAX_NODE_LENGTH) {
            E[] newTail = (E[]) new Object[tail.length + 1];
            System.arraycopy(tail, 0, newTail, 0, tail.length);
            newTail[tail.length] = val;
            return new PersistentVector<>(size + 1, shift, root, newTail);
        }
        //full tail, push into tree
        Node newroot;
        Node tailnode = new Node(root.edit, tail);
        int newshift = shift;
        //overflow root?
        if ((size >>> NODE_LENGTH_POW_2) > (1 << shift)) {
            newroot = new Node(root.edit);
            newroot.array[0] = root;
            newroot.array[1] = newPath(root.edit, shift, tailnode);
            newshift += NODE_LENGTH_POW_2;
        } else {
            newroot = pushTail(shift, root, tailnode);
        }
        return new PersistentVector<>(size + 1, newshift, newroot, (E[]) new Object[]{val});
    }

@
SuppressWarnings
(
"unchecked"
)
@
Override
public
PersistentVector
<
E
>
append
(
E
val
)
{
//room in tail?
//	if(tail.length < MAX_NODE_LENGTH)
if
(
size
tailoff
(
)
<
MAX_NODE_LENGTH
)
{
E
[
]
newTail
=
(
E
[
]
)
new
Object
[
tail
.
length
+
1
]
;
System
.
arraycopy
(
tail
,
0
,
newTail
,
0
,
tail
.
length
)
;
newTail
[
tail
.
length
]
=
val
;
return
new
PersistentVector
<>
(
size
+
1
,
shift
,
root
,
newTail
)
;
}
//full tail, push into tree
Node
newroot
;
Node
tailnode
=
new
Node
(
root
.
edit
,
tail
)
;
int
newshift
=
shift
;
//overflow root?
if
(
(
size
>>>
NODE_LENGTH_POW_2
)
>
(
1
<<
shift
)
)
{
newroot
=
new
Node
(
root
.
edit
)
;
newroot
.
array
[
0
]
=
root
;
newroot
.
array
[
1
]
=
newPath
(
root
.
edit
,
shift
,
tailnode
)
;
newshift
+=
NODE_LENGTH_POW_2
;
}
else
{
newroot
=
pushTail
(
shift
,
root
,
tailnode
)
;
}
return
new
PersistentVector
<>
(
size
+
1
,
newshift
,
newroot
,
(
E
[
]
)
new
Object
[
]
{
val
}
)
;
}

Inserts a new item at the end of the Vecsicle.
@param val the value to insert
@return a new Vecsicle with the additional item.

Inserts a new item at the end of the Vecsicle .


@Override public PersistentVector<E> concat(Iterable<? extends E> items) {
        return (PersistentVector<E>) ImList.super.concat(items);
    }

@ Override public PersistentVector < E > concat ( Iterable < ? extends E > items ) { return ( PersistentVector < E > ) ImList . super . concat ( items ) ; }

Efficiently adds items to the end of this PersistentVector.
@param items the values to insert
@return a new PersistentVector with the additional items at the end.

Efficiently adds items to the end of this PersistentVector .


@SafeVarargs
    public static <T> MutableSet<T> mutableSet(T... items) {
        MutableSet<T> ret = PersistentHashSet.emptyMutable();
        if (items == null) { return ret; }
        for (T t : items) {
            ret.put(t);
        }
        return ret;
    }

@ SafeVarargs public static < T > MutableSet < T > mutableSet ( T ... items ) { MutableSet < T > ret = PersistentHashSet . emptyMutable ( ) ; if ( items == null ) { return ret ; } for ( T t : items ) { ret . put ( t ) ; } return ret ; }

Returns a new MutableSet of the values.  This data definition method is one of the few
methods in this project that support varargs.  If the input contains duplicate elements, later
values overwrite earlier ones.

Returns a new MutableSet of the values . This data definition method is one of the few methods in this project that support varargs . If the input contains duplicate elements later values overwrite earlier ones .


@SafeVarargs
    public static <T> MutableList<T> mutableVec(T... items) {
        MutableList<T> ret = PersistentVector.emptyMutable();
        if (items == null) { return ret; }
        for (T t : items) {
            ret.append(t);
        }
        return ret;
    }

@ SafeVarargs public static < T > MutableList < T > mutableVec ( T ... items ) { MutableList < T > ret = PersistentVector . emptyMutable ( ) ; if ( items == null ) { return ret ; } for ( T t : items ) { ret . append ( t ) ; } return ret ; }

Returns a MutableVector of the given items.  This data definition method is one of the
few methods in this project that support varargs.

Returns a MutableVector of the given items . This data definition method is one of the few methods in this project that support varargs .


@SafeVarargs
    public static <T> ImSet<T> set(T... items) {
        if ( (items == null) || (items.length < 1) ) { return PersistentHashSet.empty(); }
        return PersistentHashSet.of(Arrays.asList(items));
    }

@ SafeVarargs public static < T > ImSet < T > set ( T ... items ) { if ( ( items == null ) || ( items . length < 1 ) ) { return PersistentHashSet . empty ( ) ; } return PersistentHashSet . of ( Arrays . asList ( items ) ) ; }

Returns a new PersistentHashSet of the values.  This data definition method is one of the few
methods in this project that support varargs.  If the input contains duplicate elements, later
values overwrite earlier ones.

Returns a new PersistentHashSet of the values . This data definition method is one of the few methods in this project that support varargs . If the input contains duplicate elements later values overwrite earlier ones .


@SafeVarargs
    static public <T> ImList<T> vec(T... items) {
        if ( (items == null) || (items.length < 1) ) { return PersistentVector.empty(); }
        return mutableVec(items).immutable();
    }

@ SafeVarargs static public < T > ImList < T > vec ( T ... items ) { if ( ( items == null ) || ( items . length < 1 ) ) { return PersistentVector . empty ( ) ; } return mutableVec ( items ) . immutable ( ) ; }

Returns a new PersistentVector of the given items.  This data definition method is one of the
few methods in this project that support varargs.

Returns a new PersistentVector of the given items . This data definition method is one of the few methods in this project that support varargs .


@SafeVarargs
    public static <T> UnmodIterable<T> xformArray(T... items) {
        return Xform.of(Arrays.asList(items));
    }

@ SafeVarargs public static < T > UnmodIterable < T > xformArray ( T ... items ) { return Xform . of ( Arrays . asList ( items ) ) ; }

If you need to wrap a regular Java array outside this project to perform
a transformation on it, this method is the most convenient, efficient way to do so.

If you need to wrap a regular Java array outside this project to perform a transformation on it this method is the most convenient efficient way to do so .


public static StringBuilder indentSpace(int len) {
        StringBuilder sB = new StringBuilder();
        if (len < 1) { return sB; }
        while (len > SPACES_LENGTH_MINUS_ONE) {
            sB.append(SPACES[SPACES_LENGTH_MINUS_ONE]);
            len = len - SPACES_LENGTH_MINUS_ONE;
        }
        return sB.append(SPACES[len]);
    }

public static StringBuilder indentSpace ( int len ) { StringBuilder sB = new StringBuilder ( ) ; if ( len < 1 ) { return sB ; } while ( len > SPACES_LENGTH_MINUS_ONE ) { sB . append ( SPACES [ SPACES_LENGTH_MINUS_ONE ] ) ; len = len - SPACES_LENGTH_MINUS_ONE ; } return sB . append ( SPACES [ len ] ) ; }

Creates a new StringBuilder with the given number of spaces and returns it.
@param len the number of spaces
@return a {@link StringBuilder} with the specificed number of initial spaces.

Creates a new StringBuilder with the given number of spaces and returns it .


public static <T> String arrayString(T[] items) {
        StringBuilder sB = new StringBuilder("A[");
        boolean isFirst = true;
        for (T item : items) {
            if (isFirst) {
                isFirst = false;
            } else {
                sB.append(" ");
            }
            if (item instanceof String) {
                sB.append("\"").append(item).append("\"");
            } else {
                sB.append(item);
            }
        }
        return sB.append("]").toString();
    }

public
static
<
T
>
String
arrayString
(
T
[
]
items
)
{
StringBuilder
sB
=
new
StringBuilder
(
"A["
)
;
boolean
isFirst
=
true
;
for
(
T
item
:
items
)
{
if
(
isFirst
)
{
isFirst
=
false
;
}
else
{
sB
.
append
(
" "
)
;
}
if
(
item
instanceof
String
)
{
sB
.
append
(
"\""
)
.
append
(
item
)
.
append
(
"\""
)
;
}
else
{
sB
.
append
(
item
)
;
}
}
return
sB
.
append
(
"]"
)
.
toString
(
)
;
}

There is Arrays.toString, but this is intended to produce Cymling code some day.

There is Arrays . toString but this is intended to produce Cymling code some day .


public static <T> LazyRef<T> of(Fn0<T> producer) {
        if (producer == null) {
            throw new IllegalArgumentException("The producer function cannot be null (the value it returns can)");
        }
        return new LazyRef<>(producer);
    }

Construct a LazyRef from the given initialization function.

@param producer a zero-argument function that produces the desired value when called.

@return a LazyRef with the given producer.

Construct a LazyRef from the given initialization function .


public synchronized T applyEx() {
        // Have we produced our value yet?
        if (producer != null) {
            // produce our value.
            value = producer.apply();
            // Delete the producer to 1. mark the work done and 2. free resources.
            producer = null;
        }
        // We're clear to return the lazily computed value.
        return value;
    }

This whole method is synchronized on the advice of Goetz2006 p. 347

This whole method is synchronized on the advice of Goetz2006 p . 347


public static <T> T[] insertIntoArrayAt(T item, T[] items, int idx, Class<T> tClass) {
        // Make an array that's one bigger.  It's too bad that the JVM bothers to
        // initialize this with nulls.
        @SuppressWarnings("unchecked")
        T[] newItems = (T[]) ((tClass == null) ? new Object[items.length + 1]
                                               : Array.newInstance(tClass, items.length + 1) );

        // If we aren't inserting at the first item, array-copy the items before the insert
        // point.
        if (idx > 0) {
            System.arraycopy(items, 0, newItems, 0, idx);
        }

        // Insert the new item.
        newItems[idx] = item;

        // If we aren't inserting at the last item, array-copy the items after the insert
        // point.
        if (idx < items.length) {
            System.arraycopy(items, idx, newItems, idx + 1, items.length - idx);
        }

        return newItems;
    }

Returns a new array one longer than the given one, with the specified item inserted at the specified index.
@param item The item to insert
@param items The original array (will not be modified)
@param idx the index to insert the item at.
@param tClass The runtime class to store in the new array (or null for an Object array).
@return A copy of the given array with the additional item at the appropriate index
(will be one longer than the original array).

Returns a new array one longer than the given one with the specified item inserted at the specified index .


public static <T> T[] arrayCopy(T[] items, int length, Class<T> tClass) {
        // Make an array of the appropriate size.  It's too bad that the JVM bothers to
        // initialize this with nulls.
        @SuppressWarnings("unchecked")
        T[] newItems = (T[]) ((tClass == null) ? new Object[length]
                                               : Array.newInstance(tClass, length) );

        // array-copy the items up to the new length.
        if (length > 0) {
            System.arraycopy(items, 0, newItems, 0,
                             items.length < length ? items.length
                                                   : length);
        }
        return newItems;
    }

Returns a new array containing the first n items of the given array.

@param items the items to copy
@param length the maximum length of the new array
@param tClass the class of the items in the array (null for Object)
@return a copy of the original array with the given length

Returns a new array containing the first n items of the given array .


private void suspendIfAssoaciatedWithThread() throws SystemException {
		// if there is a tx associated with this thread and it is this one
		// then suspend it to dissociate the thread (dumb feature?!?! of jboss ts)
		final SleeTransaction currentThreadTransaction = transactionManager
				.getSleeTransaction();
		if (currentThreadTransaction != null
				&& currentThreadTransaction.equals(this)) {
			// lets use the real tx manager directly, to avoid any other procedures
			transactionManager.getRealTransactionManager().suspend();
		}
	}

Some operations require that the transaction be suspended
@throws SystemException


private void beforeAsyncOperation() throws IllegalStateException,
			SecurityException {
		try {
			int status = transaction.getStatus();
			if (asyncOperationInitiated.getAndSet(true) || (status != Status.STATUS_ACTIVE
					&& status != Status.STATUS_MARKED_ROLLBACK)) {
				throw new IllegalStateException(
						"There is no active tx, tx is in state: " + status);
			}
			suspendIfAssoaciatedWithThread();
		} catch (SystemException e) {
			throw new IllegalStateException(e);
		}
	}

Verifies if the wrapped transaction is active and if dissociates it from
the thread if needed

@throws IllegalStateException
@throws SecurityException


public List<ServiceComponentImpl> buildComponents(String serviceDescriptorFileName, JarFile deployableUnitJar) throws DeploymentException {

		// make component jar entry
		JarEntry componentDescriptor = deployableUnitJar.getJarEntry(serviceDescriptorFileName);
		InputStream componentDescriptorInputStream = null;
		List<ServiceComponentImpl> result = new ArrayList<ServiceComponentImpl>();
    	try {
    		componentDescriptorInputStream = deployableUnitJar.getInputStream(componentDescriptor);
    		ServiceDescriptorFactoryImpl descriptorFactory = componentManagement.getComponentDescriptorFactory().getServiceDescriptorFactory();
    		for (ServiceDescriptorImpl descriptor : descriptorFactory.parse(componentDescriptorInputStream)) {
    			result.add(new ServiceComponentImpl(descriptor));
    		}
    	} catch (IOException e) {
    		throw new DeploymentException("failed to parse service descriptor from "+componentDescriptor.getName(),e);
    	}
    	finally {
    		if (componentDescriptorInputStream != null) {
    			try {
    				componentDescriptorInputStream.close();
    			} catch (IOException e) {
    				logger.error("failed to close inputstream of descriptor for jar "+componentDescriptor.getName());
    			}
    		}
    	}
    	return result;
    }

Builds a service component contained in the specified du jar file, with the specified and adds it to the specified deployable unit.

@param serviceDescriptorFileName
@param deployableUnitJar
@param deployableUnit
@param documentBuilder
@throws DeploymentException

Builds a service component contained in the specified du jar file with the specified and adds it to the specified deployable unit .


static private void validateDirectory(File aDirectory)
			throws FileNotFoundException {
		if (aDirectory == null) {
			throw new IllegalArgumentException("Directory should not be null.");
		}
		if (!aDirectory.exists()) {
			throw new FileNotFoundException("Directory does not exist: "
					+ aDirectory);
		}
		if (!aDirectory.isDirectory()) {
			throw new IllegalArgumentException("Is not a directory: "
					+ aDirectory);
		}
		if (!aDirectory.canRead()) {
			throw new IllegalArgumentException("Directory cannot be read: "
					+ aDirectory);
		}
	}

static
private
void
validateDirectory
(
File
aDirectory
)
throws
FileNotFoundException
{
if
(
aDirectory
==
)
{
throw
new
IllegalArgumentException
(
"Directory should not be null."
)
;
}
if
(
!
aDirectory
.
exists
(
)
)
{
throw
new
FileNotFoundException
(
"Directory does not exist: "
+
aDirectory
)
;
}
if
(
!
aDirectory
.
isDirectory
(
)
)
{
throw
new
IllegalArgumentException
(
"Is not a directory: "
+
aDirectory
)
;
}
if
(
!
aDirectory
.
canRead
(
)
)
{
throw
new
IllegalArgumentException
(
"Directory cannot be read: "
+
aDirectory
)
;
}
}

Directory is valid if it exists, does not represent a file, and can be read.

Directory is valid if it exists does not represent a file and can be read .


public static void createInheritanceLink(CtClass concreteClass,
			CtClass superClass) {
		if (superClass == null)
			return;
		try {
			concreteClass.setSuperclass(superClass);
			logger.trace(concreteClass.getName() + " Inheritance link with "
					+ superClass.getName() + " class created");
		} catch (CannotCompileException cce) {
			cce.printStackTrace();
		}
	}

public
static
void
createInheritanceLink
(
CtClass
concreteClass
,
CtClass
superClass
)
{
if
(
superClass
==
)
return
;
try
{
concreteClass
.
setSuperclass
(
superClass
)
;
logger
.
trace
(
concreteClass
.
getName
(
)
+
" Inheritance link with "
+
superClass
.
getName
(
)
+
" class created"
)
;
}
catch
(
CannotCompileException
cce
)
{
cce
.
printStackTrace
(
)
;
}
}

Create the inheritance link with the sbb absract class provided by the
sbb developer

@param concreteClass
the concrete class to which to add the inheritance link
@param superClass
the superClass to set


public static void copyMethods(CtClass source, CtClass destination,
			CtClass[] exceptions) {
		copyMethods(source.getDeclaredMethods(), destination, exceptions);
	}

public static void copyMethods ( CtClass source , CtClass destination , CtClass [ ] exceptions ) { copyMethods ( source . getDeclaredMethods ( ) , destination , exceptions ) ; }

Copy declared methods from one class to another

@param source
the class from which the methods are copied
@param destination
the class to which the methods are copied
@param exceptions
optionnal, defines the set of exceptions the methods can throw


public static void copyMethods(CtMethod[] methods, CtClass destination,
			CtClass[] exceptions) {
		CtMethod methodCopy = null;
		for (CtMethod method : methods) {
			try {
				methodCopy = new CtMethod(method, destination, null);
				if (exceptions != null) {
					try {
						methodCopy.setExceptionTypes(exceptions);
					} catch (NotFoundException e) {
						throw new SLEEException(e.getMessage(),e);
					}
				}
				destination.addMethod(methodCopy);
			} catch (CannotCompileException e) {
				throw new SLEEException(e.getMessage(),e);
			}
		}
	}

public static void copyMethods ( CtMethod [ ] methods , CtClass destination , CtClass [ ] exceptions ) { CtMethod methodCopy = null ; for ( CtMethod method : methods ) { try { methodCopy = new CtMethod ( method , destination , null ) ; if ( exceptions != null ) { try { methodCopy . setExceptionTypes ( exceptions ) ; } catch ( NotFoundException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } destination . addMethod ( methodCopy ) ; } catch ( CannotCompileException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } }

Copy methods to a class

@param methods
the methods to copy
@param destination
the class to which the methods are copied
@param exceptions
optional, defines the set of exceptions the methods can throw


private TreeItem doTree(FQDNNode localRoot) {

    TreeItem localLeaf = new TreeItem();

    LogTreeNode logTreeNode = new LogTreeNode(browseContainer, localRoot.getShortName(), localRoot.getFqdName(), localRoot.isWasLeaf(), this);

    localLeaf.setWidget(logTreeNode);

    if (localRoot.getChildren().size() > 0) {

      Tree t = new Tree();

      ArrayList names = new ArrayList(localRoot.getChildrenNames());
      Collections.sort(names);
      Iterator it = names.iterator();
      while (it.hasNext()) {
        t.addItem(doTree(localRoot.getChild((String) it.next())));
      }
      localLeaf.addItem(t);
    }

    return localLeaf;

  }

private TreeItem doTree ( FQDNNode localRoot ) { TreeItem localLeaf = new TreeItem ( ) ; LogTreeNode logTreeNode = new LogTreeNode ( browseContainer , localRoot . getShortName ( ) , localRoot . getFqdName ( ) , localRoot . isWasLeaf ( ) , this ) ; localLeaf . setWidget ( logTreeNode ) ; if ( localRoot . getChildren ( ) . size ( ) > 0 ) { Tree t = new Tree ( ) ; ArrayList names = new ArrayList ( localRoot . getChildrenNames ( ) ) ; Collections . sort ( names ) ; Iterator it = names . iterator ( ) ; while ( it . hasNext ( ) ) { t . addItem ( doTree ( localRoot . getChild ( ( String ) it . next ( ) ) ) ) ; } localLeaf . addItem ( t ) ; } return localLeaf ; }


private void removeSbbEntityWithCurrentClassLoader(
			final SbbEntity sbbEntity) {
		// remove entity
		sbbEntity.remove();
		// remove from tx data
		final TransactionContext txContext = sleeContainer.getTransactionManager().getTransactionContext();
		final SbbEntityID sbbEntityID = sbbEntity.getSbbEntityId();
		txContext.getData().remove(sbbEntityID);
		// if sbb entity is root add a tx action to ensure lock is removed
		if (sbbEntityID.isRootSbbEntity()) {
			TransactionalAction txAction = new TransactionalAction() {
				@Override
				public void execute() {
					lockFacility.remove(sbbEntityID);
				}
			};
			txContext.getAfterCommitActions().add(txAction);
		}
	}

Removes the specified sbb entity but without changing to sbb's class
loader first.

@param sbbEntity
the sbb entity to remove

Removes the specified sbb entity but without changing to sbb s class loader first .


public boolean getNotificationsEnabled(String paramName) {

		Boolean areNotificationsEnabled = paramNames.get(paramName);

		if(!isSlee11)
		{
			if (areNotificationsEnabled == null
				|| areNotificationsEnabled.booleanValue()) {
			// considering that notifications are enabled, by default, for each
			// param
				return true;
			} else {
				return false;
			}
		}else
		{
			if (areNotificationsEnabled != null
					&& areNotificationsEnabled.booleanValue()) {
				// considering that notifications are enabled, by default, for each
				// param
					return true;
				} else {
					return false;
				}
		}
	}

Indicates if notifications are enabled for the specified parameter name

@param paramName
@return


public Set<String> getReferencedRAEntityLinksWhichNotExists(
			ServiceComponent serviceComponent) {
		Set<String> result = new HashSet<String>();
		Set<String> raLinkNames = sleeContainer.getResourceManagement()
				.getLinkNamesSet();
		for (String raLink : serviceComponent
				.getResourceAdaptorEntityLinks(componentRepositoryImpl)) {
			if (!raLinkNames.contains(raLink)) {
				result.add(raLink);
			}
		}
		return result;
	}

Retrieves the set of ra entity link names referenced by the service
componen, which do not exist

@param serviceComponent

Retrieves the set of ra entity link names referenced by the service componen which do not exist


public void installService(final ServiceComponent serviceComponent)
			throws Exception {

		if (logger.isDebugEnabled()) {
			logger.debug("Installing Service " + serviceComponent);
		}

		// creates and registers the service usage mbean
		final ServiceUsageMBean serviceUsageMBean = sleeContainer
				.getUsageParametersManagement().newServiceUsageMBean(
						serviceComponent);
		// add rollback action to remove state created
		TransactionalAction action = new TransactionalAction() {
			public void execute() {
				try {
					serviceUsageMBean.remove();
				} catch (Throwable e) {
					logger.error(e.getMessage(), e);
				}
			}
		};
		final TransactionContext txContext = sleeContainer
				.getTransactionManager().getTransactionContext();
		txContext.getAfterRollbackActions().add(action);

		// register notification sources for all sbbs
		//
		final TraceManagement traceMBeanImpl = sleeContainer
				.getTraceManagement();
		for (final SbbID sbbID : serviceComponent
				.getSbbIDs(componentRepositoryImpl)) {

			// Tracer must be available for both 1.1 and 1.0 sbb components
			// SbbComponent sbbComponent =
			// componentRepositoryImpl.getComponentByID(sbbID);
			// if(sbbComponent.isSlee11())
			{
				traceMBeanImpl.registerNotificationSource(new SbbNotification(
						serviceComponent.getServiceID(), sbbID));

				// add rollback action to remove state created
				action = new TransactionalAction() {
					public void execute() {
						// remove notification sources for all sbbs
						traceMBeanImpl
								.deregisterNotificationSource(new SbbNotification(
										serviceComponent.getServiceID(), sbbID));
					}
				};
				txContext.getAfterRollbackActions().add(action);
			}

			// this might be used not only by 1.1 sbbs...
			NotificationSourceWrapperImpl sbbMNotificationSource = new NotificationSourceWrapperImpl(
					new SbbNotification(serviceComponent.getServiceID(), sbbID));
			serviceComponent.getAlarmNotificationSources().putIfAbsent(sbbID,
					sbbMNotificationSource);
		}

		sleeContainer.getSbbManagement().serviceInstall(serviceComponent);
	}

Install a service into SLEE

@param serviceComponent
@throws Exception


public void uninstallService(final ServiceComponent serviceComponent)
			throws SystemException, UnrecognizedServiceException,
			InstanceNotFoundException, MBeanRegistrationException,
			NullPointerException, UnrecognizedResourceAdaptorEntityException,
			ManagementException, InvalidStateException {

		if (logger.isDebugEnabled()) {
			logger.debug("Uninstalling service with id "
					+ serviceComponent.getServiceID());
		}

		if (serviceComponent.getServiceState().isStopping()) {
			// let's be friendly and give it a few secs
			for (int i = 0; i < 15; i++) {
				try {
					Thread.sleep(1000);
					logger.info("Waiting for "
							+ serviceComponent.getServiceID()
							+ " to stop, current state is "
							+ serviceComponent.getServiceState());
					if (serviceComponent.getServiceState().isInactive()) {
						break;
					}
				} catch (Throwable e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		if (!serviceComponent.getServiceState().isInactive()) {
			throw new InvalidStateException(serviceComponent.toString()
					+ " is not inactive");
		}

		final TransactionContext txContext = sleeContainer
				.getTransactionManager().getTransactionContext();

		if (logger.isDebugEnabled()) {
			logger.debug("Closing Usage MBean of service "
					+ serviceComponent.getServiceID());
		}

		ServiceUsageMBean serviceUsageMBean = serviceComponent.getServiceUsageMBean();
		if (serviceUsageMBean != null) {
			serviceUsageMBean.remove();
			// add rollback action to re-create the mbean
			// FIXME this doesn't make sense, this restore looses all old data,
			// it shoudl only remove on
			// commit but as it is right now, the needed sbb components are
			// already removed
			TransactionalAction action = new TransactionalAction() {
				public void execute() {
					try {
						sleeContainer.getUsageParametersManagement()
								.newServiceUsageMBean(serviceComponent);
					} catch (Throwable e) {
						logger.error(e.getMessage(), e);
					}
				}
			};
			txContext.getAfterRollbackActions().add(action);
		}

		// register notification sources for all sbbs
		final TraceManagement traceMBeanImpl = sleeContainer
				.getTraceManagement();
		for (final SbbID sbbID : serviceComponent
				.getSbbIDs(componentRepositoryImpl)) {

			// Tracer must be available for both 1.1 and 1.0 sbb components
			// SbbComponent sbbComponent =
			// componentRepositoryImpl.getComponentByID(sbbID);
			// if(sbbComponent.isSlee11())
			{
				traceMBeanImpl
						.deregisterNotificationSource(new SbbNotification(
								serviceComponent.getServiceID(), sbbID));

				// add rollback action to re-add state removed
				TransactionalAction action = new TransactionalAction() {
					public void execute() {
						// remove notification sources for all sbbs
						traceMBeanImpl
								.registerNotificationSource(new SbbNotification(
										serviceComponent.getServiceID(), sbbID));
					}

				};
				txContext.getAfterRollbackActions().add(action);
			}
		}

		// warn sbb management that the service is being uninstalled, giving it
		// the option to clear any related resources
		sleeContainer.getSbbManagement().serviceUninstall(serviceComponent);

	}

uninstall a service.

@throws SystemException
@throws UnrecognizedServiceException
@throws MBeanRegistrationException
@throws InstanceNotFoundException
@throws UnrecognizedResourceAdaptorEntityException
@throws NullPointerException
@throws InvalidStateException


public boolean isRAEntityLinkNameReferenced(String raLinkName) {
		if (raLinkName == null) {
			throw new NullPointerException("null ra link name");
		}

		boolean b = false;
		try {
			b = transactionManager.requireTransaction();
			for (ServiceID serviceID : componentRepositoryImpl.getServiceIDs()) {
				ServiceComponent serviceComponent = componentRepositoryImpl
						.getComponentByID(serviceID);
				if (serviceComponent.getServiceState() != ServiceState.INACTIVE
						&& serviceComponent.getResourceAdaptorEntityLinks(
								componentRepositoryImpl).contains(raLinkName)) {
					return true;
				}
			}
			return false;
		} finally {
			try {
				transactionManager.requireTransactionEnd(b, false);
			} catch (Throwable ex) {
				throw new SLEEException(ex.getMessage(), ex);
			}
		}
	}

public
boolean
isRAEntityLinkNameReferenced
(
String
raLinkName
)
{
if
(
raLinkName
==
)
{
throw
new
NullPointerException
(
"null ra link name"
)
;
}
boolean
b
=
false
;
try
{
b
=
transactionManager
.
requireTransaction
(
)
;
for
(
ServiceID
serviceID
:
componentRepositoryImpl
.
getServiceIDs
(
)
)
{
ServiceComponent
serviceComponent
=
componentRepositoryImpl
.
getComponentByID
(
serviceID
)
;
if
(
serviceComponent
.
getServiceState
(
)
!=
ServiceState
.
INACTIVE
&&
serviceComponent
.
getResourceAdaptorEntityLinks
(
componentRepositoryImpl
)
.
contains
(
raLinkName
)
)
{
return
true
;
}
}
return
false
;
}
finally
{
try
{
transactionManager
.
requireTransactionEnd
(
b
,
false
)
;
}
catch
(
Throwable
ex
)
{
throw
new
SLEEException
(
ex
.
getMessage
(
)
,
ex
)
;
}
}
}

Verifies if the specified ra entity link name is referenced by a non
inactive service.

@param raLinkName
@return

Verifies if the specified ra entity link name is referenced by a non inactive service .


public synchronized String[] getUsageParameterSets(SbbID sbbId)
			throws NullPointerException, UnrecognizedSbbException,
			InvalidArgumentException, ManagementException {

		if (sbbId == null)
			throw new NullPointerException("Sbb ID is null!");

		// get the sbb component
		SbbComponent sbbComponent = sleeContainer.getComponentRepository()
				.getComponentByID(sbbId);
		if (sbbComponent == null) {
			throw new UnrecognizedSbbException(sbbId.toString());
		} else {
			if (sbbComponent.getUsageParametersInterface() == null) {
				throw new InvalidArgumentException(
						"no usage parameter interface for " + sbbId);
			}
		}
		// get service component and check if the sbb belongs to the service
		ServiceComponent serviceComponent = sleeContainer
				.getComponentRepository().getComponentByID(getService());
		if (!serviceComponent.getSbbIDs(
				sleeContainer.getComponentRepository()).contains(sbbId)) {
			throw new UnrecognizedSbbException(sbbId.toString()
					+ " is not part of " + getService());
		}
		Set<String> resultSet = new HashSet<String>();
		for (UsageMBeanImpl usageMBeanImpl : usageMBeans.values()) {
			if (((SbbNotification) usageMBeanImpl.getNotificationSource())
					.getSbb().equals(sbbId)) {
				String name = usageMBeanImpl.getUsageParameterSet();
				if (name != null) {
					resultSet.add(name);
				}
			}
		}
		return resultSet.toArray(new String[resultSet.size()]);
	}

This method returns a list containing the names of the named SBB usage
parameter sets that belong to the SBB specified by the sbbID argument and
the Service represented by the ServiceUsageMBean object.

@see javax.slee.management.ServiceUsageMBean#getUsageParameterSets(javax.slee.SbbID)

This method returns a list containing the names of the named SBB usage parameter sets that belong to the SBB specified by the sbbID argument and the Service represented by the ServiceUsageMBean object .


public synchronized void resetAllUsageParameters()
			throws ManagementException {
		try {
			//FIXME: hmm, how to check here for clustered... ghmp
			for (UsageMBeanImpl usageMBeanImpl : usageMBeans.values()) {
				usageMBeanImpl.resetAllUsageParameters();
			}
		} catch (Throwable e) {
			throw new ManagementException(e.getMessage(), e);
		}
	}

Resets the usage parameters of all SBBs within the Service represented by
the ServiceUsageMBean object. The SLEE sets counter-type usage parameters
to zero and removes all samples from sample-type usage parameters.

@see javax.slee.management.ServiceUsageMBean#resetAllUsageParameters()

Resets the usage parameters of all SBBs within the Service represented by the ServiceUsageMBean object . The SLEE sets counter - type usage parameters to zero and removes all samples from sample - type usage parameters .


public Collection<ProfileID> getProfiles(String profileTableName)
			throws NullPointerException, UnrecognizedProfileTableNameException,
			TransactionRolledbackLocalException, FacilityException {

		if (logger.isTraceEnabled()) {
			logger.trace("getProfiles( profileTableName = "
					+ profileTableName + " )");
		}

		profileManagement.getSleeContainer().getTransactionManager().mandateTransaction();

		try {
			return profileManagement.getProfileTable(
							profileTableName).getProfiles();
		} catch (NullPointerException e) {
			throw e;
		} catch (UnrecognizedProfileTableNameException e) {
			throw e;
		} catch (Throwable e) {
			throw new FacilityException(e.getMessage(), e);
		}
	}

public
Collection
<
ProfileID
>
getProfiles
(
String
profileTableName
)
throws
NullPointerException
,
UnrecognizedProfileTableNameException
,
TransactionRolledbackLocalException
,
FacilityException
{
if
(
logger
.
isTraceEnabled
(
)
)
{
logger
.
trace
(
"getProfiles( profileTableName = "
+
profileTableName
+
" )"
)
;
}
profileManagement
.
getSleeContainer
(
)
.
getTransactionManager
(
)
.
mandateTransaction
(
)
;
try
{
return
profileManagement
.
getProfileTable
(
profileTableName
)
.
getProfiles
(
)
;
}
catch
(
NullPointerException
e
)
{
throw
e
;
}
catch
(
UnrecognizedProfileTableNameException
e
)
{
throw
e
;
}
catch
(
Throwable
e
)
{
throw
new
FacilityException
(
e
.
getMessage
(
)
,
e
)
;
}
}

Get a collection of ProfileID objects that identify all the profiles
contained in the specified profile table. The collection returned is
immutable. Any attempt to modify it, either directly or indirectly, will
result in a java.lang.UnsupportedOperationException being thrown.

Note: A profile identifier for the profile table's default profile will
not be included in the collection returned by this method as the default
profile has no such identifier.

This method is a required transactional method.

@deprecated
@param profileTableName
- the name of the profile table.
@return a read-only collection of ProfileID objects identifying the
profiles contained in the specified profile table.
@throws java.lang.NullPointerException
- if profileTableName is null.
@throws UnrecognizedProfileTableNameException
- if a profile table with the specified name does not exist.
@throws TransactionRolledbackLocalException
- if this method was invoked without a valid transaction
context and the transaction started by this method failed to
commit.
@throws FacilityException
- if the profile identifies could not be obtained due to a
system-level failure.

Get a collection of ProfileID objects that identify all the profiles contained in the specified profile table . The collection returned is immutable . Any attempt to modify it either directly or indirectly will result in a java . lang . UnsupportedOperationException being thrown .


public ProfileTableActivity getProfileTableActivity(String profileTableName)
			throws NullPointerException, UnrecognizedProfileTableNameException,
			TransactionRolledbackLocalException, FacilityException {

		if (logger.isTraceEnabled()) {
			logger.trace("getProfileTableActivity( profileTableName = "
					+ profileTableName + " )");
		}

		final SleeTransactionManager sleeTransactionManager = profileManagement.getSleeContainer()
				.getTransactionManager();
		boolean terminateTx = sleeTransactionManager.requireTransaction();
		try {
			return profileManagement.getProfileTable(profileTableName).getActivity();
		} catch (NullPointerException e) {
			throw e;
		} catch (UnrecognizedProfileTableNameException e) {
			throw e;
		} catch (Throwable e) {
			throw new FacilityException("Failed to obtain profile table.", e);
		} finally {
			// never rollback
			try {
				sleeTransactionManager.requireTransactionEnd(terminateTx,false);
			} catch (Throwable e) {
				throw new FacilityException(e.getMessage(),e);
			}
		}
	}

Get a ProfileTableActivity object for a profile table.

This method is a required transactional method.

@param profileTableName
- the name of the profile table.
@return a ProfileTableActivity object for the profile table.
@throws java.lang.NullPointerException
- if profileTableName is null.
@throws UnrecognizedProfileTableNameException
- if a profile table with the specified name does not exist.
@throws TransactionRolledbackLocalException
- if this method was invoked without a valid transaction
context and the transaction started by this method failed to
commit.
@throws FacilityException
- if the activity could not be obtained due to a system-level
failure. This exception is also thrown if the method is
invoked on a ProfileFacility object provided to a resource
adaptor via its ResourceAdaptorContext.

Get a ProfileTableActivity object for a profile table .


public ProfileID getProfileByIndexedAttribute(
			java.lang.String profileTableName, java.lang.String attributeName,
			java.lang.Object attributeValue) throws NullPointerException,
			UnrecognizedProfileTableNameException,
			UnrecognizedAttributeException, AttributeNotIndexedException,
			AttributeTypeMismatchException,
			TransactionRolledbackLocalException, FacilityException {

		if (logger.isTraceEnabled()) {
			logger.trace("getProfileByIndexedAttribute( profileTableName = "
					+ profileTableName + " , attributeName = " + attributeName
					+ " , attributeValue = " + attributeValue + " )");
		}

		profileManagement.getSleeContainer().getTransactionManager().mandateTransaction();

		try {
			ProfileTableImpl profileTable = profileManagement.getProfileTable(
							profileTableName);
			if (profileTable.getProfileSpecificationComponent().isSlee11()) {
				throw new FacilityException(
						"JAIN SLEE 1.1 Specs forbidden the usage of this method on SLEE 1.1 Profile Tables");
			}
			Collection<ProfileID> profileIDs = profileTable.getProfilesByAttribute(attributeName,attributeValue,false);
			if (profileIDs.isEmpty()) {
				return null;
			}
			else {
				return profileIDs.iterator().next();
			}
		} catch (NullPointerException e) {
			throw e;
		} catch (UnrecognizedProfileTableNameException e) {
			throw e;
		} catch (UnrecognizedAttributeException e) {
			throw e;
		} catch (AttributeNotIndexedException e) {
			throw e;
		} catch (AttributeTypeMismatchException e) {
			throw e;
		} catch (Throwable e) {
			throw new FacilityException(e.getMessage(), e);
		}
	}

Get a ProfileID object that identifies the profile contained in the
specified profile table, where the specified profile attribute is set to
the specified value. In the case of a profile attribute of an array type,
the type of the specified value must be the base component type of the
array, not the array type itself, and the SLEE will return the profile
identifier of any profile that contains the value within the array.

Note: The profile table's default profile is not considered when
determining matching profiles as it has no profile identifier that can be
returned by this method.

This method is a required transactional method.

This method can only be invoked against profile tables created from SLEE
1.0 profile specifications. Attempting to invoke it on a profile table
created from a SLEE 1.1 profile specification causes a FacilityException
to be thrown.

@deprecated
@param profileTableName
- the name of the profile table.
@param attributeName
- the name of the profile's attribute to check.
@param attributeValue
- the value to compare the attribute with. Returns: the
profile identifier for the first matching profile, or null if
no matching profile was found.
@throws java.lang.NullPointerException
- if any attribute is null.
@throws UnrecognizedProfileTableNameException
- if a profile table with the specified name does not exist.
@throws UnrecognizedAttributeException
- if an attribute with the specified name is not defined in
the profile specification for the specified profile table.
@throws AttributeNotIndexedException
- if the specified attribute is not indexed in the profile
specification for the specified profile table.
@throws AttributeTypeMismatchException
- if the type of the supplied attribute value does not match
the type of the specified indexed attribute.
@throws TransactionRolledbackLocalException
- if this method was invoked without a valid transaction
context and the transaction started by this method failed to
commit.
@throws FacilityException
- if the profile identifier could not be obtained due to a
system-level failure.

Get a ProfileID object that identifies the profile contained in the specified profile table where the specified profile attribute is set to the specified value . In the case of a profile attribute of an array type the type of the specified value must be the base component type of the array not the array type itself and the SLEE will return the profile identifier of any profile that contains the value within the array .


public void displayResult() {
		//default impl of display;
		if (!context.isQuiet()) {
			// Translate the result to text
			String resultText = prepareResultText();

			// render results to out
			PrintWriter out = context.getWriter();
			out.println(resultText);
			out.flush();
		}
	}

public
void
displayResult
(
)
{
//default impl of display;
if
(
!
context
.
isQuiet
(
)
)
{
// Translate the result to text
String
resultText
=
prepareResultText
(
)
;
// render results to out
PrintWriter
out
=
context
.
getWriter
(
)
;
out
.
println
(
resultText
)
;
out
.
flush
(
)
;
}
}


protected String unfoldArray(String prefix, Object[] array, PropertyEditor editor)
	{
		//StringBuffer sb = new StringBuffer("\n");
        StringBuffer sb = new StringBuffer("[");
		for (int index = 0; index<array.length; index++) {
			if (editor != null) {
				editor.setValue(array[index]);
				sb.append(editor.getAsText());
			} else {
				sb.append(array[index].toString());
			}

            if (index < array.length-1) {
                sb.append(CID_SEPARATOR);
                //sb.append("\n");
            }
		}
		sb.append("]");

		return sb.toString();
	}

Default implementation.
@param prefix
@param array
@return


void execute(final ActivityHandle realHandle, final ActivityHandle refHandle,
			final FireableEventType eventType, final Object event,
			final Address address, final ReceivableService receivableService,
			final int eventFlags) throws ActivityIsEndingException,
			FireEventException, SLEEException,
			UnrecognizedActivityHandleException {

		final SleeTransaction tx = super.suspendTransaction();
		try {
			sleeEndpoint._fireEvent(realHandle, refHandle, eventType, event, address,
					receivableService, eventFlags,tx);
		} finally {
			if (tx != null) {
				super.resumeTransaction(tx);
			}
		}
	}

void execute ( final ActivityHandle realHandle , final ActivityHandle refHandle , final FireableEventType eventType , final Object event , final Address address , final ReceivableService receivableService , final int eventFlags ) throws ActivityIsEndingException , FireEventException , SLEEException , UnrecognizedActivityHandleException { final SleeTransaction tx = super . suspendTransaction ( ) ; try { sleeEndpoint . _fireEvent ( realHandle , refHandle , eventType , event , address , receivableService , eventFlags , tx ) ; } finally { if ( tx != null ) { super . resumeTransaction ( tx ) ; } } }

Executes a non transacted fire event operation.

@param realHandle
@param refHandle
@param eventType
@param event
@param address
@param receivableService
@param eventFlags
@throws ActivityIsEndingException
@throws FireEventException
@throws SLEEException
@throws UnrecognizedActivityHandleException

Executes a non transacted fire event operation .


public void bindName(Object ach, String name)
			throws NameAlreadyBoundException {
		final Node node = getNode();
		if (node.hasChild(name)) {
			throw new NameAlreadyBoundException("name already bound");
		} else {
			node.addChild(Fqn.fromElements(name)).put(CACHE_NODE_MAP_KEY, ach);
		}
	}

public
void
bindName
(
Object
ach
,
String
name
)
throws
NameAlreadyBoundException
{
final
Node
node
=
getNode
(
)
;
if
(
node
.
hasChild
(
name
)
)
{
throw
new
NameAlreadyBoundException
(
"name already bound"
)
;
}
else
{
node
.
addChild
(
Fqn
.
fromElements
(
name
)
)
.
put
(
CACHE_NODE_MAP_KEY
,
ach
)
;
}
}

Binds the specified aci name with the specified activity context handle
@param ach
@param name
@throws NameAlreadyBoundException


public Object unbindName(String name) throws NameNotBoundException {
		final Node node = getNode();
		final Node childNode = node.getChild(name);
		if (childNode == null) {
			throw new NameNotBoundException("name not bound");
		} else {
			final Object ach = childNode.get(CACHE_NODE_MAP_KEY);
			node.removeChild(name);
			return ach;
		}
	}

public
Object
unbindName
(
String
name
)
throws
NameNotBoundException
{
final
Node
node
=
getNode
(
)
;
final
Node
childNode
=
node
.
getChild
(
name
)
;
if
(
childNode
==
)
{
throw
new
NameNotBoundException
(
"name not bound"
)
;
}
else
{
final
Object
ach
=
childNode
.
get
(
CACHE_NODE_MAP_KEY
)
;
node
.
removeChild
(
name
)
;
return
ach
;
}
}

Unbinds the specified aci name with the specified activity context id
@param name
@return
@throws NameNotBoundException


public Object lookupName(String name) {
		final Node childNode = getNode().getChild(name);
		if (childNode == null) {
			return null;
		} else {
			return childNode.get(CACHE_NODE_MAP_KEY);
		}
	}

public Object lookupName ( String name ) { final Node childNode = getNode ( ) . getChild ( name ) ; if ( childNode == null ) { return null ; } else { return childNode . get ( CACHE_NODE_MAP_KEY ) ; } }

Lookup of the activity context id bound to the specified aci name
@param name
@return


public Map getNameBindings() {

		Map result = new HashMap();
		Node childNode = null;
		Object name = null;
		for (Object obj : getNode().getChildren()) {
			childNode = (Node) obj;
			name = childNode.getFqn().getLastElement();
			result.put(name, childNode.get(CACHE_NODE_MAP_KEY));
		}
		return result;
	}

public Map getNameBindings ( ) { Map result = new HashMap ( ) ; Node childNode = null ; Object name = null ; for ( Object obj : getNode ( ) . getChildren ( ) ) { childNode = ( Node ) obj ; name = childNode . getFqn ( ) . getLastElement ( ) ; result . put ( name , childNode . get ( CACHE_NODE_MAP_KEY ) ) ; } return result ; }

Retrieves a map of the bindings. Key is the aci name and Value is the activity context handle
@return

Retrieves a map of the bindings . Key is the aci name and Value is the activity context handle


public Result next(ActivityContext ac,
			EventContext sleeEvent, Set<SbbEntityID> sbbEntitiesThatHandledCurrentEvent, SleeContainer sleeContainer) {

		SbbEntityID sbbEntityId = null;
		SbbEntity sbbEntity = null;
		EventEntryDescriptor mEventEntry = null;

		// get the highest priority sbb from sbb entities attached to AC
		for (Iterator<SbbEntityID> iter = ac.getSortedSbbAttachmentSet(sbbEntitiesThatHandledCurrentEvent).iterator(); iter
				.hasNext();) {
			sbbEntityId = iter.next();
			sbbEntity = sleeContainer.getSbbEntityFactory().getSbbEntity(sbbEntityId,true);
			if (sbbEntity == null) {
				// ignore, sbb entity has been removed
				continue;
			}
			if (eventRouterConfiguration.isConfirmSbbEntityAttachement() && !sbbEntity.isAttached(ac.getActivityContextHandle())) {
				// detached by a concurrent tx, see Issue 2313
				continue;
			}
			if (sleeEvent.getService() != null && !sleeEvent.getService().equals(sbbEntityId.getServiceID())) {
				if (!sleeEvent.isActivityEndEvent()) {
					continue;
				}
				else {
					return new Result(sbbEntity, false);
				}
			}
			// check event is allowed to be handled by the sbb
			mEventEntry = sbbEntity.getSbbComponent().getDescriptor().getEventEntries().get(sleeEvent.getEventTypeId());
			if (mEventEntry != null && mEventEntry.isReceived()) {
				return new Result(sbbEntity, true);
			} else {
				if (!sleeEvent.isActivityEndEvent()) {
					if (logger.isDebugEnabled()) {
						logger
						.debug("Event is not received by sbb descriptor of entity "
								+ sbbEntityId + ", will not deliver event to sbb entity ...");
					}
					continue;
				}
				else {
					return new Result(sbbEntity, false);
				}
			}
		}

		return null;

	}

Retrieves the next sbb entity to handle the event.

@param ac
@param sleeEvent
@param sbbEntitiesThatHandledCurrentEvent
@return Result that indicates the next sbb entity to handle the event,
note that sbb entities that are not entitled to *deliver* the
event (service id is set or the event is not defined in sbb
descriptor) will only be returned in case event is activity end
event.

Retrieves the next sbb entity to handle the event .


public boolean isHigherLevel(TraceLevel other) throws NullPointerException {
        if (other == null) throw new NullPointerException("other is null");

        return this.level < other.level;
    }

public
boolean
isHigherLevel
(
TraceLevel
other
)
throws
NullPointerException
{
if
(
other
==
)
throw
new
NullPointerException
(
"other is null"
)
;
return
this
.
level
<
other
.
level
;
}

Determine if this TraceLevel object represents a level that is higher than some other
TraceLevel object.  For the purposes of the comparison OFF is considered a higher level
than SEVERE, and FINEST is the lowest level.
@param other the TraceLevel object to compare this with.
@return true if the level represented by this TraceLevel
object is a higher level than the level represented by the specified
TraceLevel object, false otherwise.
@throws NullPointerException if other is null.

Determine if this TraceLevel object represents a level that is higher than some other TraceLevel object . For the purposes of the comparison OFF is considered a higher level than SEVERE and FINEST is the lowest level .