public static Set<Class> findWrapperClasses() {

        final List<TypeToWrapper> localTypeToWrapperList = getTypeToWrapper();

        Set<Class> resultList = new HashSet<Class>();

        if (localTypeToWrapperList != null) {
            for (TypeToWrapper typeToWrapper : localTypeToWrapperList) {
                resultList.add(typeToWrapper.getWrapperType());
            }
        }

        return resultList;

    }

public static Set < Class > findWrapperClasses ( ) { final List < TypeToWrapper > localTypeToWrapperList = getTypeToWrapper ( ) ; Set < Class > resultList = new HashSet < Class > ( ) ; if ( localTypeToWrapperList != null ) { for ( TypeToWrapper typeToWrapper : localTypeToWrapperList ) { resultList . add ( typeToWrapper . getWrapperType ( ) ) ; } } return resultList ; }

Gets a list with all wrapper classes.

@return a list with all wrapper classes


public static Set<ImplicitContextData> getImplicitContextDataProviders() {
        final Set<ImplicitContextData> result = new HashSet<ImplicitContextData>();

        for (Class clazz : ContextProviderServiceLoader.getServiceLocator().getImplicitContextProvider()) {

            try {
                if (ImplicitContextData.class.isAssignableFrom(clazz)) {
                    ImplicitContextData instance = (ImplicitContextData)(clazz.newInstance());
                    result.add(instance);
                }
            }
            catch (Throwable e) {
                // to be ignored
            }

        }

        return result;
    }

public
static
Set
<
ImplicitContextData
>
getImplicitContextDataProviders
(
)
{
final
Set
<
ImplicitContextData
>
result
=
new
HashSet
<
ImplicitContextData
>
(
)
;
for
(
Class
clazz
:
ContextProviderServiceLoader
.
getServiceLocator
(
)
.
getImplicitContextProvider
(
)
)
{
try
{
if
(
ImplicitContextData
.
class
.
isAssignableFrom
(
clazz
)
)
{
ImplicitContextData
instance
=
(
ImplicitContextData
)
(
clazz
.
newInstance
(
)
)
;
result
.
add
(
instance
)
;
}
}
catch
(
Throwable
e
)
{
// to be ignored
}
}
return
result
;
}

Generic function to get a implicit data provider classes from resource files.

@return a set that contains all context provider type the were found

Generic function to get a implicit data provider classes from resource files .


public static List<TypeToWrapper> getAvailableWrappers() {

        final List<TypeToWrapper> result = new ArrayList<TypeToWrapper>();

        for (Class clazz : ContextProviderServiceLoader.getServiceLocator().getContextProvider()) {

            try {
                if (WrappedContextData.class.isAssignableFrom(clazz)) {
                    // try to create instance to get the wrapped type
                    final WrappedContextData instance = (WrappedContextData)clazz.newInstance();
                    result.add(new TypeToWrapper(instance.getWrappedType(), clazz));
                }
            }
            catch (Throwable e) {
                // to be ignored
            }

        }

        return result;
    }

Method to get all available wrappers.

@return all wrapping between wrapper classes and their wrapped types.


private void initConnectors() {

        // first get all connector configuration Names
        Set<String> connectorConfigurationNames = this.getConnectorConfigurationNames();

        for (String connectorConfigurationName : connectorConfigurationNames) {

            Connector connector = this.createConnector(connectorConfigurationName);

            if (connector != null) {

                this.connectorMap.put(connectorConfigurationName, connector);

            }

        }

        // Add mandatory logger
        if (!isConnectorConfigured(LogConnector.class)) {
            Connector logConnector = new LogConnector();
            this.connectorMap.put("LOGGER", logConnector);
        }

    }


final void sendErrorReportToConnectors(ConnectorOutputProvider connectorOutputProvider) {

        for (Connector connector : this.connectorMap.values()) {

            connector.sendErrorReport(connectorOutputProvider);

        }
    }

final void sendErrorReportToConnectors ( ConnectorOutputProvider connectorOutputProvider ) { for ( Connector connector : this . connectorMap . values ( ) ) { connector . sendErrorReport ( connectorOutputProvider ) ; } }

Send error report to all initialized connector instances.

@param connectorOutputProvider the context data provider used for output

Send error report to all initialized connector instances .


final Set<String> getConnectorConfigurationNames() {

        Set<String> connectorNames = new HashSet<String>();

        Enumeration<Object> keyEnumeration = getSystemProperties().keys();
        while (keyEnumeration.hasMoreElements()) {
            String key = keyEnumeration.nextElement().toString();

            // check if property key has tracee connector format
            Matcher matcher = KEY_MATCHER_PATTERN.matcher(key);
            if (matcher.matches() && matcher.groupCount() > 0) {

                connectorNames.add(matcher.group(1));

            }

        }

        return connectorNames;

    }

Extracts all names for connector configurations from System properties.

@return a Set containing all connector configuration names

Extracts all names for connector configurations from System properties .


final Map<String, String> getPropertiesForConnectorConfigurationName(final String connectorName) {

        final Map<String, String> propertyMap = new HashMap<String, String>();

        final String patternString = String.format(CONNECTOR_PROPERTY_GRABBER_PATTERN, connectorName);
        final Pattern propertyGrabPattern = Pattern.compile(patternString);

        final Set<Map.Entry<Object, Object>> entries = getSystemProperties().entrySet();

        for (Map.Entry<Object, Object> entry : entries) {
            final String key = entry.getKey().toString();
            final Object value = entry.getValue();

            // check if property key has tracee connector format
            final Matcher matcher = propertyGrabPattern.matcher(key);
            if (value != null && matcher.matches() && matcher.groupCount() > 0) {

                final String propertyName = matcher.group(1);

                propertyMap.put(propertyName, value.toString());

            }

        }

        return propertyMap;

    }

Collects all properties for a given connector configuration name and writes them to a Map.

@param connectorName the name of the connector configuration
@return a Map containing all properties for a connector configuration name

Collects all properties for a given connector configuration name and writes them to a Map .


final Connector createConnector(final String connectorConfigurationName) {

        Map<String, String> propertyMap = this.getPropertiesForConnectorConfigurationName(connectorConfigurationName);
        String type = propertyMap.get(TraceeContextLoggerConstants.SYSTEM_PROPERTY_CONTEXT_LOGGER_CONNECTOR_TYPE);

        // get canonical class name for well known connectors
        if (WELL_KNOW_CONNECTOR_MAPPINGS.containsKey(type)) {
            type = WELL_KNOW_CONNECTOR_MAPPINGS.get(type);
        }

        try {

            // try to create connector instance
            Connector connector = (Connector)Class.forName(type).newInstance();

            // now try to call init method
            connector.init(propertyMap);

            return connector;

        }
        catch (Exception e) {
            LOGGER.error("An error occurred while creating connector with name '" + connectorConfigurationName + "' of type '" + type + "'", e);
        }

        return null;
    }

Tries to create a Connector for a given connector configuration name.

@param connectorConfigurationName the name of the connector configuration
@return the connector if it could be created and initialized without error, otherwise null

Tries to create a Connector for a given connector configuration name .


private boolean isConnectorConfigured(Class connectorClass) {
        for (Connector connector : this.connectorMap.values()) {

            if (connectorClass.isInstance(connector)) {
                return true;
            }

        }

        return false;
    }

private boolean isConnectorConfigured ( Class connectorClass ) { for ( Connector connector : this . connectorMap . values ( ) ) { if ( connectorClass . isInstance ( connector ) ) { return true ; } } return false ; }

Checks whether the LogConnector is defined or not.

@param connectorClass the connector to check for
@return true, if LogConnector is already defined, otherwise false.

Checks whether the LogConnector is defined or not .


boolean hasGetterPrefixInMethodName(Method method) {

        String methodName = method.getName();
        if (methodName != null) {

            for (String prefix : GETTER_PREFIXES) {

                if (methodName.startsWith(prefix)) {
                    return true;
                }
            }

        }
        return false;
    }

boolean hasGetterPrefixInMethodName ( Method method ) { String methodName = method . getName ( ) ; if ( methodName != null ) { for ( String prefix : GETTER_PREFIXES ) { if ( methodName . startsWith ( prefix ) ) { return true ; } } } return false ; }

Getter method names must have a specific prefix.

@param method the method to check
@return true, if the method name prefix is a getter Prefix, otherwise false

Getter method names must have a specific prefix .


boolean isPublicNonStaticMethod(final Method method) {
        int modifiers = method.getModifiers();
        return !Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers);
    }

boolean isPublicNonStaticMethod ( final Method method ) { int modifiers = method . getModifiers ( ) ; return ! Modifier . isStatic ( modifiers ) && Modifier . isPublic ( modifiers ) ; }

Getter methods must be public and not be static.

@param method the method to check
@return true if the method is not static and public, otherwise false

Getter methods must be public and not be static .


boolean hasCompatibleReturnTypes(Class type, Method method) {

        Field correspondingField = getCorrespondingField(type, method);

        return correspondingField != null && method.getReturnType().isAssignableFrom(correspondingField.getType());

    }

boolean hasCompatibleReturnTypes ( Class type , Method method ) { Field correspondingField = getCorrespondingField ( type , method ) ; return correspondingField != null && method . getReturnType ( ) . isAssignableFrom ( correspondingField . getType ( ) ) ; }

Getter method and field must have compatible fields.

@param type the type to search the field in
@param method the method to check
@return true, if field type is assignable to methods return type

Getter method and field must have compatible fields .


Field getCorrespondingField(Class type, Method method) {

        try {
            return type.getDeclaredField(GetterUtilities.getFieldName(method));
        }
        catch (NoSuchFieldException e) {
            return null;
        }

    }

Field getCorrespondingField ( Class type , Method method ) { try { return type . getDeclaredField ( GetterUtilities . getFieldName ( method ) ) ; } catch ( NoSuchFieldException e ) { return null ; } }

Helper method for getting a corresponsing field for a method

@param type the type to search the field in
@param method the getter method to search the field for
@return the Field or null if the field for the passed method doesn't exists


public static boolean isGetterMethod(final String methodName) {

        if (methodName != null) {

            for (String prefix : GETTER_PREFIXES) {
                if (methodName.startsWith(prefix)) {
                    return true;
                }
            }

        }

        return false;
    }

public static boolean isGetterMethod ( final String methodName ) { if ( methodName != null ) { for ( String prefix : GETTER_PREFIXES ) { if ( methodName . startsWith ( prefix ) ) { return true ; } } } return false ; }

Checks whether the method name starts with a getter prefix.

@param methodName the method name to check for
@return true if the method name starts with eiher one of values stored in GETTER_PREFIXES

Checks whether the method name starts with a getter prefix .


static String capitalizeFirstCharOfString(final String input) {
        if (input == null || input.length() == 0) {
            return "";
        }
        else if (input.length() == 1) {
            return input.toUpperCase();
        }
        else {
            return input.substring(0, 1).toUpperCase() + input.substring(1);
        }
    }

static String capitalizeFirstCharOfString ( final String input ) { if ( input == null || input . length ( ) == 0 ) { return "" ; } else if ( input . length ( ) == 1 ) { return input . toUpperCase ( ) ; } else { return input . substring ( 0 , 1 ) . toUpperCase ( ) + input . substring ( 1 ) ; } }

Capitalizes first char of an input string.

@param input the string to be processed;
@return The input string with the first capitalized char. Returns empty string, if passed input String is null or empty.

Capitalizes first char of an input string .


static String decapitalizeFirstCharOfString(final String input) {
        if (input == null || input.length() == 0) {
            return "";
        }
        else if (input.length() == 1) {
            return input.toLowerCase();
        }
        else {
            return input.substring(0, 1).toLowerCase() + input.substring(1);
        }
    }

static String decapitalizeFirstCharOfString ( final String input ) { if ( input == null || input . length ( ) == 0 ) { return "" ; } else if ( input . length ( ) == 1 ) { return input . toLowerCase ( ) ; } else { return input . substring ( 0 , 1 ) . toLowerCase ( ) + input . substring ( 1 ) ; } }

Decapitalizes first char of an input string.

@param input the string to be processed;
@return The input string with the first capitalized char. Returns empty string, if passed input String is null or empty.

Decapitalizes first char of an input string .


static String stripGetterPrefix(final String input) {

        if (input != null) {
            for (String prefix : GETTER_PREFIXES) {
                if (input.startsWith(prefix)) {
                    return input.substring(prefix.length());
                }
            }
        }

        return input;
    }

static String stripGetterPrefix ( final String input ) { if ( input != null ) { for ( String prefix : GETTER_PREFIXES ) { if ( input . startsWith ( prefix ) ) { return input . substring ( prefix . length ( ) ) ; } } } return input ; }

Strips getter prefix from input string

@param input the input string to be processed
@return the string stripped by getter prefix


void sendErrorReportToConnectors(ProceedingJoinPoint proceedingJoinPoint, String annotatedId, Throwable e) {

		// try to get error message annotation
		ErrorMessage errorMessage = WatchdogUtils.getErrorMessageAnnotation(proceedingJoinPoint);

		if (errorMessage == null) {
			TraceeContextLogger
					.create()
					.enforceOrder()
					.apply()
					.logWithPrefixedMessage(MessagePrefixProvider.provideLogMessagePrefix(MessageLogLevel.ERROR, Watchdog.class), CoreImplicitContextProviders.COMMON,
							CoreImplicitContextProviders.TRACEE, WatchdogDataWrapper.wrap(annotatedId, proceedingJoinPoint), e);
		} else {
			TraceeContextLogger
					.create()
					.enforceOrder()
					.apply()
					.logWithPrefixedMessage(MessagePrefixProvider.provideLogMessagePrefix(MessageLogLevel.ERROR, Watchdog.class),
							TraceeMessage.wrap(errorMessage.value()), CoreImplicitContextProviders.COMMON, CoreImplicitContextProviders.TRACEE,
							WatchdogDataWrapper.wrap(annotatedId, proceedingJoinPoint), e);
		}
	}

void
sendErrorReportToConnectors
(
ProceedingJoinPoint
proceedingJoinPoint
,
String
annotatedId
,
Throwable
e
)
{
// try to get error message annotation
ErrorMessage
errorMessage
=
WatchdogUtils
.
getErrorMessageAnnotation
(
proceedingJoinPoint
)
;
if
(
errorMessage
==
)
{
TraceeContextLogger
.
create
(
)
.
enforceOrder
(
)
.
apply
(
)
.
logWithPrefixedMessage
(
MessagePrefixProvider
.
provideLogMessagePrefix
(
MessageLogLevel
.
ERROR
,
Watchdog
.
class
)
,
CoreImplicitContextProviders
.
COMMON
,
CoreImplicitContextProviders
.
TRACEE
,
WatchdogDataWrapper
.
wrap
(
annotatedId
,
proceedingJoinPoint
)
,
e
)
;
}
else
{
TraceeContextLogger
.
create
(
)
.
enforceOrder
(
)
.
apply
(
)
.
logWithPrefixedMessage
(
MessagePrefixProvider
.
provideLogMessagePrefix
(
MessageLogLevel
.
ERROR
,
Watchdog
.
class
)
,
TraceeMessage
.
wrap
(
errorMessage
.
value
(
)
)
,
CoreImplicitContextProviders
.
COMMON
,
CoreImplicitContextProviders
.
TRACEE
,
WatchdogDataWrapper
.
wrap
(
annotatedId
,
proceedingJoinPoint
)
,
e
)
;
}
}

Sends the error reports to all connectors.

@param proceedingJoinPoint the aspectj calling context
@param annotatedId         the id defined in the watchdog annotation

Sends the error reports to all connectors .


public Object apply(ContextLoggerConfiguration contextLoggerConfiguration, Object instanceToWrap) {

		// check for implicit context
		if (IsImplicitContextEnumValuePredicate.getInstance().apply(instanceToWrap)) {
			return createInstance((Class) contextLoggerConfiguration.getImplicitContextProviderClass((ImplicitContext) instanceToWrap));
		}

		// now try to find instance type in known wrapper types map
		Class matchingWrapperType = contextLoggerConfiguration.getContextProviderClass(instanceToWrap.getClass());
		if (matchingWrapperType == null) {

			// now try to find instance type in TypeToWrapper List
			for (TypeToWrapper wrapper : contextLoggerConfiguration.getWrapperList()) {
				if (wrapper.getWrappedInstanceType().isAssignableFrom(instanceToWrap.getClass())) {
					matchingWrapperType = wrapper.getWrapperType();
					break;
				}
			}

		}

		if (matchingWrapperType != null) {
			// now create wrapper instance
			try {
				WrappedContextData wrapperInstance = (WrappedContextData) createInstance(matchingWrapperType);
				wrapperInstance.setContextData(instanceToWrap);

				return wrapperInstance;
			} catch (Exception e) {
				// continue

			}
		}

		return instanceToWrap;
	}

Wraps the passed instance inside a matching tracee context logging provider instance.
Will return the passed instance, if no matching tracee context logging provider exists.

@param contextLoggerConfiguration the configuration to use
@param instanceToWrap             the instance to wrap
@return either a tracee context provider that encapsulates the passed instance or the instance itself if no matching context provider exists

Wraps the passed instance inside a matching tracee context logging provider instance . Will return the passed instance if no matching tracee context logging provider exists .


protected Object createInstance(final Class type) {
		if (type != null) {
			try {
				return type.newInstance();
			} catch (Exception e) {
				// should not occur
			}
		}
		return null;
	}

protected
Object
createInstance
(
final
Class
type
)
{
if
(
type
!=
)
{
try
{
return
type
.
newInstance
(
)
;
}
catch
(
Exception
e
)
{
// should not occur
}
}
return
;
}

Creates a new instance of the passed type via reflection.

@param type the type of the new instance
@return a new instance of the passed type or null if an exception occurred during the creation of the instance of if the passed type is null.

Creates a new instance of the passed type via reflection .


public static Profile getCurrentProfile() {

		// First get profile from system properties
		Profile profile = getProfileFromSystemProperties();

		// check if profile has been found otherwise try getting profile from file in classpath
		if (profile == null) {
			profile = getProfileFromFileInClasspath(ProfilePropertyNames.PROFILE_SET_BY_FILE_IN_CLASSPATH_FILENAME);
		}

		// use DEFAULT profile, if profile has not been found
		if (profile == null) {
			profile = ProfilePropertyNames.DEFAULT_PROFILE;
		}

		return profile;

	}

Gets the current profile.
Uses the following algorithm to determine the profile.
1. If System Property is set force it as profile
2. If Custom Profile resource can be located in classpath use that file as profile
3. Use default profile

@return

Gets the current profile . Uses the following algorithm to determine the profile . 1 . If System Property is set force it as profile 2 . If Custom Profile resource can be located in classpath use that file as profile 3 . Use default profile


public static Properties openProperties(final String propertyFileName) throws IOException {

		if (propertyFileName == null) {
			return null;
		}

		InputStream inputStream = null;
		try {
			inputStream = Profile.class.getResourceAsStream(propertyFileName);
			if (inputStream != null) {
				// file could be opened
				Properties properties = new Properties();
				properties.load(inputStream);
				return properties;
			} else {
				// file doesn't exist
				return null;
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}

public
static
Properties
openProperties
(
final
String
propertyFileName
)
throws
IOException
{
if
(
propertyFileName
==
)
{
return
;
}
InputStream
inputStream
=
;
try
{
inputStream
=
Profile
.
class
.
getResourceAsStream
(
propertyFileName
)
;
if
(
inputStream
!=
)
{
// file could be opened
Properties
properties
=
new
Properties
(
)
;
properties
.
load
(
inputStream
)
;
return
properties
;
}
else
{
// file doesn't exist
return
;
}
}
finally
{
if
(
inputStream
!=
)
{
inputStream
.
close
(
)
;
}
}
}

Loads properties from resources.

@param propertyFileName the property file name to load
@return the properties, or null if the properties can't be found
@throws IOException if property file can't be opened


private void fillManualContextOverrideMap(final String[] contexts, final boolean value) {
		if (contexts != null) {

			for (String context : contexts) {

				if (!context.isEmpty()) {
					this.manualContextOverrides.put(context, value);
				}

			}

		}
	}

private void fillManualContextOverrideMap ( final String [ ] contexts , final boolean value ) { if ( contexts != null ) { for ( String context : contexts ) { if ( ! context . isEmpty ( ) ) { this . manualContextOverrides . put ( context , value ) ; } } } }

Adds passed contexts value pairs to manualContextOverrides.

@param contexts The property name of the context data.
@param value    the value which should be set.

Adds passed contexts value pairs to manualContextOverrides .


private TraceeContextStringRepresentationBuilderImpl createContextStringRepresentationLogBuilder() {

		TraceeContextStringRepresentationBuilderImpl traceeContextStringRepresentationBuilderImpl = new TraceeContextStringRepresentationBuilderImpl();
		traceeContextStringRepresentationBuilderImpl.setManualContextOverrides(this.getManualContextOverrides());
		traceeContextStringRepresentationBuilderImpl.setProfile(this.getProfile());
		traceeContextStringRepresentationBuilderImpl.setEnforceOrder(this.getEnforceOrder());
		traceeContextStringRepresentationBuilderImpl.setOutputWriterConfiguration(this.getOutputWriterConfiguration());

		return traceeContextStringRepresentationBuilderImpl;
	}

Creates a TraceeGsonContextStringRepresentationBuilder instance which can be used for creating the createStringRepresentation message.

@return An instance of TraceeGsonContextStringRepresentationBuilder


public static boolean checkIfMethodThrowsContainsPassedException(final ProceedingJoinPoint proceedingJoinPoint, Throwable thrownException) {

        if (proceedingJoinPoint == null || thrownException == null) {
            return false;
        }

        Class[] throwsClassesFromMethodSignature = getDefinedThrowsFromMethodSignature(proceedingJoinPoint);
        return checkClassIsDefinedInThrowsException(throwsClassesFromMethodSignature, thrownException);
    }

Checks whether the passed Throwable is contained in methods throws part.

@param proceedingJoinPoint The aspectj join point
@param thrownException The Throwable which must be looked for
@return true if Throwable was found and must be suppressed, otherwise false

Checks whether the passed Throwable is contained in methods throws part .


public static boolean checkClassIsDefinedInThrowsException(Class[] classes, Throwable thrownException) {

        // return false if either passed classes array or thrownException are null.
        if (classes == null || thrownException == null) {
            return false;
        }

        // loop through classes array to check for matching type
        for (Class clazz : classes) {

            if (clazz.isInstance(thrownException)) {
                return true;
            }

        }

        return false;
    }

Checks whether the passed Throwable is defined included in passed classes array or is subtype of one of the included classes.

@param classes the classes to search
@param thrownException the Throwable which must be searched for
@return true if Throwable was found, otherwise false

Checks whether the passed Throwable is defined included in passed classes array or is subtype of one of the included classes .


public static Class[] getDefinedThrowsFromMethodSignature(final ProceedingJoinPoint proceedingJoinPoint) {

        if (proceedingJoinPoint == null) {
            return new Class[0];
        }

        // get watchdog annotation from method
        MethodSignature methodSignature = (MethodSignature)proceedingJoinPoint.getSignature();

        return methodSignature.getMethod().getExceptionTypes();
    }

public
static
Class
[
]
getDefinedThrowsFromMethodSignature
(
final
ProceedingJoinPoint
proceedingJoinPoint
)
{
if
(
proceedingJoinPoint
==
)
{
return
new
Class
[
0
]
;
}
// get watchdog annotation from method
MethodSignature
methodSignature
=
(
MethodSignature
)
proceedingJoinPoint
.
getSignature
(
)
;
return
methodSignature
.
getMethod
(
)
.
getExceptionTypes
(
)
;
}

Gets all Exceptions declared at the throws part of the method signature.

@param proceedingJoinPoint the proceeding join point to get the method signature from.
@return All defined exceptions that must be caught (are defined in the method signature in the throws part)

Gets all Exceptions declared at the throws part of the method signature .


public static boolean checkProcessWatchdog(final Watchdog watchdogAnnotation, final ProceedingJoinPoint proceedingJoinPoint, final Throwable throwable) {
        // check if watchdog aspect processing is deactivated by annotation
        if (watchdogAnnotation != null && watchdogAnnotation.isActive()) {

            // checks if throws annotations must be suppressed
            boolean throwableIsPartOfThrowsDeclaration = WatchdogUtils.checkIfMethodThrowsContainsPassedException(proceedingJoinPoint, throwable);

            if (!watchdogAnnotation.suppressThrowsExceptions() || (watchdogAnnotation.suppressThrowsExceptions() && !throwableIsPartOfThrowsDeclaration)) {

                return true;

            }

        }

        return false;
    }

Checks whether the exception should be processed or not.

@param watchdogAnnotation the watchdog annotation to check.
@return true, if passed watchdogAnnotation is not null and not disabled vie system properties, otherwise false.

Checks whether the exception should be processed or not .


public final @NotNull S hasSize(int expected) {
    isNotNull();
    int size = actualGroupSize();
    if (size == expected) {
      return myself();
    }
    failIfCustomMessageIsSet();
    throw failure(format("expected size:<%s> but was:<%s> for <%s>", expected, size, actual));
  }

Verifies that the number of values in the actual group is equal to the given one.

@param expected the expected number of values in the actual group.
@return this assertion object.
@throws AssertionError if the number of values of the actual group is not equal to the given one.

Verifies that the number of values in the actual group is equal to the given one .


protected final void assertDoesNotHaveDuplicates() {
    isNotNull();
    Collection<?> duplicates = duplicatesFrom(actualAsList());
    if (duplicates.isEmpty()) {
      return;
    }
    failIfCustomMessageIsSet();
    throw failure(format("<%s> contains duplicate(s):<%s>", actual, duplicates));
  }

protected
final
void
assertDoesNotHaveDuplicates
(
)
{
isNotNull
(
)
;
Collection
<
>
duplicates
=
duplicatesFrom
(
actualAsList
(
)
)
;
if
(
duplicates
.
isEmpty
(
)
)
{
return
;
}
failIfCustomMessageIsSet
(
)
;
throw
failure
(
format
(
"<%s> contains duplicate(s):<%s>"
,
actual
,
duplicates
)
)
;
}

Verifies that the actual group of objects does not have duplicates.

@throws AssertionError if the actual group of objects is {@code null}.
@throws AssertionError if the actual group of objects has duplicates.

Verifies that the actual group of objects does not have duplicates .


public View getDropDownView(int index, View convertView, ViewGroup parent) {
        return dropDownViewFactory.getView(convertView, itemList.get(index));
    }

public View getDropDownView ( int index , View convertView , ViewGroup parent ) { return dropDownViewFactory . getView ( convertView , itemList . get ( index ) ) ; }

Declared by SpinnerAdapter, this method allows your spinner to show
different views in your drop down vs the 'closed' spinned box.

Declared by SpinnerAdapter this method allows your spinner to show different views in your drop down vs the closed spinned box .


protected final int reserveTermName(String name) {
		checkStatus(Status.INITIALIZING);
		checkInitializationPrecondition(TermUtils.isValidTermName(name), "Object '%s' is not a valid term name",name);
		checkInitializationPrecondition(!this.nameOrdinal.containsKey(name),"Term '%s' has been already reserved",name);
		this.nameOrdinal.put(name, ++this.ordinal);
		return this.ordinal;
	}

protected
final
int
reserveTermName
(
String
name
)
{
checkStatus
(
Status
.
INITIALIZING
)
;
checkInitializationPrecondition
(
TermUtils
.
isValidTermName
(
name
)
,
"Object '%s' is not a valid term name"
,
name
)
;
checkInitializationPrecondition
(
!
this
.
nameOrdinal
.
containsKey
(
name
)
,
"Term '%s' has been already reserved"
,
name
)
;
this
.
nameOrdinal
.
put
(
name
,
++
this
.
ordinal
)
;
return
this
.
ordinal
;
}

Allow the reservation of term names during the initialization of the
vocabulary.

@param name
then name of the term
@return a number that represents the position in which the term was
reserved
@throws IllegalArgumentException
if the specified name is not valid or it has been already
reserved.
@throws IllegalStateException
if the vocabulary has been already initialized.

Allow the reservation of term names during the initialization of the vocabulary .


protected final <S extends ImmutableTerm> void registerTerm(S term) {
		checkStatus(Status.INITIALIZING);
		checkInitializationPrecondition(this.nameOrdinal.containsKey(term.name()),"Term '%s' has not been reserved",term.name());
		checkInitializationPrecondition(term.ordinal()>=0 && term.ordinal()<=this.ordinal,"Invalid ordinal '%d' for reserved name '%s'",term.ordinal(),term.name());
		this.terms.put(term.ordinal(),this.termClass.cast(term));
	}

Upon reservation, the method enables registering the properly built
immutable term instance.

@param term
the term to be registered.
@throws IllegalArgumentException
if the specified term instance cannot be registered, either
because the ordinal is invalid or because another term
with the same name has already been registered.
@throws IllegalStateException
if the vocabulary has been already initialized.

Upon reservation the method enables registering the properly built immutable term instance .


protected final void initialize() {
		checkStatus(Status.INITIALIZING);
		if(this.terms.size()!=this.nameOrdinal.size()) {
			throw new IllegalStateException(
				String.format(
					"Vocabulary '%s' (%s) initialization failure: not all reserved names have been registered",
					this.namespace,
					getClass().getName()));
		}
		this.status=Status.INITIALIZED;
	}

Complete the initialization of the vocabulary. Beyond this point the
vocabulary can be put to use.

@throws IllegalStateException
if the vocabulary has been already initialized or not all the
reserved names have been registered.

Complete the initialization of the vocabulary . Beyond this point the vocabulary can be put to use .


public DataSet getRepresentation() {
		return
			DataDSL.
				dataSet().
					individual(newReference().toLocalIndividual().named("anonymous")).
						hasLink(KNOWS).
							referringTo(newReference().toManagedIndividual("unknownTemplate1").named("r1")).
					individual(newReference().toLocalIndividual().named("anonymous")).
						hasProperty(CREATED_ON).
							withValue(new Date()).
						hasLink(KNOWS).
							referringTo(newReference().toManagedIndividual("unknownTemplate2").named("r1")).
					individual(newReference().toManagedIndividual("unknownTemplate2").named("r1")).
						hasProperty(CREATION_DATE).
							withValue(new Date()).
						hasProperty(AGE).
							withValue(34).
						hasLink(HAS_FATHER).
							toIndividual(newReference().toLocalIndividual().named("Michel")).
								hasLink(HAS_WIFE).
									referringTo(newReference().toLocalIndividual().named("Consuelo")).
					build();
	}

public DataSet getRepresentation ( ) { return DataDSL . dataSet ( ) . individual ( newReference ( ) . toLocalIndividual ( ) . named ( "anonymous" ) ) . hasLink ( KNOWS ) . referringTo ( newReference ( ) . toManagedIndividual ( "unknownTemplate1" ) . named ( "r1" ) ) . individual ( newReference ( ) . toLocalIndividual ( ) . named ( "anonymous" ) ) . hasProperty ( CREATED_ON ) . withValue ( new Date ( ) ) . hasLink ( KNOWS ) . referringTo ( newReference ( ) . toManagedIndividual ( "unknownTemplate2" ) . named ( "r1" ) ) . individual ( newReference ( ) . toManagedIndividual ( "unknownTemplate2" ) . named ( "r1" ) ) . hasProperty ( CREATION_DATE ) . withValue ( new Date ( ) ) . hasProperty ( AGE ) . withValue ( 34 ) . hasLink ( HAS_FATHER ) . toIndividual ( newReference ( ) . toLocalIndividual ( ) . named ( "Michel" ) ) . hasLink ( HAS_WIFE ) . referringTo ( newReference ( ) . toLocalIndividual ( ) . named ( "Consuelo" ) ) . build ( ) ; }

Get custom representation with bad data

@return the representation


private static URIRef relativeResolution(URI target, URI base) {
		URIRef Base=URIRef.create(base); // NOSONAR
		URIRef R=URIRef.create(target); // NOSONAR
		URIRef T=URIRef.create(); // NOSONAR
		if(defined(R.scheme)) {
			T.scheme    = R.scheme;
			T.authority = R.authority;
			T.path      = removeDotSegments(R.path);
			T.query     = R.query;
		} else {
			if(defined(R.authority)) {
				T.authority = R.authority;
				T.path      = removeDotSegments(R.path);
				T.query     = R.query;
			} else {
				resolvePathOnlyTarget(Base, R, T);
			}
			T.scheme = Base.scheme;
		}
		T.fragment = R.fragment;
		return T;
	}

private
static
URIRef
relativeResolution
(
URI
target
,
URI
base
)
{
URIRef
Base
=
URIRef
.
create
(
base
)
;
// NOSONAR
URIRef
R
=
URIRef
.
create
(
target
)
;
// NOSONAR
URIRef
T
=
URIRef
.
create
(
)
;
// NOSONAR
if
(
defined
(
R
.
scheme
)
)
{
T
.
scheme
=
R
.
scheme
;
T
.
authority
=
R
.
authority
;
T
.
path
=
removeDotSegments
(
R
.
path
)
;
T
.
query
=
R
.
query
;
}
else
{
if
(
defined
(
R
.
authority
)
)
{
T
.
authority
=
R
.
authority
;
T
.
path
=
removeDotSegments
(
R
.
path
)
;
T
.
query
=
R
.
query
;
}
else
{
resolvePathOnlyTarget
(
Base
,
R
,
T
)
;
}
T
.
scheme
=
Base
.
scheme
;
}
T
.
fragment
=
R
.
fragment
;
return
T
;
}

5.2.  Relative Resolution

This section describes an algorithm for converting a URI reference
that might be relative to a given base URI into the parsed components
of the reference's target.  The components can then be recomposed, as
described in Section 5.3, to form the target URI.  This algorithm
provides definitive results that can be used to test the output of
other implementations.  Applications may implement relative reference
resolution by using some other algorithm, provided that the results
match what would be given by this one.

5.2.1.  Pre-parse the Base URI

The base URI (Base) is established according to the procedure of
Section 5.1 and parsed into the five main components described in
Section 3.  Note that only the scheme component is required to be
present in a base URI; the other components may be empty or
undefined.  A component is undefined if its associated delimiter does
not appear in the URI reference; the path component is never
undefined, though it may be empty.

Normalization of the base URI, as described in Sections 6.2.2 and
6.2.3, is optional.  A URI reference must be transformed to its
target URI before it can be normalized.

5.2.2.  Transform References

For each URI reference (R), the following pseudocode describes an
algorithm for transforming R into its target URI (T):
-- The URI reference is parsed into the five URI components
--
(R.scheme, R.authority, R.path, R.query, R.fragment) = parse(R);

-- A non-strict parser may ignore a scheme in the reference
-- if it is identical to the base URI's scheme.
--
if ((not strict) and (R.scheme == Base.scheme)) then
undefine(R.scheme);
endif;

if defined(R.scheme) then
T.scheme    = R.scheme;
T.authority = R.authority;
T.path      = remove_dot_segments(R.path);
T.query     = R.query;
else
if defined(R.authority) then
T.authority = R.authority;
T.path      = remove_dot_segments(R.path);
T.query     = R.query;
else
if (R.path == "") then
T.path = Base.path;
if defined(R.query) then
T.query = R.query;
else
T.query = Base.query;
endif;
else
if (R.path starts-with "/") then
T.path = remove_dot_segments(R.path);
else
T.path = merge(Base.path, R.path);
T.path = remove_dot_segments(T.path);
endif;
T.query = R.query;
endif;
T.authority = Base.authority;
endif;
T.scheme = Base.scheme;
endif;

T.fragment = R.fragment;


private static String merge(String path, String relativePath, boolean hasAuthority) {
		String parent=path;
		if(hasAuthority && parent.isEmpty()) {
			parent=SLASH;
		}
		return parent.substring(0,parent.lastIndexOf('/')+1).concat(relativePath);
	}

private static String merge ( String path , String relativePath , boolean hasAuthority ) { String parent = path ; if ( hasAuthority && parent . isEmpty ( ) ) { parent = SLASH ; } return parent . substring ( 0 , parent . lastIndexOf ( ' ' ) + 1 ) . concat ( relativePath ) ; }

5.2.3.  Merge Paths

The pseudocode above refers to a "merge" routine for merging a
relative-path reference with the path of the base URI.  This is
accomplished as follows:

o  If the base URI has a defined authority component and an empty
path, then return a string consisting of "/" concatenated with the
reference's path; otherwise,
o  return a string consisting of the reference's path component
appended to all but the last segment of the base URI's path (i.e.,
excluding any characters after the right-most "/" in the base URI
path, or excluding the entire base URI path if it does not contain
any "/" characters).

@param hasAuthority


private static String removeDotSegments(String path) {
		Deque<String> outputBuffer=new LinkedList<String>();
		String input=path==null?EMPTY:path;
		while(!input.isEmpty()) {
			input=processInput(outputBuffer, input);
		}
		return assembleInOrder(outputBuffer);
	}

private static String removeDotSegments ( String path ) { Deque < String > outputBuffer = new LinkedList < String > ( ) ; String input = path == null ? EMPTY : path ; while ( ! input . isEmpty ( ) ) { input = processInput ( outputBuffer , input ) ; } return assembleInOrder ( outputBuffer ) ; }

5.2.4.  Remove Dot Segments

The pseudocode also refers to a "remove_dot_segments" routine for
interpreting and removing the special "." and ".." complete path
segments from a referenced path.  This is done after the path is
extracted from a reference, whether or not the path was relative, in
order to remove any invalid or extraneous dot-segments prior to
forming the target URI.  Although there are many ways to accomplish
this removal process, we describe a simple method using two string
buffers.

1.  The input buffer is initialized with the now-appended path
components and the output buffer is initialized to the empty
string.

2.  While the input buffer is not empty, loop as follows:

A.  If the input buffer begins with a prefix of "../" or "./",
then remove that prefix from the input buffer; otherwise,

B.  if the input buffer begins with a prefix of "/./" or "/.",
where "." is a complete path segment, then replace that
prefix with "/" in the input buffer; otherwise,

C.  if the input buffer begins with a prefix of "/../" or "/..",
where ".." is a complete path segment, then replace that
prefix with "/" in the input buffer and remove the last
segment and its preceding "/" (if any) from the output
buffer; otherwise,

D.  if the input buffer consists only of "." or "..", then remove
that from the input buffer; otherwise,

E.  move the first path segment in the input buffer to the end of
the output buffer, including the initial "/" character (if
any) and any subsequent characters up to, but not including,
the next "/" character or the end of the input buffer.

3.  Finally, the output buffer is returned as the result of
remove_dot_segments.


public Name<String> name(String name, String... names) {
		return createName(assemble(name, names));
	}

public Name < String > name ( String name , String ... names ) { return createName ( assemble ( name , names ) ) ; }

Concatenates elements to form a dotted name, discarding null values
and empty strings.

@param name
the first element of the name
@param names
the remaining elements of the name
@return {@code name} and {@code names} concatenated by periods

Concatenates elements to form a dotted name discarding null values and empty strings .


public Name<String> name(Class<?> clazz, String... names) {
		return name(clazz.getCanonicalName(), names);
	}

public Name < String > name ( Class < ? > clazz , String ... names ) { return name ( clazz . getCanonicalName ( ) , names ) ; }

Concatenates a canonical class name and elements to form a dotted name, discarding any null values or empty strings
any null values or empty strings.

@param clazz
the first element of the name
@param names
the remaining elements of the name
@return {@code clazz} and {@code names} concatenated by periods

Concatenates a canonical class name and elements to form a dotted name discarding any null values or empty strings any null values or empty strings .


public static MediaType wildcard(String type) {
		requireNonNull(type,TYPE_CANNOT_BE_NULL);
		return new ImmutableMediaType(MediaTypes.preferredSyntax(),type,WILDCARD_TYPE,null,null);
	}

public static MediaType wildcard ( String type ) { requireNonNull ( type , TYPE_CANNOT_BE_NULL ) ; return new ImmutableMediaType ( MediaTypes . preferredSyntax ( ) , type , WILDCARD_TYPE , null , null ) ; }

Create a wildcard media type for a given primary type

@param type
The media type primary type
@return a wildcard media type for the given primary type
@throws NullPointerException
if the type is null
@throws IllegalArgumentException
if the specified type is not valid


public static MediaType wildcard(String type, String suffix) {
		requireNonNull(type,TYPE_CANNOT_BE_NULL);
		requireNonNull(suffix,"Suffix cannot be null");
		return new ImmutableMediaType(MediaTypes.preferredSyntax(),type,WILDCARD_TYPE,suffix,null);
	}

public
static
MediaType
wildcard
(
String
type
,
String
suffix
)
{
requireNonNull
(
type
,
TYPE_CANNOT_BE_NULL
)
;
requireNonNull
(
suffix
,
"Suffix cannot be null"
)
;
return
new
ImmutableMediaType
(
MediaTypes
.
preferredSyntax
(
)
,
type
,
WILDCARD_TYPE
,
suffix
,
)
;
}

Create a wildcard structured-syntax media type for a given primary type

@param type
The media type primary type
@param suffix
The suffix associated to the structured-syntax
@return a wildcard media type for the given primary type and suffix
@throws NullPointerException
if the type or suffix is null
@throws IllegalArgumentException
if the specified type or suffix is not valid

Create a wildcard structured - syntax media type for a given primary type


public static MediaType of(String type, String subtype) {
		requireNonNull(type,TYPE_CANNOT_BE_NULL);
		requireNonNull(subtype,"Subtype cannot be null");
		return fromString(type+"/"+subtype);
	}

public
static
MediaType
of
(
String
type
,
String
subtype
)
{
requireNonNull
(
type
,
TYPE_CANNOT_BE_NULL
)
;
requireNonNull
(
subtype
,
"Subtype cannot be null"
)
;
return
fromString
(
type
+
"/"
+
subtype
)
;
}

Create a media type

@param type
The media type primary type
@param subtype
The media type subtype
@return A media type for the specified media range
@throws NullPointerException
if any of the specified media range elements is null
@throws InvalidMediaTypeException
if any of the specified media range elements is not valid


public static String toHeader(final MediaType mediaType) {
		requireNonNull(mediaType,REFERENCE_MEDIA_TYPE_CANNOT_BE_NULL);
		final StringBuilder builder=
			new StringBuilder().
				append(mediaType.type().toLowerCase(Locale.ENGLISH)).
				append('/').
				append(mediaType.subType().toLowerCase(Locale.ENGLISH));
		final String suffix=mediaType.suffix();
		if(suffix!=null) {
			builder.append('+').append(suffix.toLowerCase(Locale.ENGLISH));
		}
		final Charset charset=mediaType.charset();
		if(charset!=null) {
			builder.append(";charset=").append(charset.name().toLowerCase(Locale.ENGLISH));
		}
		for(Entry<String,String> entry:mediaType.parameters().entrySet()) {
			final String key=entry.getKey();
			if(isStandardParameter(key)) {
				continue;
			}
			builder.append(';').append(key.toLowerCase(Locale.ENGLISH)).append('=').append(entry.getValue());
		}
		return builder.toString();
	}

public static String toHeader ( final MediaType mediaType ) { requireNonNull ( mediaType , REFERENCE_MEDIA_TYPE_CANNOT_BE_NULL ) ; final StringBuilder builder = new StringBuilder ( ) . append ( mediaType . type ( ) . toLowerCase ( Locale . ENGLISH ) ) . append ( ' ' ) . append ( mediaType . subType ( ) . toLowerCase ( Locale . ENGLISH ) ) ; final String suffix = mediaType . suffix ( ) ; if ( suffix != null ) { builder . append ( ' ' ) . append ( suffix . toLowerCase ( Locale . ENGLISH ) ) ; } final Charset charset = mediaType . charset ( ) ; if ( charset != null ) { builder . append ( ";charset=" ) . append ( charset . name ( ) . toLowerCase ( Locale . ENGLISH ) ) ; } for ( Entry < String , String > entry : mediaType . parameters ( ) . entrySet ( ) ) { final String key = entry . getKey ( ) ; if ( isStandardParameter ( key ) ) { continue ; } builder . append ( ' ' ) . append ( key . toLowerCase ( Locale . ENGLISH ) ) . append ( ' ' ) . append ( entry . getValue ( ) ) ; } return builder . toString ( ) ; }

Format the media type in a HTTP-header compliant manner using preferred
format.

@param mediaType
the media type to format
@return the compliant representation of the media type
@see [RFC
7231] Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content,
section 3.1.1.1

Format the media type in a HTTP - header compliant manner using preferred format .


@Override
	public void run() {
		ApplicationContext ctx = ApplicationContext.getInstance();
		LOGGER.debug("Starting resolution process on {}...",new Date());
		try(WriteSession session=ctx.createSession()) {
			ResourceSnapshot snapshot=
				session.find(
					ResourceSnapshot.class,
					this.name,
					DynamicResourceHandler.class);

			DataSet dataSet = this.handler.get(snapshot);
			Individual<?,?> individual =
				dataSet.
					individualOfId(ManagedIndividualId.createId(snapshot.name(),snapshot.templateId()));

			SnapshotResolver snapshotResolver =
				SnapshotResolver.
					builder().
						withReadSession(session).
						withCanonicalBase(CANONICAL_BASE).
						build();
			URI snapshotEndpoint = snapshotResolver.toURI(snapshot);

			individual.
				addValue(
					SNAPSHOT_ENDPOINT,
					Literals.newLiteral(snapshotEndpoint));
			individual.
				addValue(
					SNAPSHOT_RESOLUTION,
					Literals.newLiteral(roundtrip(snapshotResolver,snapshotEndpoint,snapshot)));

			this.handler.update(this.name, dataSet);

			session.modify(snapshot);
			session.saveChanges();
		} catch (Exception e) {
			LOGGER.error("Could not resolve resource",e);
		} finally {
			LOGGER.debug("Finalized resolution process");
		}
	}

@
Override
public
void
run
(
)
{
ApplicationContext
ctx
=
ApplicationContext
.
getInstance
(
)
;
LOGGER
.
debug
(
"Starting resolution process on {}..."
,
new
Date
(
)
)
;
try
(
WriteSession
session
=
ctx
.
createSession
(
)
)
{
ResourceSnapshot
snapshot
=
session
.
find
(
ResourceSnapshot
.
class
,
this
.
name
,
DynamicResourceHandler
.
class
)
;
DataSet
dataSet
=
this
.
handler
.
get
(
snapshot
)
;
Individual
<
,
>
individual
=
dataSet
.
individualOfId
(
ManagedIndividualId
.
createId
(
snapshot
.
name
(
)
,
snapshot
.
templateId
(
)
)
)
;
SnapshotResolver
snapshotResolver
=
SnapshotResolver
.
builder
(
)
.
withReadSession
(
session
)
.
withCanonicalBase
(
CANONICAL_BASE
)
.
build
(
)
;
URI
snapshotEndpoint
=
snapshotResolver
.
toURI
(
snapshot
)
;
individual
.
addValue
(
SNAPSHOT_ENDPOINT
,
Literals
.
newLiteral
(
snapshotEndpoint
)
)
;
individual
.
addValue
(
SNAPSHOT_RESOLUTION
,
Literals
.
newLiteral
(
roundtrip
(
snapshotResolver
,
snapshotEndpoint
,
snapshot
)
)
)
;
this
.
handler
.
update
(
this
.
name
,
dataSet
)
;
session
.
modify
(
snapshot
)
;
session
.
saveChanges
(
)
;
}
catch
(
Exception
e
)
{
LOGGER
.
error
(
"Could not resolve resource"
,
e
)
;
}
finally
{
LOGGER
.
debug
(
"Finalized resolution process"
)
;
}
}

Update the resource representation adding the path where the resource is
published and whether or not if given that URI it can be resolved to the
same resource.

Update the resource representation adding the path where the resource is published and whether or not if given that URI it can be resolved to the same resource .


@Override
	public int compareTo(Term other) {
		ImmutableTerm self = this;
		if(self.getDeclaringVocabulary() != other.getDeclaringVocabulary()) {
			throw new ClassCastException();
		}
		return self.ordinal - other.ordinal();
	}

@ Override public int compareTo ( Term other ) { ImmutableTerm self = this ; if ( self . getDeclaringVocabulary ( ) != other . getDeclaringVocabulary ( ) ) { throw new ClassCastException ( ) ; } return self . ordinal - other . ordinal ( ) ; }

Compares this term with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object.

Term constants are only comparable to other term constants of the same
vocabulary. The natural order implemented by this method is the order in
which the constants are declared.

Compares this term with the specified object for order . Returns a negative integer zero or a positive integer as this object is less than equal to or greater than the specified object .


public List<Name<String>> pendingAttachmentNames(String attachmentId) {
		List<Name<String>> result = new ArrayList<Name<String>>();
		NameSource source = this.attachmentNameSources.get(attachmentId);
		if(source!=null) {
			result.addAll(source.pendingNames);
		}
		return result;
	}

public List < Name < String > > pendingAttachmentNames ( String attachmentId ) { List < Name < String >> result = new ArrayList < Name < String > > ( ) ; NameSource source = this . attachmentNameSources . get ( attachmentId ) ; if ( source != null ) { result . addAll ( source . pendingNames ) ; } return result ; }

Return the pending names for the specified attachment.

@param attachmentId
the name of the attachment.
@return the pending names for the specified attachment.

Return the pending names for the specified attachment .


public void addAttachmentName(String attachmentId, Name<String> nextName) {
		nameSource(attachmentId).addName(nextName);
	}

public void addAttachmentName ( String attachmentId , Name < String > nextName ) { nameSource ( attachmentId ) . addName ( nextName ) ; }

Add a name to the list of available names for a given attachment.

@param attachmentId
the name of the attachment.
@param nextName
the member name.

Add a name to the list of available names for a given attachment .


public Name<String> nextAttachmentName(String attachmentId) {
		NameSource result = this.attachmentNameSources.get(attachmentId);
		if(result==null) {
			result=new NameSource("attachment <<"+attachmentId+">>");
		}
		return result.nextName();
	}

public
Name
<
String
>
nextAttachmentName
(
String
attachmentId
)
{
NameSource
result
=
this
.
attachmentNameSources
.
get
(
attachmentId
)
;
if
(
result
==
)
{
result
=
new
NameSource
(
"attachment <<"
+
attachmentId
+
">>"
)
;
}
return
result
.
nextName
(
)
;
}

Return the next available name for a given attachment. The name will be
removed from the list of available names for the specified attachment.

@param attachmentId
the name of the attachment.
@return the next available name for the specified attachment.

Return the next available name for a given attachment . The name will be removed from the list of available names for the specified attachment .


public static NameProvider create(Name<String> resource) {
		Objects.requireNonNull(resource,"Owner name cannot be null");
		return new NameProvider(resource);
	}

public
static
NameProvider
create
(
Name
<
String
>
resource
)
{
Objects
.
requireNonNull
(
resource
,
"Owner name cannot be null"
)
;
return
new
NameProvider
(
resource
)
;
}

Create a new name provider.

@param resource
the name of the owner of the name provider.
@return a name provider.


private static void parseSuffix(final MediaRange mr, final String mediaType) {
		final String subType=mr.subType;
		final int plusIdx=subType.lastIndexOf('+');
		if(plusIdx==0) {
			throw new InvalidMediaTypeException(mediaType,"missing subtype for structured media type ("+subType.substring(1)+")");
		} else if(plusIdx==subType.length()-1) {
			throw new InvalidMediaTypeException(mediaType,"missing suffix for structured media type ("+subType.substring(0,subType.length()-1)+")");
		} else if(plusIdx>0) {
			mr.subType=subType.substring(0,plusIdx);
			mr.suffix=subType.substring(plusIdx+1);
		} // Otherwise the subtype does not define a structuring syntax.
	}

As per RFC 6838, Section 4.2 structuring syntaxes specifier syntaxes are
defined after the last '+' symbol.

@see [RFC 6838]
Media Type Specifications and Registration Procedures, Section
4.2

As per RFC 6838 Section 4 . 2 structuring syntaxes specifier syntaxes are defined after the last + symbol .


private static void checkQuotedString(final String quotedString) {
		boolean quotedPair=false;
		for(int i=0;i<quotedString.length();i++) {
			final char ch=quotedString.charAt(i);
			if(quotedPair) {
				checkArgument(QUOTED_PAIR.get(ch),"Invalid quoted-pair character '%s' in quoted string '%s' at %d",ch,quotedString ,i);
				quotedPair=false;
			} else if(ch==SLASH) {
				quotedPair=true;
			} else {
				checkArgument(QDTEXT.get(ch),"Invalid character '%s' in quoted string '%s' at %d",ch,quotedString ,i);
			}

		}
		checkArgument(!quotedPair,"Missing quoted-pair character in quoted string '%s' at %d",quotedString,quotedString.length());
	}

Checks the given quoted string for illegal characters, as defined in RFC
7230, section 3.2.6.

@throws IllegalArgumentException
in case of illegal characters
@see Hypertext
Transfer Protocol (HTTP/1.1): Message Syntax and Routing, Section
3.2.6

Checks the given quoted string for illegal characters as defined in RFC 7230 section 3 . 2 . 6 .


@Override
	public Integer next() {
		if(!hasNext()) {
			throw new NoSuchElementException("No more codepoints available in the CharSequence");
		}
		this.index=this.next;
		final Integer codePoint = Character.codePointAt(this.s, this.next);
		this.next+=Character.charCount(codePoint);
		return codePoint;
	}

Returns the next code point in the iteration.

@return the next code point in the iteration
@throws NoSuchElementException
if the iteration has no more code points

Returns the next code point in the iteration .


@Override
	public void run() {
		ApplicationContext ctx = ApplicationContext.getInstance();
		Date date = new Date();
		LOGGER.debug("Starting update process on {}...",date);
		try(WriteSession session = ctx.createSession()) {
			ResourceSnapshot snapshot = session.find(ResourceSnapshot.class,this.name,DynamicResourceHandler.class);
			DataSet dataSet = this.handler.get(snapshot);
			Individual<?,?> individual =
				dataSet.
					individualOfId(
						ManagedIndividualId.
							createId(this.name, DynamicResourceHandler.ID));
			individual.
				addValue(
					REFRESHED_ON,
					Literals.of(date).dateTime());
			this.handler.update(this.name, dataSet);
			session.modify(snapshot);
			session.saveChanges();
		} catch (Exception e) {
			LOGGER.error("Could not update resource",e);
		} finally {
			LOGGER.debug("Finalized update process");
		}
	}

@
Override
public
void
run
(
)
{
ApplicationContext
ctx
=
ApplicationContext
.
getInstance
(
)
;
Date
date
=
new
Date
(
)
;
LOGGER
.
debug
(
"Starting update process on {}..."
,
date
)
;
try
(
WriteSession
session
=
ctx
.
createSession
(
)
)
{
ResourceSnapshot
snapshot
=
session
.
find
(
ResourceSnapshot
.
class
,
this
.
name
,
DynamicResourceHandler
.
class
)
;
DataSet
dataSet
=
this
.
handler
.
get
(
snapshot
)
;
Individual
<
,
>
individual
=
dataSet
.
individualOfId
(
ManagedIndividualId
.
createId
(
this
.
name
,
DynamicResourceHandler
.
ID
)
)
;
individual
.
addValue
(
REFRESHED_ON
,
Literals
.
of
(
date
)
.
dateTime
(
)
)
;
this
.
handler
.
update
(
this
.
name
,
dataSet
)
;
session
.
modify
(
snapshot
)
;
session
.
saveChanges
(
)
;
}
catch
(
Exception
e
)
{
LOGGER
.
error
(
"Could not update resource"
,
e
)
;
}
finally
{
LOGGER
.
debug
(
"Finalized update process"
)
;
}
}

Update the resource representation adding a temporal timestamp of when
the resource was last updated.

Update the resource representation adding a temporal timestamp of when the resource was last updated .


URI toURI() {
		StringBuilder builder=new StringBuilder();
		if(defined(this.scheme)) {
			builder.append(this.scheme);
			builder.append(":");
		}
		if(defined(this.authority)) {
			builder.append("//");
			builder.append(this.authority);
		}
		if(defined(this.path)) {
			builder.append(this.path);
		}
		if(defined(this.query)) {
			builder.append("?");
			builder.append(this.query);
		}
		if(defined(this.fragment)) {
			builder.append("#");
			builder.append(this.fragment);
		}
		String rawURI = builder.toString();
		return URI.create(rawURI);
	}

URI toURI ( ) { StringBuilder builder = new StringBuilder ( ) ; if ( defined ( this . scheme ) ) { builder . append ( this . scheme ) ; builder . append ( ":" ) ; } if ( defined ( this . authority ) ) { builder . append ( "//" ) ; builder . append ( this . authority ) ; } if ( defined ( this . path ) ) { builder . append ( this . path ) ; } if ( defined ( this . query ) ) { builder . append ( "?" ) ; builder . append ( this . query ) ; } if ( defined ( this . fragment ) ) { builder . append ( "#" ) ; builder . append ( this . fragment ) ; } String rawURI = builder . toString ( ) ; return URI . create ( rawURI ) ; }

5.3.  Component Recomposition

Parsed URI components can be recomposed to obtain the corresponding
URI reference string.  Using pseudocode, this would be:

result = ""

if defined(scheme) then
append scheme to result;
append ":" to result;
endif;

if defined(authority) then
append "//" to result;
append authority to result;
endif;

append path to result;

if defined(query) then
append "?" to result;
append query to result;
endif;

if defined(fragment) then
append "#" to result;
append fragment to result;
endif;

return result;

Note that we are careful to preserve the distinction between a
component that is undefined, meaning that its separator was not
present in the reference, and a component that is empty, meaning that
the separator was present and was immediately followed by the next
component separator or the end of the reference.


private static void closeQuietly(final InputStream is, final String message) {
		if(is!=null) {
		try {
			is.close();
		} catch (final Exception e) {
			if(LOGGER.isWarnEnabled()) {
				LOGGER.warn(message,e);
			}
		}
		}
	}

private static void closeQuietly ( final InputStream is , final String message ) { if ( is != null ) { try { is . close ( ) ; } catch ( final Exception e ) { if ( LOGGER . isWarnEnabled ( ) ) { LOGGER . warn ( message , e ) ; } } } }

Close an input stream logging possible failures.
@param is The input stream that is to be closed.
@param message The message to log in case of failure.

Close an input stream logging possible failures .


static boolean isNameStartChar(final int codePoint) {
		return
			(codePoint == ':')                             ||
			(codePoint >= 'A' && codePoint <= 'Z')         ||
			(codePoint == '_')                             ||
			(codePoint >= 'a' && codePoint <= 'z')         ||
			(codePoint >= 0xC0 && codePoint <= 0xD6)       ||
			(codePoint >= 0xD8 && codePoint <= 0xF6)       ||
			(codePoint >= 0xF8 && codePoint <= 0x2FF)      ||
			(codePoint >= 0x370 && codePoint <= 0x37D)     ||
			(codePoint >= 0x37F && codePoint <= 0x1FFF)    ||
			(codePoint >= 0x200C && codePoint <= 0x200D)   ||
			(codePoint >= 0x2070 && codePoint <= 0x218F)   ||
			(codePoint >= 0x2C00 && codePoint <= 0x2FEF)   ||
			(codePoint >= 0x3001 && codePoint <= 0xD7FF)   ||
			(codePoint >= 0xF900 && codePoint <= 0xFDCF)   ||
			(codePoint >= 0xFDF0 && codePoint <= 0xFFFD)   ||
			(codePoint >= 0x10000 && codePoint <= 0xEFFFF);
	}

static boolean isNameStartChar ( final int codePoint ) { return ( codePoint == ' ' ) || ( codePoint >= ' ' && codePoint <= ' ' ) || ( codePoint == ' ' ) || ( codePoint >= ' ' && codePoint <= ' ' ) || ( codePoint >= 0xC0 && codePoint <= 0xD6 ) || ( codePoint >= 0xD8 && codePoint <= 0xF6 ) || ( codePoint >= 0xF8 && codePoint <= 0x2FF ) || ( codePoint >= 0x370 && codePoint <= 0x37D ) || ( codePoint >= 0x37F && codePoint <= 0x1FFF ) || ( codePoint >= 0x200C && codePoint <= 0x200D ) || ( codePoint >= 0x2070 && codePoint <= 0x218F ) || ( codePoint >= 0x2C00 && codePoint <= 0x2FEF ) || ( codePoint >= 0x3001 && codePoint <= 0xD7FF ) || ( codePoint >= 0xF900 && codePoint <= 0xFDCF ) || ( codePoint >= 0xFDF0 && codePoint <= 0xFFFD ) || ( codePoint >= 0x10000 && codePoint <= 0xEFFFF ) ; }

Determines if a character is a Name start character.

@param codePoint
The code point of the character to be tested. For UTF-16
characters the code point corresponds to the value of the char
that represents the character.
@return {@code true} if {@code codePoint} is a Name start character,
otherwise {@code false}
@see Name definition in the Extensible Markup
Language (XML) 1.0 (Fifth Edition) specification.

Determines if a character is a Name start character .


static boolean isNameChar(final int codePoint) {
		return
			isNameStartChar(codePoint)                   ||
			(codePoint == '-')                           ||
			(codePoint == '.')                           ||
			(codePoint >= '0' && codePoint <= '9')       ||
			(codePoint == 0xB7)                          ||
			(codePoint >= 0x0300 && codePoint <= 0x036F) ||
			(codePoint >= 0x203F && codePoint <= 0x2040);
	}

static boolean isNameChar ( final int codePoint ) { return isNameStartChar ( codePoint ) || ( codePoint == ' ' ) || ( codePoint == ' ' ) || ( codePoint >= ' ' && codePoint <= ' ' ) || ( codePoint == 0xB7 ) || ( codePoint >= 0x0300 && codePoint <= 0x036F ) || ( codePoint >= 0x203F && codePoint <= 0x2040 ) ; }

Determines if a character is a Name character.

@param codePoint
The code point of the character to be tested. For UTF-8 and UTF-16
characters the code point corresponds to the value of the char
that represents the character.
@return {@code true} if {@code codePoint} is a Name character,
otherwise {@code false}
@see Name definition in the Extensible Markup
Language (XML) 1.0 (Fifth Edition) specification.

Determines if a character is a Name character .


static void checkToken(final String token, final String message, Object... args) {
		checkNotNull(message,"Message cannot be null");
		try {
			validateLength(token);
			validateCharacters(token);
		} catch (IllegalArgumentException e) {
			throw new InvalidTokenException(String.format(message,args),token,e);
		}
	}

static
void
checkToken
(
final
String
token
,
final
String
message
,
Object
...
args
)
{
checkNotNull
(
message
,
"Message cannot be null"
)
;
try
{
validateLength
(
token
)
;
validateCharacters
(
token
)
;
}
catch
(
IllegalArgumentException
e
)
{
throw
new
InvalidTokenException
(
String
.
format
(
message
,
args
)
,
token
,
e
)
;
}
}

Checks the given type name for illegal characters, as defined in RFC
7230, section 3.2.6.

@param token
the string to validate
@throws IllegalArgumentException
in case of illegal characters
@see Hypertext
Transfer Protocol (HTTP/1.1): Message Syntax and Routing, Section
3.2.6

Checks the given type name for illegal characters as defined in RFC 7230 section 3 . 2 . 6 .


public DataTransformator mediaType(MediaType mediaType) {
		checkNotNull(mediaType,MEDIA_TYPE_CANNOT_BE_NULL);
		DataTransformator result = new DataTransformator(this);
		result.setMediaType(mediaType);
		return result;
	}

public DataTransformator mediaType ( MediaType mediaType ) { checkNotNull ( mediaType , MEDIA_TYPE_CANNOT_BE_NULL ) ; DataTransformator result = new DataTransformator ( this ) ; result . setMediaType ( mediaType ) ; return result ; }

Create transformator with the specified media type

@param mediaType
the new media type
@return a new transformator with the same configuration except for the
media type, which is set to the specified one
@throws UnsupportedMediaTypeException
if the media type is not valid


static void registerAdapterClass(Class<?> clazz) {
		Objects.requireNonNull(clazz,"Adapter class cannot be null");
		TypeAdapter.ADAPTER_CLASSES.addIfAbsent(clazz);
	}

static
void
registerAdapterClass
(
Class
<
>
clazz
)
{
Objects
.
requireNonNull
(
clazz
,
"Adapter class cannot be null"
)
;
TypeAdapter
.
ADAPTER_CLASSES
.
addIfAbsent
(
clazz
)
;
}

Register a new adapter class.

@param clazz
the adapter class.
@throws NullPointerException
if the adapter class is {@code null}.


static <S,T> TypeAdapter<S,T> createAdapter(Class<? extends S> sourceType, Class<? extends T> targetType) {
		return doCreateAdapter(targetType,AdapterMethodValidator.newInstance(targetType, sourceType));
	}

static < S , T > TypeAdapter < S , T > createAdapter ( Class < ? extends S > sourceType , Class < ? extends T > targetType ) { return doCreateAdapter ( targetType , AdapterMethodValidator . newInstance ( targetType , sourceType ) ) ; }

Get an adapter capable of transforming instances of a source type into
instances of a target type.

@param sourceType
The type of the instances that the adapter should be able to
transform.
@param targetType
The type of instances that the adapter should be able to
create.
@return An adapter capable of transforming instances of the {@code sourceType}
into instances of the {@code targetType}.
@throws CannotAdaptClassesException
when no adapter capable of carrying out such transformation
is available.

Get an adapter capable of transforming instances of a source type into instances of a target type .


static <S,T> T adapt(S object, Class<? extends T> resultClass) {
		return TypeAdapter.<S,T>doCreateAdapter(resultClass, AdapterMethodValidator.newInstance(resultClass, object)).adapt(object);
	}

static < S , T > T adapt ( S object , Class < ? extends T > resultClass ) { return TypeAdapter . < S , T > doCreateAdapter ( resultClass , AdapterMethodValidator . newInstance ( resultClass , object ) ) . adapt ( object ) ; }

Transform a given object into an instance of the specified type.

@param object
The object that is to be transformed.
@param resultClass
The type of instance that is to be created.
@return An instance of type {@code resultClass} created upon the
specified @ object} .
@throws CannotAdaptClassesException
when no adapter capable of carrying out such transformation
is available.

Transform a given object into an instance of the specified type .


public ImmutableNamespaces withPrefix(String prefix, String namespaceURI) {
		Objects.requireNonNull(prefix, "Prefix cannot be null");
		Objects.requireNonNull(namespaceURI, "Namespace URI cannot be null");
		ImmutableNamespaces result=new ImmutableNamespaces(this.map);
		result.map.put(prefix, namespaceURI);
		return result;
	}

public
ImmutableNamespaces
withPrefix
(
String
prefix
,
String
namespaceURI
)
{
Objects
.
requireNonNull
(
prefix
,
"Prefix cannot be null"
)
;
Objects
.
requireNonNull
(
namespaceURI
,
"Namespace URI cannot be null"
)
;
ImmutableNamespaces
result
=
new
ImmutableNamespaces
(
this
.
map
)
;
result
.
map
.
put
(
prefix
,
namespaceURI
)
;
return
result
;
}

Create a copy of the namespaces which includes a mapping between a given
prefix and namespace URI.

@param prefix
the prefix to be added
@param namespaceURI
the namespace URI to be mapped to the prefix
@return a copy of the instance that includes the mapping between the
specified namespace URI and prefix.
@throws NullPointerException if the prefix or namespace URI are null.

Create a copy of the namespaces which includes a mapping between a given prefix and namespace URI .


public ImmutableNamespaces withoutPrefix(String... prefixes) {
		ImmutableNamespaces result=new ImmutableNamespaces(this.map);
		for(String prefix:prefixes) {
			result.map.remove(prefix);
		}
		return result;
	}

public ImmutableNamespaces withoutPrefix ( String ... prefixes ) { ImmutableNamespaces result = new ImmutableNamespaces ( this . map ) ; for ( String prefix : prefixes ) { result . map . remove ( prefix ) ; } return result ; }

Create a copy of the namespaces without the prefixes.

@param prefixes
the prefixes to be excluded from the copy
@return a copy of the instance that excludes the mappings for the
specified prefixes.

Create a copy of the namespaces without the prefixes .


public static String escapeXML(final CharSequence s) {
		final StringBuilder sb = new StringBuilder(s.length() * 2);
		final CodePointIterator iterator = new CodePointIterator(s);
		while (iterator.hasNext()) {
			final int codePoint = iterator.next();
			if (codePoint == '<') {
				sb.append(LT);
			} else if (codePoint == '>') {
				sb.append(GT);
			} else if (codePoint == '\"') {
				sb.append(QUOT);
			} else if (codePoint == '&') {
				sb.append(AMP);
			} else if (codePoint == '\'') {
				sb.append(APOS);
			} else {
				sb.appendCodePoint(codePoint);
			}
		}
		return sb.toString();
	}

public static String escapeXML ( final CharSequence s ) { final StringBuilder sb = new StringBuilder ( s . length ( ) * 2 ) ; final CodePointIterator iterator = new CodePointIterator ( s ) ; while ( iterator . hasNext ( ) ) { final int codePoint = iterator . next ( ) ; if ( codePoint == ' ' ) { sb . append ( LT ) ; } else if ( codePoint == ' ' ) { sb . append ( GT ) ; } else if ( codePoint == ' ' ) { sb . append ( QUOT ) ; } else if ( codePoint == ' ' ) { sb . append ( AMP ) ; } else if ( codePoint == ' ' ) { sb . append ( APOS ) ; } else { sb . appendCodePoint ( codePoint ) ; } } return sb . toString ( ) ; }

Escapes a character sequence so that it is valid XML.

@param s
The character sequence.
@return The escaped version of the character sequence.

Escapes a character sequence so that it is valid XML .


@Override
	public DataSet query(ResourceSnapshot resource, Query query, ReadSession session) throws InvalidQueryException {
		return QuerySupport.getDescription(resource.name(), query);
	}

@ Override public DataSet query ( ResourceSnapshot resource , Query query , ReadSession session ) throws InvalidQueryException { return QuerySupport . getDescription ( resource . name ( ) , query ) ; }

Instead of retrieving the contents of the resource, return a description
of the query received.

Instead of retrieving the contents of the resource return a description of the query received .


public final void addNameProvider(Name<String> containerName, NameProvider provider) {
		this.nameProviders.put(containerName, provider);
	}

public final void addNameProvider ( Name < String > containerName , NameProvider provider ) { this . nameProviders . put ( containerName , provider ) ; }

Add a name provider for a container resource.

@param containerName
the name of the container.
@param provider
the name provider.

Add a name provider for a container resource .


public final NameProvider nameProvider(Name<?> containerName) {
		NameProvider result = this.nameProviders.get(containerName);
		if(result==null) {
			throw new ApplicationRuntimeException("Unknown container '"+containerName+"'");
		}
		return result;
	}

public
final
NameProvider
nameProvider
(
Name
<
>
containerName
)
{
NameProvider
result
=
this
.
nameProviders
.
get
(
containerName
)
;
if
(
result
==
)
{
throw
new
ApplicationRuntimeException
(
"Unknown container '"
+
containerName
+
"'"
)
;
}
return
result
;
}

Return the name provider registered for a given container resource.

@param containerName
the name of the container.
@return the provider for the specified container resource.

Return the name provider registered for a given container resource .


public <T> T unwrap(final Class<? extends T> clazz) throws ApplicationEngineException {
		checkNotNull(clazz,"Target class cannot be null");
		if(!clazz.isInstance(this)) {
			throw new ApplicationEngineException("Application Engine implementation is not compatible with "+clazz.getCanonicalName());
		}
		return clazz.cast(this);
	}

Return an object of the specified type to allow access to the
provider-specific API. If the provider's ApplicationEngine implementation
does not support the specified class, the ApplicationEngineException is
thrown.

@param <T> the type of object to be returned
@param clazz
the class of the object to be returned. This is normally
either the underlying {@code ApplicationEngine} implementation
class or an interface that it implements.
@return an instance of the specified class
@throws ApplicationEngineException
if the provider does not support the call

Return an object of the specified type to allow access to the provider - specific API . If the provider s ApplicationEngine implementation does not support the specified class the ApplicationEngineException is thrown .


public boolean isOutOfScope() {
		// Files are always on scope
		if(this.directory==null) {
			return false;
		}

		// First, normalize
		final Path normalize=normalize();

		// If now we are a file, we are in scope
		if(normalize.directory==null) {
			return false;
		}

		// If we find a segment which is '..' we are out of scope
		final String[] segments=normalize.segments();
		boolean result=false;
		for(int i=0;i<segments.length && !result;i++) {
			result=isDotSegment(segments[i]);
		}
		return result;
	}

Checks if the path is out of the scope.

@return {@code true}, if is out of the scope, {@code false} otherwise

Checks if the path is out of the scope .


public Path withDirectory(final String directory) {
		final Path result = new Path(this);
		result.setDirectory(directory);
		return result;
	}

public Path withDirectory ( final String directory ) { final Path result = new Path ( this ) ; result . setDirectory ( directory ) ; return result ; }

Create a new path with a given directory.

@param directory the directory for the path
@return the new path

Create a new path with a given directory .


public Path withFile(final String file) {
		final Path result = new Path(this);
		result.setFile(file);
		return result;
	}

public Path withFile ( final String file ) { final Path result = new Path ( this ) ; result . setFile ( file ) ; return result ; }

Create a new path with a given file.

@param file the file for the path
@return the new path


private Path assembleRelativeSegments(final Path path, final Path base, final Deque<String> segments) {
		if(segments.isEmpty() && path.isDirectory() && base.isFile()) {
			segments.add(CURRENT);
		}

		return Path.create(assembleSegments(segments,path.getFile()));
	}

private Path assembleRelativeSegments ( final Path path , final Path base , final Deque < String > segments ) { if ( segments . isEmpty ( ) && path . isDirectory ( ) && base . isFile ( ) ) { segments . add ( CURRENT ) ; } return Path . create ( assembleSegments ( segments , path . getFile ( ) ) ) ; }

If there are no segments in the resolved path, and we are trying to
resolve a directory coming from a path, we have to make explicit that we
want the directory

If there are no segments in the resolved path and we are trying to resolve a directory coming from a path we have to make explicit that we want the directory


static <T> Class<T> getTypeParameter(Class<?> clazz, Class<? super T> bound) {
		Type t = checkNotNull(clazz);
		while (t instanceof Class<?>) {
			t = ((Class<?>) t).getGenericSuperclass();
		}
		/**
		 * This is not guaranteed to work for all cases with convoluted piping
		 * of type parameters: but it can at least resolve straight-forward
		 * extension with single type parameter (as per [Issue-89]). And when it
		 * fails to do that, will indicate with specific exception.
		 */
		if(t instanceof ParameterizedType) {
			Class<T> result=processParameterizedType(bound, (ParameterizedType) t);
			if(result!=null) {
				return result;
			}
		}
		throw new IllegalStateException("Cannot figure out type parameterization for "+ clazz.getName());
	}

Finds the type parameter for the given class which is assignable to the
bound class.

@param clazz
a parameterized class
@param bound
the type bound
@param <T>
the type bound
@return the class's type parameter

Finds the type parameter for the given class which is assignable to the bound class .


public static <T> PrimitiveObjectFactory<T> create(final Class<? extends T> valueClass) {
		checkNotNull(valueClass, "Value class cannot be null");
		checkArgument(valueClass.isPrimitive(), "Value class '" + valueClass.getName() + "' is not primitive");
		return new PrimitiveObjectFactory<T>(valueClass);
	}

public
static
<
T
>
PrimitiveObjectFactory
<
T
>
create
(
final
Class
<
extends
T
>
valueClass
)
{
checkNotNull
(
valueClass
,
"Value class cannot be null"
)
;
checkArgument
(
valueClass
.
isPrimitive
(
)
,
"Value class '"
+
valueClass
.
getName
(
)
+
"' is not primitive"
)
;
return
new
PrimitiveObjectFactory
<
T
>
(
valueClass
)
;
}

Create a primitive object factory for the specified primitive class

@param <T>
the primitive class type
@param valueClass
the primitive class to use
@return an object factory
@throws NullPointerException
if the specified class is {@code null}
@throws IllegalArgumentException
if the specified class is not a primitive class


public static List<Variant> createVariants(MediaType... mediaTypes) {
		return
			Variant.VariantListBuilder.
				newInstance().
					mediaTypes(mediaTypes).
					encodings().
					languages().
					add().
					build();
	}

public static List < Variant > createVariants ( MediaType ... mediaTypes ) { return Variant . VariantListBuilder . newInstance ( ) . mediaTypes ( mediaTypes ) . encodings ( ) . languages ( ) . add ( ) . build ( ) ; }

Get a list of acceptable variants. Current implementation only leverages
media type for the specification of variants.

@param mediaTypes
The list of acceptable media types.
@return A list of acceptable variants.

Get a list of acceptable variants . Current implementation only leverages media type for the specification of variants .


@SuppressWarnings("unchecked")
	public Individual<T,S> resolve(DataSet dataSet) {
		return (Individual<T,S>) dataSet.individualOfId(ref());
	}

@ SuppressWarnings ( "unchecked" ) public Individual < T , S > resolve ( DataSet dataSet ) { return ( Individual < T , S > ) dataSet . individualOfId ( ref ( ) ) ; }

Find the individual of the data set with the same identifier

@param dataSet
the data set
@return the individual with the same identifier, or {@code null} if no
individual has the same identifier.


@Factory
    public static <T extends ViewGroup> Matcher<T> equalChildrenCountAs(int value) {
        return new ViewGroupComparison<T>(value, EQUAL, EQUAL);
    }

@ Factory public static < T extends ViewGroup > Matcher < T > equalChildrenCountAs ( int value ) { return new ViewGroupComparison < T > ( value , EQUAL , EQUAL ) ; }


@Factory
    public static <T extends ViewGroup> Matcher<T> moreChildrenThan(int value) {
        return new ViewGroupComparison<T>(value, GREATER_THAN, GREATER_THAN);
    }

@ Factory public static < T extends ViewGroup > Matcher < T > moreChildrenThan ( int value ) { return new ViewGroupComparison < T > ( value , GREATER_THAN , GREATER_THAN ) ; }


@Factory
    public static <T extends ViewGroup> Matcher<T> moreChildrenOrEqual(int value) {
        return new ViewGroupComparison<T>(value, EQUAL, GREATER_THAN);
    }

@ Factory public static < T extends ViewGroup > Matcher < T > moreChildrenOrEqual ( int value ) { return new ViewGroupComparison < T > ( value , EQUAL , GREATER_THAN ) ; }


@Factory
    public static <T extends ViewGroup> Matcher<T> lessChildrenThan(int value) {
        return new ViewGroupComparison<T>(value, LESS_THAN, LESS_THAN);
    }

@ Factory public static < T extends ViewGroup > Matcher < T > lessChildrenThan ( int value ) { return new ViewGroupComparison < T > ( value , LESS_THAN , LESS_THAN ) ; }


@Factory
    public static <T extends ViewGroup> Matcher<T> lessChildrenOrEqual(int value) {
        return new ViewGroupComparison<T>(value, LESS_THAN, EQUAL);
    }

@ Factory public static < T extends ViewGroup > Matcher < T > lessChildrenOrEqual ( int value ) { return new ViewGroupComparison < T > ( value , LESS_THAN , EQUAL ) ; }


public Measures getMeasuresByYearState(String year, String stateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Measure.getMeasuresByYearState", new ArgMap("year", year, "stateId", stateId), Measures.class );
	}

public Measures getMeasuresByYearState ( String year , String stateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Measure.getMeasuresByYearState" , new ArgMap ( "year" , year , "stateId" , stateId ) , Measures . class ) ; }

This method returns a list of state ballot measures in a given year.

@param year
@param stateId
@return {@link Measures}: List of minimal measure information.

This method returns a list of state ballot measures in a given year .


public Measure getMeasure(String measureId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Measure.getMeasure", new ArgMap("measureId", measureId), Measure.class );
	}

public Measure getMeasure ( String measureId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Measure.getMeasure" , new ArgMap ( "measureId" , measureId ) , Measure . class ) ; }

This method returns a single Ballot Measure detail.

@param measureId
@return {@link Measure}: detail on single measure

This method returns a single Ballot Measure detail .


public CandidateRating getCandidateRating(String candidateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Rating.getCandidateRating", new ArgMap("candidateId", candidateId), CandidateRating.class );
	}

public CandidateRating getCandidateRating ( String candidateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Rating.getCandidateRating" , new ArgMap ( "candidateId" , candidateId ) , CandidateRating . class ) ; }

This method dumps a candidate's rating by an SIG.

@param candidateId
@return {@link CandidateRating}

This method dumps a candidate s rating by an SIG .


public Rating getRating(String ratingId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Rating.getRating", new ArgMap("ratingId", ratingId), Rating.class );
	}

public Rating getRating ( String ratingId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Rating.getRating" , new ArgMap ( "ratingId" , ratingId ) , Rating . class ) ; }

This method dumps all candidate ratings from a scorecard by an SIG.

@param ratingId
@return {@link Rating}
@throws VoteSmartException, VoteSmartErrorException

This method dumps all candidate ratings from a scorecard by an SIG .


public Elections getElectionByYearState(String year) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Election.getElectionByYearState", new ArgMap("year", year), Elections.class );
	}

public Elections getElectionByYearState ( String year ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Election.getElectionByYearState" , new ArgMap ( "year" , year ) , Elections . class ) ; }

This method grabs district basic election data according to year and stateid.

@param year
@return {@link Elections}

This method grabs district basic election data according to year and stateid .


public ElectionByZip getElectionByZip(String zip5) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Election.getElectionByZip", new ArgMap("zip5", zip5), ElectionByZip.class );
	}

public ElectionByZip getElectionByZip ( String zip5 ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Election.getElectionByZip" , new ArgMap ( "zip5" , zip5 ) , ElectionByZip . class ) ; }

This method grabs district basic election data according to zip code.

@param zip5
@return {@link ElectionByZip}:

This method grabs district basic election data according to zip code .


public StageCandidates getStageCandidates(String electionId, String stageId, String party) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Election.getStageCandidates", new ArgMap("electionId", electionId, "stageId", stageId, "party", party), StageCandidates .class );
	}

public StageCandidates getStageCandidates ( String electionId , String stageId , String party ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Election.getStageCandidates" , new ArgMap ( "electionId" , electionId , "stageId" , stageId , "party" , party ) , StageCandidates . class ) ; }

This method grabs district basic election data according to electionId and stageId.
Per state lists of a Presidential election are available by specifying the stateId.

@param electionId
@param stageId
@param party
@return {@link StageCandidates}:

This method grabs district basic election data according to electionId and stageId . Per state lists of a Presidential election are available by specifying the stateId .


public AddressAddress getOfficeByOfficeState(String officeId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Address.getOfficeByOfficeState", new ArgMap("officeId", officeId), AddressAddress.class );
	}

public AddressAddress getOfficeByOfficeState ( String officeId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Address.getOfficeByOfficeState" , new ArgMap ( "officeId" , officeId ) , AddressAddress . class ) ; }

This method grabs office address and basic candidate information according to the officeId and state.

@param officeId
@return {@link AddressAddress}: Candidate name and list of offices

This method grabs office address and basic candidate information according to the officeId and state .


public Offices getOfficesByType(String officeTypeId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Office.getOfficesByType", new ArgMap("officeTypeId", officeTypeId), Offices.class );
	}

public Offices getOfficesByType ( String officeTypeId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Office.getOfficesByType" , new ArgMap ( "officeTypeId" , officeTypeId ) , Offices . class ) ; }

This method dumps offices we keep track of according to type.

@param officeTypeId
@return {@link Offices}:

This method dumps offices we keep track of according to type .


public Offices getOfficesByLevel(String levelId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Office.getOfficesByLevel", new ArgMap("levelId", levelId), Offices.class );
	}

public Offices getOfficesByLevel ( String levelId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Office.getOfficesByLevel" , new ArgMap ( "levelId" , levelId ) , Offices . class ) ; }

This method dumps offices we keep track of according to level.

@param levelId
@return {@link Offices}:

This method dumps offices we keep track of according to level .


public Offices getOfficesByTypeLevel(String officeTypeId, String officeLevelId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Office.getOfficesByTypeLevel", new ArgMap("officeTypeId", officeTypeId, "officeLevelId", officeLevelId), Offices.class );
	}

public Offices getOfficesByTypeLevel ( String officeTypeId , String officeLevelId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Office.getOfficesByTypeLevel" , new ArgMap ( "officeTypeId" , officeTypeId , "officeLevelId" , officeLevelId ) , Offices . class ) ; }

This method dumps offices we keep track of according to type and level.

@param officeTypeId
@param officeLevelId
@return {@link Offices}:

This method dumps offices we keep track of according to type and level .


public Offices getOfficesByBranchLevel(String branchId, String levelId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Office.getOfficesByBranchLevel", new ArgMap("branchId", branchId, "levelId", levelId), Offices.class );
	}

public Offices getOfficesByBranchLevel ( String branchId , String levelId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Office.getOfficesByBranchLevel" , new ArgMap ( "branchId" , branchId , "levelId" , levelId ) , Offices . class ) ; }

This method dumps offices we keep track of according to branch and level.

@param branchId
@param levelId
@return {@link Offices}:

This method dumps offices we keep track of according to branch and level .


public Counties getCounties(String stateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Local.getCounties", new ArgMap("stateId", stateId), Counties.class );
	}

public Counties getCounties ( String stateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Local.getCounties" , new ArgMap ( "stateId" , stateId ) , Counties . class ) ; }

Fetches counties in a state.

@param stateId
@return {@link Counties}:


public Cities getCities(String stateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Local.getCities", new ArgMap("stateId", stateId), Cities.class );
	}

public Cities getCities ( String stateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Local.getCities" , new ArgMap ( "stateId" , stateId ) , Cities . class ) ; }

Fetches cities in a state.

@param stateId
@return {@link Cities}:


public LocalCandidateList getOfficials(String localId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Local.getOfficials", new ArgMap("localId", localId), LocalCandidateList.class );
	}

public LocalCandidateList getOfficials ( String localId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Local.getOfficials" , new ArgMap ( "localId" , localId ) , LocalCandidateList . class ) ; }

Fetches officials for a locality.

@param localId
@return {@link LocalCandidateList}:


public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException {
		BufferedReader reader = null;
		HttpURLConnection conn = null;
		String charSet = "utf-8";
		try {
			if ( isCaching(method, argMap) ) {
				File file = getCacheFile(method, argMap);

				long fileLength = file.length();
				logger.fine("Length of File in cache:" + fileLength + ": " + file.getName());
				if ( fileLength == 0L ) {
					VoteSmart.cacheFileFromAPI(method, argMap, file);
				}
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
			} else {
				conn = VoteSmart.getConnectionFromAPI(method, argMap);
				charSet = getCharset(conn);
				reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charSet));
			}

	        JAXBElement<T> e = unmarshaller.unmarshal( new StreamSource( reader ), responseType );
	        if ( e.getName().getLocalPart().equals("error") ) {
//		        ErrorBase error = unmarshaller.unmarshal( new StreamSource( reader = new StringReader(XMLStr) ), ErrorBase.class ).getValue();
	        	throw new VoteSmartErrorException( ((ErrorBase)e.getValue()), method, argMap );
	        } else {
	        	return e.getValue();
	        }
/*
 	        Object o = unmarshaller.unmarshal( new StreamSource( reader ) );
	        if ( o instanceof ErrorBase ) {
	        	throw new VoteSmartErrorException((ErrorBase) o, method, argMap);
	        } else {
		        @SuppressWarnings("unchecked")
				T e = (T) o;
		        return e;
	        }
*/
		} catch ( JAXBException e ) {
			throw new VoteSmartException(e);
		} catch (URISyntaxException e) {
			throw new VoteSmartException(e);
		} catch (IOException e) {
			throw new VoteSmartException(e);
		} finally {
			suspendCache = false;
			if ( conn != null ) conn.disconnect();
			if ( reader != null ) {
				try {
					reader.close();
				} catch (IOException e) {
					throw new VoteSmartException(e);
				}
			}
		}
	}

Queries the API server for the information requested

@param method
@param argMap
@param responseType
@throws VoteSmartErrorException


public CandidateList getStatewide(String stateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Officials.getStatewide", new ArgMap("stateId", stateId), CandidateList.class );
	}

public CandidateList getStatewide ( String stateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Officials.getStatewide" , new ArgMap ( "stateId" , stateId ) , CandidateList . class ) ; }

This method grabs a list of officials according to state representation.

@param stateId
@return {@link CandidateList}

This method grabs a list of officials according to state representation .


public CandidateList getByOfficeTypeState(String officeTypeId, String stateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Officials.getByOfficeTypeState", new ArgMap("officeTypeId", officeTypeId, "stateId", stateId), CandidateList.class );
	}

public CandidateList getByOfficeTypeState ( String officeTypeId , String stateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Officials.getByOfficeTypeState" , new ArgMap ( "officeTypeId" , officeTypeId , "stateId" , stateId ) , CandidateList . class ) ; }

This method grabs a list of officials according to office type and state representation.

@param officeTypeId
@param stateId
@return {@link CandidateList}

This method grabs a list of officials according to office type and state representation .


public CandidateList getByZip(String zip5) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Officials.getByZip", new ArgMap("zip5", zip5), CandidateList.class );
	}

public CandidateList getByZip ( String zip5 ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Officials.getByZip" , new ArgMap ( "zip5" , zip5 ) , CandidateList . class ) ; }

This method grabs a list of officials according to the zip code they represent.

@param zip5
@return {@link CandidateList}

This method grabs a list of officials according to the zip code they represent .


public AddlBio getAddlBio(String candidateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("CandidateBio.getAddlBio", new ArgMap("candidateId", candidateId), AddlBio.class );
	}

public AddlBio getAddlBio ( String candidateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "CandidateBio.getAddlBio" , new ArgMap ( "candidateId" , candidateId ) , AddlBio . class ) ; }

This method grabs the extended bio for each candidate that has one.

@param candidateId
@return {@link AddlBio}: Additional items in a list.

This method grabs the extended bio for each candidate that has one .


public Bio getBio(String candidateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("CandidateBio.getDetailedBio", new ArgMap("candidateId", candidateId), Bio.class );
	}

public Bio getBio ( String candidateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "CandidateBio.getDetailedBio" , new ArgMap ( "candidateId" , candidateId ) , Bio . class ) ; }

This method grabs the extended bio for each candidate that has one.
It uses the updated version 'getDetailedBio' of the call.

@param candidateId
@return {@link AddlBio}: Additional items in a list.

This method grabs the extended bio for each candidate that has one . It uses the updated version getDetailedBio of the call .


public CandidateList getByLastname(String lastName, String electionYear) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Candidates.getByLastname", new ArgMap("lastName", lastName, "electionYear", electionYear), CandidateList.class );
	}

public CandidateList getByLastname ( String lastName , String electionYear ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Candidates.getByLastname" , new ArgMap ( "lastName" , lastName , "electionYear" , electionYear ) , CandidateList . class ) ; }

This method grabs a list of candidates according to a lastname match.

@param lastName
@param electionYear
@return {@link CandidateList}: list of detailed candidate information.

This method grabs a list of candidates according to a lastname match .


public CandidateList getByElection(String electionId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Candidates.getByElection", new ArgMap("electionId", electionId), CandidateList.class );
	}

public CandidateList getByElection ( String electionId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Candidates.getByElection" , new ArgMap ( "electionId" , electionId ) , CandidateList . class ) ; }

This method grabs a list of candidates according to a fuzzy lastname match.

@param electionId
@return {@link CandidateList}: list of detailed candidate information.

This method grabs a list of candidates according to a fuzzy lastname match .


public CandidateList getByDistrict(String districtId, String electionYear) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Candidates.getByDistrict", new ArgMap("districtId", districtId, "electionYear", electionYear), CandidateList.class );
	}

public CandidateList getByDistrict ( String districtId , String electionYear ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Candidates.getByDistrict" , new ArgMap ( "districtId" , districtId , "electionYear" , electionYear ) , CandidateList . class ) ; }

This method grabs a list of candidates according to the district they represent.

@param districtId
@param electionYear
@return {@link CandidateList}: list of detailed candidate information.

This method grabs a list of candidates according to the district they represent .