public Q setBean(final String beanName, final Object bean) {
		if (bean == null) {
			return _this();
		}
		init();
		final String beanNamePrefix = beanName + '.';

		query.forEachNamedParameter(p -> {
			final String paramName = p.name;

			if (paramName.startsWith(beanNamePrefix)) {
				final String propertyName = paramName.substring(beanNamePrefix.length());

				if (BeanUtil.declared.hasRootProperty(bean, propertyName)) {
					final Object value = BeanUtil.declared.getProperty(bean, propertyName);
					setObject(paramName, value);
				}
			}

		});

		return _this();
	}

public Q setBean ( final String beanName , final Object bean ) { if ( bean == null ) { return _this ( ) ; } init ( ) ; final String beanNamePrefix = beanName + ' ' ; query . forEachNamedParameter ( p -> { final String paramName = p . name ; if ( paramName . startsWith ( beanNamePrefix ) ) { final String propertyName = paramName . substring ( beanNamePrefix . length ( ) ) ; if ( BeanUtil . declared . hasRootProperty ( bean , propertyName ) ) { final Object value = BeanUtil . declared . getProperty ( bean , propertyName ) ; setObject ( paramName , value ) ; } } } ) ; return _this ( ) ; }

Sets bean parameters from bean. Non-existing bean properties are ignored.

Sets bean parameters from bean . Non - existing bean properties are ignored .


public Q setMap(final Map parameters) {
		if (parameters == null) {
			return _this();
		}
		init();
		query.forEachNamedParameter(p -> {
			final String paramName = p.name;
			setObject(paramName, parameters.get(paramName));
		});
		return _this();
	}

public Q setMap ( final Map parameters ) { if ( parameters == null ) { return _this ( ) ; } init ( ) ; query . forEachNamedParameter ( p -> { final String paramName = p . name ; setObject ( paramName , parameters . get ( paramName ) ) ; } ) ; return _this ( ) ; }


public Q setObjects(final Object... objects) {
		int index = 1;
		for (final Object object : objects) {
			setObject(index++, object);
		}
		return _this();
	}

public Q setObjects ( final Object ... objects ) { int index = 1 ; for ( final Object object : objects ) { setObject ( index ++ , object ) ; } return _this ( ) ; }

Sets an array of objects parameters in given order.

Sets an array of objects parameters in given order .


public void insertChunkAfter(final SqlChunk previous) {
		SqlChunk next = previous.nextChunk;
		previous.nextChunk = this;
		this.previousChunk = previous;
		if (next != null) {
			next.previousChunk = this;
			this.nextChunk = next;
		}
	}

public void insertChunkAfter ( final SqlChunk previous ) { SqlChunk next = previous . nextChunk ; previous . nextChunk = this ; this . previousChunk = previous ; if ( next != null ) { next . previousChunk = this ; this . nextChunk = next ; } }

Appends chunk to previous one and maintains the double-linked list of the previous chunk.
Current surrounding connections of this chunk will be cut-off.

Appends chunk to previous one and maintains the double - linked list of the previous chunk . Current surrounding connections of this chunk will be cut - off .


protected DbEntityDescriptor lookupType(final Class entity) {
		final DbEntityDescriptor ded = dbEntityManager.lookupType(entity);
		if (ded == null) {
			throw new DbSqlBuilderException("Invalid or not-persistent entity: " + entity.getName());
		}
		return ded;
	}

protected
DbEntityDescriptor
lookupType
(
final
Class
entity
)
{
final
DbEntityDescriptor
ded
=
dbEntityManager
.
lookupType
(
entity
)
;
if
(
ded
==
)
{
throw
new
DbSqlBuilderException
(
"Invalid or not-persistent entity: "
+
entity
.
getName
(
)
)
;
}
return
ded
;
}

Lookups for entity name and throws an exception if entity type is invalid.

Lookups for entity name and throws an exception if entity type is invalid .


protected DbEntityDescriptor findColumnRef(final String columnRef) {
		DbEntityDescriptor ded = templateData.findTableDescriptorByColumnRef(columnRef);
		if (ded == null) {
			throw new DbSqlBuilderException("Invalid column reference: [" + columnRef + "]");
		}
		return ded;
	}

protected
DbEntityDescriptor
findColumnRef
(
final
String
columnRef
)
{
DbEntityDescriptor
ded
=
templateData
.
findTableDescriptorByColumnRef
(
columnRef
)
;
if
(
ded
==
)
{
throw
new
DbSqlBuilderException
(
"Invalid column reference: ["
+
columnRef
+
"]"
)
;
}
return
ded
;
}

Finds a table that contains given column.

Finds a table that contains given column .


protected String resolveTable(final String tableRef, final DbEntityDescriptor ded) {
		String tableAlias = templateData.getTableAlias(tableRef);
		if (tableAlias != null) {
			return tableAlias;
		}
		return ded.getTableNameForQuery();
	}

protected String resolveTable ( final String tableRef , final DbEntityDescriptor ded ) { String tableAlias = templateData . getTableAlias ( tableRef ) ; if ( tableAlias != null ) { return tableAlias ; } return ded . getTableNameForQuery ( ) ; }

Resolves table name or alias that will be used in the query.

Resolves table name or alias that will be used in the query .


protected static Class resolveClass(final Object object) {
		Class type = object.getClass();
		return type == Class.class ? (Class) object : type;
	}

protected static Class resolveClass ( final Object object ) { Class type = object . getClass ( ) ; return type == Class . class ? ( Class ) object : type ; }


protected void appendMissingSpace(final StringBuilder out) {
		int len = out.length();
		if (len == 0) {
			return;
		}
		len--;
		if (!CharUtil.isWhitespace(out.charAt(len))) {
			out.append(' ');
		}
	}

protected void appendMissingSpace ( final StringBuilder out ) { int len = out . length ( ) ; if ( len == 0 ) { return ; } len -- ; if ( ! CharUtil . isWhitespace ( out . charAt ( len ) ) ) { out . append ( ' ' ) ; } }

Appends missing space if the output doesn't end with whitespace.

Appends missing space if the output doesn t end with whitespace .


public Enumeration<String> getFileParameterNames() {
		if (mreq == null) {
			return null;
		}
		return Collections.enumeration(mreq.getFileParameterNames());
	}

public Enumeration < String > getFileParameterNames ( ) { if ( mreq == null ) { return null ; } return Collections . enumeration ( mreq . getFileParameterNames ( ) ) ; }

Get an enumeration of the parameter names for uploaded files


public static boolean include(final ServletRequest request, final ServletResponse response, final String page) throws IOException, ServletException {
		RequestDispatcher dispatcher = request.getRequestDispatcher(page);
		if (dispatcher != null) {
			dispatcher.include(request, response);
			return true;
		}
		return false;
	}

public static boolean include ( final ServletRequest request , final ServletResponse response , final String page ) throws IOException , ServletException { RequestDispatcher dispatcher = request . getRequestDispatcher ( page ) ; if ( dispatcher != null ) { dispatcher . include ( request , response ) ; return true ; } return false ; }

Include page which path is relative to the current HTTP request.

Include page which path is relative to the current HTTP request .


public static String getUrl(final HttpServletRequest request) {
		String servletPath = request.getServletPath();
		String query = request.getQueryString();
		if ((query != null) && (query.length() != 0)) {
			servletPath += '?' + query;
		}
		return servletPath;
	}

public static String getUrl ( final HttpServletRequest request ) { String servletPath = request . getServletPath ( ) ; String query = request . getQueryString ( ) ; if ( ( query != null ) && ( query . length ( ) != 0 ) ) { servletPath += ' ' + query ; } return servletPath ; }

Returns url, without context path, convenient for request dispatcher.

Returns url without context path convenient for request dispatcher .


public static String getRequestUri(final HttpServletRequest request) {
		String result = getIncludeRequestUri(request);
		if (result == null) {
			result = request.getRequestURI();
		}
		return result;
	}

public static String getRequestUri ( final HttpServletRequest request ) { String result = getIncludeRequestUri ( request ) ; if ( result == null ) { result = request . getRequestURI ( ) ; } return result ; }


public String[] resolveParamNames(final Method actionClassMethod) {
		MethodParameter[] methodParameters = Paramo.resolveParameters(actionClassMethod);

		String[] names = new String[methodParameters.length];

		for (int i = 0; i < methodParameters.length; i++) {
			names[i] = methodParameters[i].getName();
		}

		return names;
	}

public String [ ] resolveParamNames ( final Method actionClassMethod ) { MethodParameter [ ] methodParameters = Paramo . resolveParameters ( actionClassMethod ) ; String [ ] names = new String [ methodParameters . length ] ; for ( int i = 0 ; i < methodParameters . length ; i ++ ) { names [ i ] = methodParameters [ i ] . getName ( ) ; } return names ; }


@Override
	public void start() {
		initLogger();

		log.info("PETITE start  ----------");

		petiteContainer = createPetiteContainer();

		if (externalsCache) {
			petiteContainer.setExternalsCache(TypeCache.createDefault());
		}

		log.info("Web application? " + isWebApplication);

		if (!isWebApplication) {
			// make session scope to act as singleton scope
			// if this is not a web application (and http session is not available).
			petiteContainer.registerScope(SessionScope.class, new SingletonScope(petiteContainer));
		}

		// load parameters from properties files
		petiteContainer.defineParameters(joyPropsSupplier.get().getProps());

		// automagic configuration
		if (autoConfiguration) {
			final AutomagicPetiteConfigurator automagicPetiteConfigurator =
				new AutomagicPetiteConfigurator(petiteContainer);

			automagicPetiteConfigurator.registerAsConsumer(joyScannerSupplier.get().getClassScanner());
		}

		petiteContainerConsumers.accept(this.petiteContainer);

		log.info("PETITE OK!");
	}

Creates and initializes Petite container.
It will be auto-magically configured by scanning the classpath.

Creates and initializes Petite container . It will be auto - magically configured by scanning the classpath .


@Override
	public void stop() {
		if (log != null) {
			log.info("PETITE stop");
		}
		if (petiteContainer != null) {
			petiteContainer.shutdown();
		}
		petiteContainer = null;
	}

@
Override
public
void
stop
(
)
{
if
(
log
!=
)
{
log
.
info
(
"PETITE stop"
)
;
}
if
(
petiteContainer
!=
)
{
petiteContainer
.
shutdown
(
)
;
}
petiteContainer
=
;
}


public EmailFilter subject(final String subject) {
		final SearchTerm subjectTerm = new SubjectTerm(subject);
		concat(subjectTerm);
		return this;
	}

public EmailFilter subject ( final String subject ) { final SearchTerm subjectTerm = new SubjectTerm ( subject ) ; concat ( subjectTerm ) ; return this ; }

Defines filter for SUBJECT field.

@param subject The SUBJECT.
@return this


public EmailFilter messageId(final String messageId) {
		final SearchTerm msgIdTerm = new MessageIDTerm(messageId);
		concat(msgIdTerm);
		return this;
	}

public EmailFilter messageId ( final String messageId ) { final SearchTerm msgIdTerm = new MessageIDTerm ( messageId ) ; concat ( msgIdTerm ) ; return this ; }

Defines filter for message id.

@param messageId The message ID.
@return this


public EmailFilter from(final String fromAddress) {
		final SearchTerm fromTerm = new FromStringTerm(fromAddress);
		concat(fromTerm);
		return this;
	}

public EmailFilter from ( final String fromAddress ) { final SearchTerm fromTerm = new FromStringTerm ( fromAddress ) ; concat ( fromTerm ) ; return this ; }

Defines filter for FROM field.

@param fromAddress The FROM address
@return this


public EmailFilter to(final String toAddress) {
		final SearchTerm toTerm = new RecipientStringTerm(RecipientType.TO, toAddress);
		concat(toTerm);
		return this;
	}

public EmailFilter to ( final String toAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . TO , toAddress ) ; concat ( toTerm ) ; return this ; }

Defines filter for TO field.

@param toAddress The TO address.
@return this


public EmailFilter cc(final String ccAddress) {
		final SearchTerm toTerm = new RecipientStringTerm(RecipientType.CC, ccAddress);
		concat(toTerm);
		return this;
	}

public EmailFilter cc ( final String ccAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . CC , ccAddress ) ; concat ( toTerm ) ; return this ; }

Defines filter for CC field.

@param ccAddress CC addreses.
@return this


public EmailFilter bcc(final String bccAddress) {
		final SearchTerm toTerm = new RecipientStringTerm(RecipientType.BCC, bccAddress);
		concat(toTerm);
		return this;
	}

public EmailFilter bcc ( final String bccAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . BCC , bccAddress ) ; concat ( toTerm ) ; return this ; }

Defines filter for BCC field.

@param bccAddress BCC address.
@return this


public EmailFilter flags(final Flags flags, final boolean value) {
		final SearchTerm flagTerm = new FlagTerm(flags, value);
		concat(flagTerm);
		return this;
	}

public EmailFilter flags ( final Flags flags , final boolean value ) { final SearchTerm flagTerm = new FlagTerm ( flags , value ) ; concat ( flagTerm ) ; return this ; }

Defines filter for many flags at once.

@param flags The {@link Flags} to filter on.
@param value The {@link Flag} setting to check for.
@return this


public EmailFilter flag(final Flag flag, final boolean value) {
		final Flags flags = new Flags();
		flags.add(flag);
		return flags(flags, value);
	}

public EmailFilter flag ( final Flag flag , final boolean value ) { final Flags flags = new Flags ( ) ; flags . add ( flag ) ; return flags ( flags , value ) ; }

Defines filter for single flag.

@param flag  The flag to filter on.
@param value The {@link Flag} setting to check for.
@return this


public EmailFilter receivedDate(final Operator operator, final long milliseconds) {
		final SearchTerm term = new ReceivedDateTerm(operator.value, new Date(milliseconds));
		concat(term);
		return this;
	}

public EmailFilter receivedDate ( final Operator operator , final long milliseconds ) { final SearchTerm term = new ReceivedDateTerm ( operator . value , new Date ( milliseconds ) ) ; concat ( term ) ; return this ; }

Defines filter for received date.

@return this


public EmailFilter sentDate(final Operator operator, final long milliseconds) {
		final SearchTerm term = new SentDateTerm(operator.value, new Date(milliseconds));
		concat(term);
		return this;
	}

public EmailFilter sentDate ( final Operator operator , final long milliseconds ) { final SearchTerm term = new SentDateTerm ( operator . value , new Date ( milliseconds ) ) ; concat ( term ) ; return this ; }

Defines filter for sent date.

@param operator     {@link Operator} to use.
@param milliseconds the milliseconds since January 1, 1970, 00:00:00 GMT.
@return this


public EmailFilter size(final Operator comparison, final int size) {
		final SearchTerm term = new SizeTerm(comparison.value, size);
		concat(term);
		return this;
	}

public EmailFilter size ( final Operator comparison , final int size ) { final SearchTerm term = new SizeTerm ( comparison . value , size ) ; concat ( term ) ; return this ; }

Defines filter for message size.

@param comparison {@link Operator}.
@param size       size of message.
@return this


public EmailFilter and(final EmailFilter... emailFilters) {
		final SearchTerm[] searchTerms = new SearchTerm[emailFilters.length];

		for (int i = 0; i < emailFilters.length; i++) {
			searchTerms[i] = emailFilters[i].searchTerm;
		}

		concat(new AndTerm(searchTerms));
		return this;
	}

public EmailFilter and ( final EmailFilter ... emailFilters ) { final SearchTerm [ ] searchTerms = new SearchTerm [ emailFilters . length ] ; for ( int i = 0 ; i < emailFilters . length ; i ++ ) { searchTerms [ i ] = emailFilters [ i ] . searchTerm ; } concat ( new AndTerm ( searchTerms ) ) ; return this ; }

Defines AND group of filters.

@param emailFilters array of {@link EmailFilter}s to AND.
@return this


public EmailFilter or(final EmailFilter... emailFilters) {
		final SearchTerm[] searchTerms = new SearchTerm[emailFilters.length];

		for (int i = 0; i < emailFilters.length; i++) {
			searchTerms[i] = emailFilters[i].searchTerm;
		}

		concat(new OrTerm(searchTerms));
		return this;
	}

public EmailFilter or ( final EmailFilter ... emailFilters ) { final SearchTerm [ ] searchTerms = new SearchTerm [ emailFilters . length ] ; for ( int i = 0 ; i < emailFilters . length ; i ++ ) { searchTerms [ i ] = emailFilters [ i ] . searchTerm ; } concat ( new OrTerm ( searchTerms ) ) ; return this ; }

Defines OR group of filters.

@param emailFilters array of {@link EmailFilter}s to OR.
@return this


public EmailFilter not(final EmailFilter emailFilter) {
		final SearchTerm searchTerm = new NotTerm(emailFilter.searchTerm);
		concat(searchTerm);
		return this;
	}

public EmailFilter not ( final EmailFilter emailFilter ) { final SearchTerm searchTerm = new NotTerm ( emailFilter . searchTerm ) ; concat ( searchTerm ) ; return this ; }

Appends single filter as NOT.

@param emailFilter {@link EmailFilter} to append.
@return this


protected void concat(SearchTerm searchTerm) {
		if (nextIsNot) {
			searchTerm = new NotTerm(searchTerm);
			nextIsNot = false;
		}
		if (operatorAnd) {
			and(searchTerm);
		} else {
			or(searchTerm);
		}
	}

protected void concat ( SearchTerm searchTerm ) { if ( nextIsNot ) { searchTerm = new NotTerm ( searchTerm ) ; nextIsNot = false ; } if ( operatorAnd ) { and ( searchTerm ) ; } else { or ( searchTerm ) ; } }

Concatenates last search term with new one.

@param searchTerm searchTerm {@link SearchTerm} concatenate.
@see #and(SearchTerm)
@see #or(SearchTerm)

Concatenates last search term with new one .


public static String encode(final byte[] bytes) {
		StringBuilder base32 = new StringBuilder((bytes.length * 8 + 4) / 5);

		int currByte, digit, i = 0;
		while (i < bytes.length) {

			// STEP 0; insert new 5 bits, leave 3 bits
			currByte = bytes[i++] & 255;
			base32.append(CHARS[currByte >> 3]);
			digit = (currByte & 7) << 2;
			if (i >= bytes.length) {
				base32.append(CHARS[digit]);
				break;
			}

			// STEP 3: insert 2 new bits, then 5 bits, leave 1 bit
			currByte = bytes[i++] & 255;
			base32.append(CHARS[digit | (currByte >> 6)]);
			base32.append(CHARS[(currByte >> 1) & 31]);
			digit = (currByte & 1) << 4;
			if (i >= bytes.length) {
				base32.append(CHARS[digit]);
				break;
			}

			// STEP 1: insert 4 new bits, leave 4 bit
			currByte = bytes[i++] & 255;
			base32.append(CHARS[digit | (currByte >> 4)]);
			digit = (currByte & 15) << 1;
			if (i >= bytes.length) {
				base32.append(CHARS[digit]);
				break;
			}

			// STEP 4: insert 1 new bit, then 5 bits, leave 2 bits
			currByte = bytes[i++] & 255;
			base32.append(CHARS[digit | (currByte >> 7)]);
			base32.append(CHARS[(currByte >> 2) & 31]);
			digit = (currByte & 3) << 3;
			if (i >= bytes.length) {
				base32.append(CHARS[digit]);
				break;
			}

			// STEP 2: insert 3 new bits, then 5 bits, leave 0 bit
			currByte = bytes[i++] & 255;
			base32.append(CHARS[digit | (currByte >> 5)]);
			base32.append(CHARS[currByte & 31]);
		}
		return base32.toString();
	}

Encode an array of binary bytes into a Base32 string.

Encode an array of binary bytes into a Base32 string .


protected byte[] convertValueToArray(final Object value) {
		if (value instanceof Blob) {
			final Blob blob = (Blob) value;
			try {
				final long length = blob.length();
				if (length > Integer.MAX_VALUE) {
					throw new TypeConversionException("Blob is too big.");
				}
				return blob.getBytes(1, (int) length);
			} catch (SQLException sex) {
				throw new TypeConversionException(value, sex);
			}
		}

		if (value instanceof File) {
			try {
				return FileUtil.readBytes((File) value);
			} catch (IOException ioex) {
				throw new TypeConversionException(value, ioex);
			}
		}

		if (value instanceof Collection) {
			final Collection collection = (Collection) value;
			final byte[] target = new byte[collection.size()];

			int i = 0;
			for (final Object element : collection) {
				target[i] = convertType(element);
				i++;
			}

			return target;
		}

		if (value instanceof Iterable) {
			final Iterable iterable = (Iterable) value;

			final ArrayList<Byte> byteArrayList = new ArrayList<>();

			for (final Object element : iterable) {
				final byte convertedValue = convertType(element);
				byteArrayList.add(Byte.valueOf(convertedValue));
			}

			final byte[] array = new byte[byteArrayList.size()];

			for (int i = 0; i < byteArrayList.size(); i++) {
				final Byte b = byteArrayList.get(i);
				array[i] = b.byteValue();
			}

			return array;
		}

		if (value instanceof CharSequence) {
			final String[] strings = StringUtil.splitc(value.toString(), ArrayConverter.NUMBER_DELIMITERS);
			return convertArrayToArray(strings);
		}

		// everything else:
		return convertToSingleElementArray(value);
	}

protected
byte
[
]
convertValueToArray
(
final
Object
value
)
{
if
(
value
instanceof
Blob
)
{
final
Blob
blob
=
(
Blob
)
value
;
try
{
final
long
length
=
blob
.
length
(
)
;
if
(
length
>
Integer
.
MAX_VALUE
)
{
throw
new
TypeConversionException
(
"Blob is too big."
)
;
}
return
blob
.
getBytes
(
1
,
(
int
)
length
)
;
}
catch
(
SQLException
sex
)
{
throw
new
TypeConversionException
(
value
,
sex
)
;
}
}
if
(
value
instanceof
File
)
{
try
{
return
FileUtil
.
readBytes
(
(
File
)
value
)
;
}
catch
(
IOException
ioex
)
{
throw
new
TypeConversionException
(
value
,
ioex
)
;
}
}
if
(
value
instanceof
Collection
)
{
final
Collection
collection
=
(
Collection
)
value
;
final
byte
[
]
target
=
new
byte
[
collection
.
size
(
)
]
;
int
i
=
0
;
for
(
final
Object
element
:
collection
)
{
target
[
i
]
=
convertType
(
element
)
;
i
++
;
}
return
target
;
}
if
(
value
instanceof
Iterable
)
{
final
Iterable
iterable
=
(
Iterable
)
value
;
final
ArrayList
<
Byte
>
byteArrayList
=
new
ArrayList
<>
(
)
;
for
(
final
Object
element
:
iterable
)
{
final
byte
convertedValue
=
convertType
(
element
)
;
byteArrayList
.
add
(
Byte
.
valueOf
(
convertedValue
)
)
;
}
final
byte
[
]
array
=
new
byte
[
byteArrayList
.
size
(
)
]
;
for
(
int
i
=
0
;
i
<
byteArrayList
.
size
(
)
;
i
++
)
{
final
Byte
b
=
byteArrayList
.
get
(
i
)
;
array
[
i
]
=
b
.
byteValue
(
)
;
}
return
array
;
}
if
(
value
instanceof
CharSequence
)
{
final
String
[
]
strings
=
StringUtil
.
splitc
(
value
.
toString
(
)
,
ArrayConverter
.
NUMBER_DELIMITERS
)
;
return
convertArrayToArray
(
strings
)
;
}
// everything else:
return
convertToSingleElementArray
(
value
)
;
}

Converts non-array value to array. Detects various
types and collections, iterates them to make conversion
and to create target array.

Converts non - array value to array . Detects various types and collections iterates them to make conversion and to create target array .


protected boolean isGzipEligible(final HttpServletRequest request) {
		// request parameter name

		if (requestParameterName.length() != 0) {
			String forceGzipString = request.getParameter(requestParameterName);

			if (forceGzipString != null) {
				return Converter.get().toBooleanValue(forceGzipString, false);
			}
		}

		// extract uri

		String uri = request.getRequestURI();

		if (uri == null) {
			return false;
		}

		uri = uri.toLowerCase();

		boolean result = false;

		// check uri

		if (matches == null) {					// match == *
			if (extensions == null) {			// extensions == *
				return true;
			}
			// extension
			String extension = FileNameUtil.getExtension(uri);

			if (extension.length() > 0) {
				extension = extension.toLowerCase();

				if (StringUtil.equalsOne(extension, extensions) != -1) {
					result = true;
				}
			}
		} else {
			if (wildcards) {
				result = Wildcard.matchPathOne(uri, matches) != -1;
			} else {
				for (String match : matches) {
					if (uri.contains(match)) {
						result = true;
						break;
					}
				}
			}
		}

		if ((result) && (excludes != null)) {
			if (wildcards) {
				if (Wildcard.matchPathOne(uri, excludes) != -1) {
					result = false;
				}
			} else {
				for (String exclude : excludes) {
					if (uri.contains(exclude)) {
						result = false;						// excludes founded
						break;
					}
				}
			}
		}

		return result;
	}

protected
boolean
isGzipEligible
(
final
HttpServletRequest
request
)
{
// request parameter name
if
(
requestParameterName
.
length
(
)
!=
0
)
{
String
forceGzipString
=
request
.
getParameter
(
requestParameterName
)
;
if
(
forceGzipString
!=
)
{
return
Converter
.
get
(
)
.
toBooleanValue
(
forceGzipString
,
false
)
;
}
}
// extract uri
String
uri
=
request
.
getRequestURI
(
)
;
if
(
uri
==
)
{
return
false
;
}
uri
=
uri
.
toLowerCase
(
)
;
boolean
result
=
false
;
// check uri
if
(
matches
==
)
{
// match == *
if
(
extensions
==
)
{
// extensions == *
return
true
;
}
// extension
String
extension
=
FileNameUtil
.
getExtension
(
uri
)
;
if
(
extension
.
length
(
)
>
0
)
{
extension
=
extension
.
toLowerCase
(
)
;
if
(
StringUtil
.
equalsOne
(
extension
,
extensions
)
!=
1
)
{
result
=
true
;
}
}
}
else
{
if
(
wildcards
)
{
result
=
Wildcard
.
matchPathOne
(
uri
,
matches
)
!=
1
;
}
else
{
for
(
String
match
:
matches
)
{
if
(
uri
.
contains
(
match
)
)
{
result
=
true
;
break
;
}
}
}
}
if
(
(
result
)
&&
(
excludes
!=
)
)
{
if
(
wildcards
)
{
if
(
Wildcard
.
matchPathOne
(
uri
,
excludes
)
!=
1
)
{
result
=
false
;
}
}
else
{
for
(
String
exclude
:
excludes
)
{
if
(
uri
.
contains
(
exclude
)
)
{
result
=
false
;
// excludes founded
break
;
}
}
}
}
return
result
;
}

Determine if request is eligible for GZipping.

Determine if request is eligible for GZipping .


public List<Violation> validate(final Object target) {
		return validate(ValidationContext.resolveFor(target.getClass()), target);
	}

public List < Violation > validate ( final Object target ) { return validate ( ValidationContext . resolveFor ( target . getClass ( ) ) , target ) ; }

Validate object using context from the annotations.

Validate object using context from the annotations .


public List<Violation> validate(final ValidationContext ctx, final Object target, final String targetName) {
		for (Map.Entry<String, List<Check>> entry : ctx.map.entrySet()) {
			String name = entry.getKey();
			Object value = BeanUtil.declaredSilent.getProperty(target, name);
			String valueName = targetName != null ? (targetName + '.' + name) : name;		// move up
			ValidationConstraintContext vcc = new ValidationConstraintContext(this, target, valueName);

			for (Check check : entry.getValue()) {
				String[] checkProfiles = check.getProfiles();
				if (!matchProfiles(checkProfiles)) {
					continue;
				}
				if (check.getSeverity() < severity) {
					continue;
				}
				ValidationConstraint constraint = check.getConstraint();
				if (!constraint.isValid(vcc, value)) {
					addViolation(new Violation(valueName, target, value, check));
				}
			}
		}

		return getViolations();
	}

public
List
<
Violation
>
validate
(
final
ValidationContext
ctx
,
final
Object
target
,
final
String
targetName
)
{
for
(
Map
.
Entry
<
String
,
List
<
Check
>
>
entry
:
ctx
.
map
.
entrySet
(
)
)
{
String
name
=
entry
.
getKey
(
)
;
Object
value
=
BeanUtil
.
declaredSilent
.
getProperty
(
target
,
name
)
;
String
valueName
=
targetName
!=
(
targetName
+
'
'
+
name
)
:
name
;
// move up
ValidationConstraintContext
vcc
=
new
ValidationConstraintContext
(
this
,
target
,
valueName
)
;
for
(
Check
check
:
entry
.
getValue
(
)
)
{
String
[
]
checkProfiles
=
check
.
getProfiles
(
)
;
if
(
!
matchProfiles
(
checkProfiles
)
)
{
continue
;
}
if
(
check
.
getSeverity
(
)
<
severity
)
{
continue
;
}
ValidationConstraint
constraint
=
check
.
getConstraint
(
)
;
if
(
!
constraint
.
isValid
(
vcc
,
value
)
)
{
addViolation
(
new
Violation
(
valueName
,
target
,
value
,
check
)
)
;
}
}
}
return
getViolations
(
)
;
}

Performs validation of provided validation context and appends violations.

Performs validation of provided validation context and appends violations .


public void useProfile(final String profile) {
		if (profile == null) {
			return;
		}
		if (this.enabledProfiles == null) {
			this.enabledProfiles = new HashSet<>();
		}
		this.enabledProfiles.add(profile);
	}

public void useProfile ( final String profile ) { if ( profile == null ) { return ; } if ( this . enabledProfiles == null ) { this . enabledProfiles = new HashSet <> ( ) ; } this . enabledProfiles . add ( profile ) ; }


public void useProfiles(final String... enabledProfiles) {
		if (enabledProfiles == null) {
			return;
		}
		if (this.enabledProfiles == null) {
			this.enabledProfiles = new HashSet<>();
		}
		Collections.addAll(this.enabledProfiles, enabledProfiles);
	}

public void useProfiles ( final String ... enabledProfiles ) { if ( enabledProfiles == null ) { return ; } if ( this . enabledProfiles == null ) { this . enabledProfiles = new HashSet <> ( ) ; } Collections . addAll ( this . enabledProfiles , enabledProfiles ) ; }


protected boolean matchProfiles(final String[] checkProfiles) {
		// test for all profiles
		if ((checkProfiles != null) && (checkProfiles.length == 1) && checkProfiles[0].equals(ALL_PROFILES)) {
			return true;
		}
		if (enabledProfiles == null || enabledProfiles.isEmpty()) {
			if (validateAllProfilesByDefault) {
				return true;	// all profiles are considered as enabled
			}
			// only default profile is enabled
			if ((checkProfiles == null) || (checkProfiles.length == 0)) {
				return true;
			}
			for (String profile : checkProfiles) {
				if (StringUtil.isEmpty(profile)) {
					return true;	// default profile
				}
				if (profile.equals(DEFAULT_PROFILE)) {
					return true;
				}
			}
			return false;
		}
		// there are enabled profiles
		if ((checkProfiles == null) || (checkProfiles.length == 0)) {
			return enabledProfiles.contains(DEFAULT_PROFILE);
		}
		boolean result = false;
		for (String profile : checkProfiles) {
			boolean b = true;
			boolean must = false;
			if (StringUtil.isEmpty(profile)) {
				profile = DEFAULT_PROFILE;
			} else if (profile.charAt(0) == '-') {
				profile = profile.substring(1);
				b = false;
			} else if (profile.charAt(0) == '+') {
				profile = profile.substring(1);
				must = true;
			}

			if (enabledProfiles.contains(profile)) {
				if (!b) {
					return false;
				}
				result = true;
			} else {
				if (must) {
					return false;
				}
			}
		}
		return result;
	}

Determine if any of checks profiles is among enabled profiles.

Determine if any of checks profiles is among enabled profiles .


protected Object parseRequestBody(final String body, final Class targetType) {
		return JsonParser.create().parse(body, targetType);
	}

protected Object parseRequestBody ( final String body , final Class targetType ) { return JsonParser . create ( ) . parse ( body , targetType ) ; }

Parses request body into the target type.

Parses request body into the target type .


public long toMilliseconds() {
		double then = (fraction - JD_1970.fraction) * MILLIS_IN_DAY;
		then += (integer - JD_1970.integer) * MILLIS_IN_DAY;
		then += then > 0 ? 1.0e-6 : -1.0e-6;
		return (long) then;
	}

public long toMilliseconds ( ) { double then = ( fraction - JD_1970 . fraction ) * MILLIS_IN_DAY ; then += ( integer - JD_1970 . integer ) * MILLIS_IN_DAY ; then += then > 0 ? 1.0e-6 : - 1.0e-6 ; return ( long ) then ; }


public JulianDate add(final JulianDate jds) {
		int i = this.integer + jds.integer;
		double f = this.fraction + jds.fraction;
		return new JulianDate(i, f);
	}

public JulianDate add ( final JulianDate jds ) { int i = this . integer + jds . integer ; double f = this . fraction + jds . fraction ; return new JulianDate ( i , f ) ; }


public JulianDate sub(final JulianDate jds) {
		int i = this.integer - jds.integer;
		double f = this.fraction -jds.fraction;
		return new JulianDate(i, f);
	}

public JulianDate sub ( final JulianDate jds ) { int i = this . integer - jds . integer ; double f = this . fraction - jds . fraction ; return new JulianDate ( i , f ) ; }


private void set(final int i, double f) {
		integer = i;
		int fi = (int) f;
		f -= fi;
		integer += fi;
		if (f < 0) {
			f += 1;
			integer--;
		}
		this.fraction = f;
	}

private void set ( final int i , double f ) { integer = i ; int fi = ( int ) f ; f -= fi ; integer += fi ; if ( f < 0 ) { f += 1 ; integer -- ; } this . fraction = f ; }

Sets integer and fractional part with normalization.
Normalization means that if double is out of range,
values will be correctly fixed.

Sets integer and fractional part with normalization . Normalization means that if double is out of range values will be correctly fixed .


@Override
	protected void initialize(final char[] input) {
		super.initialize(input);
		this.tag = new ParsedTag();
		this.doctype = new ParsedDoctype();
		this.text = new char[1024];
		this.textLen = 0;
		this.parsingTime = -1;
	}

@ Override protected void initialize ( final char [ ] input ) { super . initialize ( input ) ; this . tag = new ParsedTag ( ) ; this . doctype = new ParsedDoctype ( ) ; this . text = new char [ 1024 ] ; this . textLen = 0 ; this . parsingTime = - 1 ; }


protected void emitComment(final int from, final int to) {
		if (config.enableConditionalComments) {
			// CC: downlevel-hidden starting
			if (match(CC_IF, from)) {
				int endBracketNdx = find(']', from + 3, to);

				CharSequence expression = charSequence(from + 1, endBracketNdx);

				ndx = endBracketNdx + 1;

				char c = input[ndx];

				if (c != '>') {
					errorInvalidToken();
				}

				visitor.condComment(expression, true, true, false);

				state = DATA_STATE;
				return;
			}

			if (to > CC_ENDIF2.length && match(CC_ENDIF2, to - CC_ENDIF2.length)) {
				// CC: downlevel-hidden ending
				visitor.condComment(_ENDIF, false, true, true);

				state = DATA_STATE;
				return;
			}
		}

		CharSequence comment = charSequence(from, to);

		visitor.comment(comment);

		commentStart = -1;
	}

protected
void
emitComment
(
final
int
from
,
final
int
to
)
{
if
(
config
.
enableConditionalComments
)
{
// CC: downlevel-hidden starting
if
(
match
(
CC_IF
,
from
)
)
{
int
endBracketNdx
=
find
(
'
'
,
from
+
3
,
to
)
;
CharSequence
expression
=
charSequence
(
from
+
1
,
endBracketNdx
)
;
ndx
=
endBracketNdx
+
1
;
char
c
=
input
[
ndx
]
;
if
(
c
!=
'
'
)
{
errorInvalidToken
(
)
;
}
visitor
.
condComment
(
expression
,
true
,
true
,
false
)
;
state
=
DATA_STATE
;
return
;
}
if
(
to
>
CC_ENDIF2
.
length
&&
match
(
CC_ENDIF2
,
to
CC_ENDIF2
.
length
)
)
{
// CC: downlevel-hidden ending
visitor
.
condComment
(
_ENDIF
,
false
,
true
,
true
)
;
state
=
DATA_STATE
;
return
;
}
}
CharSequence
comment
=
charSequence
(
from
,
to
)
;
visitor
.
comment
(
comment
)
;
commentStart
=
1
;
}

Emits a comment. Also checks for conditional comments!

Emits a comment . Also checks for conditional comments!


protected void _error(String message) {
		if (config.calculatePosition) {
			Position currentPosition = position(ndx);
			message = message
					.concat(StringPool.SPACE)
					.concat(currentPosition.toString());
		} else {
			message = message
					.concat(" [@")
					.concat(Integer.toString(ndx))
					.concat(StringPool.RIGHT_SQ_BRACKET);
		}

		visitor.error(message);
	}

protected
void
_error
(
String
message
)
{
if
(
config
.
calculatePosition
)
{
Position
currentPosition
=
position
(
ndx
)
;
message
=
message
.
concat
(
StringPool
.
SPACE
)
.
concat
(
currentPosition
.
toString
(
)
)
;
}
else
{
message
=
message
.
concat
(
" [@"
)
.
concat
(
Integer
.
toString
(
ndx
)
)
.
concat
(
StringPool
.
RIGHT_SQ_BRACKET
)
;
}
visitor
.
error
(
message
)
;
}

Prepares error message and reports it to the visitor.

Prepares error message and reports it to the visitor .


public String createHash(final char[] password) {

		// Generate a random salt
		SecureRandom random = new SecureRandom();
		byte[] salt = new byte[saltBytes];
		random.nextBytes(salt);

		// Hash the password
		byte[] hash = pbkdf2(password, salt, pbkdf2Iterations, hashBytes);

		// format iterations:salt:hash
		return pbkdf2Iterations + ":" + StringUtil.toHexString(salt) + ":" + StringUtil.toHexString(hash);
	}

public
String
createHash
(
final
char
[
]
password
)
{
// Generate a random salt
SecureRandom
random
=
new
SecureRandom
(
)
;
byte
[
]
salt
=
new
byte
[
saltBytes
]
;
random
.
nextBytes
(
salt
)
;
// Hash the password
byte
[
]
hash
=
pbkdf2
(
password
,
salt
,
pbkdf2Iterations
,
hashBytes
)
;
// format iterations:salt:hash
return
pbkdf2Iterations
+
":"
+
StringUtil
.
toHexString
(
salt
)
+
":"
+
StringUtil
.
toHexString
(
hash
)
;
}

Returns a salted PBKDF2 hash of the password.

@param password the password to hash
@return a salted PBKDF2 hash of the password

Returns a salted PBKDF2 hash of the password .


private static byte[] pbkdf2(final char[] password, final byte[] salt, final int iterations, final int bytes) {
		PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
		try {
			SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
			return skf.generateSecret(spec).getEncoded();
		}
		catch (NoSuchAlgorithmException ignore) {
			return null;
		}
		catch (InvalidKeySpecException e) {
			throw new IllegalArgumentException(e);
		}
	}

private static byte [ ] pbkdf2 ( final char [ ] password , final byte [ ] salt , final int iterations , final int bytes ) { PBEKeySpec spec = new PBEKeySpec ( password , salt , iterations , bytes * 8 ) ; try { SecretKeyFactory skf = SecretKeyFactory . getInstance ( PBKDF2_ALGORITHM ) ; return skf . generateSecret ( spec ) . getEncoded ( ) ; } catch ( NoSuchAlgorithmException ignore ) { return null ; } catch ( InvalidKeySpecException e ) { throw new IllegalArgumentException ( e ) ; } }

Computes the PBKDF2 hash of a password.

@param password the password to hash.
@param salt the salt
@param iterations the iteration count (slowness factor)
@param bytes the length of the hash to compute in bytes
@return the PBDKF2 hash of the password

Computes the PBKDF2 hash of a password .


private static byte[] fromHex(final String hex) {
		final byte[] binary = new byte[hex.length() / 2];
		for (int i = 0; i < binary.length; i++) {
			binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
		}
		return binary;
	}

private static byte [ ] fromHex ( final String hex ) { final byte [ ] binary = new byte [ hex . length ( ) / 2 ] ; for ( int i = 0 ; i < binary . length ; i ++ ) { binary [ i ] = ( byte ) Integer . parseInt ( hex . substring ( 2 * i , 2 * i + 2 ) , 16 ) ; } return binary ; }

Converts a string of hexadecimal characters into a byte array.

@param hex the hex string
@return the hex string decoded into a byte array

Converts a string of hexadecimal characters into a byte array .


public ProviderDefinition[] resolveProviderDefinitions(final Class type, final String name) {
		return providerResolver.resolve(type, name);
	}

public ProviderDefinition [ ] resolveProviderDefinitions ( final Class type , final String name ) { return providerResolver . resolve ( type , name ) ; }

Resolves provider definition defined in a bean.

Resolves provider definition defined in a bean .


public EmailAttachmentBuilder name(final String name) {
		if (name != null && !name.trim().isEmpty()) {
			this.name = name;
		}
		return this;
	}

public EmailAttachmentBuilder name ( final String name ) { if ( name != null && ! name . trim ( ) . isEmpty ( ) ) { this . name = name ; } return this ; }

Sets file name.

@param name File name to set.
@return this


protected EmailAttachmentBuilder setContentIdFromNameIfMissing() {
		if (contentId == null) {
			if (name != null) {
				contentId(FileNameUtil.getName(name));
			} else {
				contentId(NO_NAME);
			}
		}
		return this;
	}

protected EmailAttachmentBuilder setContentIdFromNameIfMissing ( ) { if ( contentId == null ) { if ( name != null ) { contentId ( FileNameUtil . getName ( name ) ) ; } else { contentId ( NO_NAME ) ; } } return this ; }

Set content ID if it is missing.

@return this
@see #contentId(String)


protected String resolveContentType(final String contentType) {
		if (contentType != null) {
			return contentType;
		}
		if (name == null) {
			return MimeTypes.MIME_APPLICATION_OCTET_STREAM;
		}

		final String extension = FileNameUtil.getExtension(name);
		return MimeTypes.getMimeType(extension);
	}

protected String resolveContentType ( final String contentType ) { if ( contentType != null ) { return contentType ; } if ( name == null ) { return MimeTypes . MIME_APPLICATION_OCTET_STREAM ; } final String extension = FileNameUtil . getExtension ( name ) ; return MimeTypes . getMimeType ( extension ) ; }

Resolves content type from all data.

@param contentType Content type if we know it. {@code null} is fine to use.
@return content type


private static int parseType(
      final String signature, final int startOffset, final SignatureVisitor signatureVisitor) {
    int offset = startOffset; // Current offset in the parsed signature.
    char currentChar = signature.charAt(offset++); // The signature character at 'offset'.

    // Switch based on the first character of the JavaTypeSignature, which indicates its kind.
    switch (currentChar) {
      case 'Z':
      case 'C':
      case 'B':
      case 'S':
      case 'I':
      case 'F':
      case 'J':
      case 'D':
      case 'V':
        // Case of a BaseType or a VoidDescriptor.
        signatureVisitor.visitBaseType(currentChar);
        return offset;

      case '[':
        // Case of an ArrayTypeSignature, a '[' followed by a JavaTypeSignature.
        return parseType(signature, offset, signatureVisitor.visitArrayType());

      case 'T':
        // Case of TypeVariableSignature, an identifier between 'T' and ';'.
        int endOffset = signature.indexOf(';', offset);
        signatureVisitor.visitTypeVariable(signature.substring(offset, endOffset));
        return endOffset + 1;

      case 'L':
        // Case of a ClassTypeSignature, which ends with ';'.
        // These signatures have a main class type followed by zero or more inner class types
        // (separated by '.'). Each can have type arguments, inside '<' and '>'.
        int start = offset; // The start offset of the currently parsed main or inner class name.
        boolean visited = false; // Whether the currently parsed class name has been visited.
        boolean inner = false; // Whether we are currently parsing an inner class type.
        // Parses the signature, one character at a time.
        while (true) {
          currentChar = signature.charAt(offset++);
          if (currentChar == '.' || currentChar == ';') {
            // If a '.' or ';' is encountered, this means we have fully parsed the main class name
            // or an inner class name. This name may already have been visited it is was followed by
            // type arguments between '<' and '>'. If not, we need to visit it here.
            if (!visited) {
              String name = signature.substring(start, offset - 1);
              if (inner) {
                signatureVisitor.visitInnerClassType(name);
              } else {
                signatureVisitor.visitClassType(name);
              }
            }
            // If we reached the end of the ClassTypeSignature return, otherwise start the parsing
            // of a new class name, which is necessarily an inner class name.
            if (currentChar == ';') {
              signatureVisitor.visitEnd();
              break;
            }
            start = offset;
            visited = false;
            inner = true;
          } else if (currentChar == '<') {
            // If a '<' is encountered, this means we have fully parsed the main class name or an
            // inner class name, and that we now need to parse TypeArguments. First, we need to
            // visit the parsed class name.
            String name = signature.substring(start, offset - 1);
            if (inner) {
              signatureVisitor.visitInnerClassType(name);
            } else {
              signatureVisitor.visitClassType(name);
            }
            visited = true;
            // Now, parse the TypeArgument(s), one at a time.
            while ((currentChar = signature.charAt(offset)) != '>') {
              switch (currentChar) {
                case '*':
                  // Unbounded TypeArgument.
                  ++offset;
                  signatureVisitor.visitTypeArgument();
                  break;
                case '+':
                case '-':
                  // Extends or Super TypeArgument. Use offset + 1 to skip the '+' or '-'.
                  offset =
                      parseType(
                          signature, offset + 1, signatureVisitor.visitTypeArgument(currentChar));
                  break;
                default:
                  // Instanceof TypeArgument. The '=' is implicit.
                  offset = parseType(signature, offset, signatureVisitor.visitTypeArgument('='));
                  break;
              }
            }
          }
        }
        return offset;

      default:
        throw new IllegalArgumentException();
    }
  }

Parses a JavaTypeSignature and makes the given visitor visit it.

@param signature a string containing the signature that must be parsed.
@param startOffset index of the first character of the signature to parsed.
@param signatureVisitor the visitor that must visit this signature.
@return the index of the first character after the parsed signature.

Parses a JavaTypeSignature and makes the given visitor visit it .


int computeAttributesSize() {
    symbolTable.addConstantUtf8(Constants.MODULE);
    // 6 attribute header bytes, 6 bytes for name, flags and version, and 5 * 2 bytes for counts.
    int size =
        22 + requires.length + exports.length + opens.length + usesIndex.length + provides.length;
    if (packageCount > 0) {
      symbolTable.addConstantUtf8(Constants.MODULE_PACKAGES);
      // 6 attribute header bytes, and 2 bytes for package_count.
      size += 8 + packageIndex.length;
    }
    if (mainClassIndex > 0) {
      symbolTable.addConstantUtf8(Constants.MODULE_MAIN_CLASS);
      // 6 attribute header bytes, and 2 bytes for main_class_index.
      size += 8;
    }
    return size;
  }

Returns the size of the Module, ModulePackages and ModuleMainClass attributes generated by this
ModuleWriter. Also add the names of these attributes in the constant pool.

@return the size in bytes of the Module, ModulePackages and ModuleMainClass attributes.

Returns the size of the Module ModulePackages and ModuleMainClass attributes generated by this ModuleWriter . Also add the names of these attributes in the constant pool .


void putAttributes(final ByteVector output) {
    // 6 bytes for name, flags and version, and 5 * 2 bytes for counts.
    int moduleAttributeLength =
        16 + requires.length + exports.length + opens.length + usesIndex.length + provides.length;
    output
        .putShort(symbolTable.addConstantUtf8(Constants.MODULE))
        .putInt(moduleAttributeLength)
        .putShort(moduleNameIndex)
        .putShort(moduleFlags)
        .putShort(moduleVersionIndex)
        .putShort(requiresCount)
        .putByteArray(requires.data, 0, requires.length)
        .putShort(exportsCount)
        .putByteArray(exports.data, 0, exports.length)
        .putShort(opensCount)
        .putByteArray(opens.data, 0, opens.length)
        .putShort(usesCount)
        .putByteArray(usesIndex.data, 0, usesIndex.length)
        .putShort(providesCount)
        .putByteArray(provides.data, 0, provides.length);
    if (packageCount > 0) {
      output
          .putShort(symbolTable.addConstantUtf8(Constants.MODULE_PACKAGES))
          .putInt(2 + packageIndex.length)
          .putShort(packageCount)
          .putByteArray(packageIndex.data, 0, packageIndex.length);
    }
    if (mainClassIndex > 0) {
      output
          .putShort(symbolTable.addConstantUtf8(Constants.MODULE_MAIN_CLASS))
          .putInt(2)
          .putShort(mainClassIndex);
    }
  }

Puts the Module, ModulePackages and ModuleMainClass attributes generated by this ModuleWriter
in the given ByteVector.

@param output where the attributes must be put.

Puts the Module ModulePackages and ModuleMainClass attributes generated by this ModuleWriter in the given ByteVector .


public static String decode(final String source, final String encoding) {
		return decode(source, encoding, false);
	}

public static String decode ( final String source , final String encoding ) { return decode ( source , encoding , false ) ; }

Decodes URL elements. This method may be used for all
parts of URL, except for the query parts, since it does
not decode the '+' character.
@see #decodeQuery(String, String)

Decodes URL elements . This method may be used for all parts of URL except for the query parts since it does not decode the + character .


public static String decodeQuery(final String source, final String encoding) {
		return decode(source, encoding, true);
	}

public static String decodeQuery ( final String source , final String encoding ) { return decode ( source , encoding , true ) ; }


@Override
	@SuppressWarnings("unchecked")
	public void start() {
		initLogger();

		if (!databaseEnabled) {
			log.info("DB not enabled.");
			return;
		}

		log.info("DB start ----------");

		final PetiteContainer petiteContainer = joyPetiteSupplier.get().getPetiteContainer();

		// connection pool
		connectionProvider = createConnectionProviderIfNotSupplied();

		petiteContainer.addBean(beanNamePrefix() + "pool", connectionProvider);

		if (connectionProvider instanceof CoreConnectionPool) {
			final CoreConnectionPool pool = (CoreConnectionPool) connectionProvider;
			if (pool.getDriver() == null) {
				databaseEnabled = false;
				log.warn("DB configuration not set (" + beanNamePrefix() + "pool.*). DB will be disabled.");
				return;
			}
		}
		connectionProvider.init();

		checkConnectionProvider();

		// transactions manager
		jtxManager = createJtxTransactionManager(connectionProvider);
		jtxManager.setValidateExistingTransaction(true);

		final AnnotationTxAdviceManager annTxAdviceManager = new AnnotationTxAdviceManager(new LeanJtxWorker(jtxManager), jtxScopePattern);
		AnnotationTxAdviceSupport.manager = annTxAdviceManager;

		// create proxy
		joyProxettaSupplier.get().getProxetta().withAspect(createTxProxyAspects(annTxAdviceManager.getAnnotations()));

		final DbSessionProvider sessionProvider = new DbJtxSessionProvider(jtxManager);

		// querymap
		final long startTime = System.currentTimeMillis();

		final QueryMap queryMap = new DbPropsQueryMap();

		log.debug("Queries loaded in " + (System.currentTimeMillis() - startTime) + "ms.");
		log.debug("Total queries: " + queryMap.size());

		// dboom
		dbOom = DbOom.create()
			.withConnectionProvider(connectionProvider)
			.withSessionProvider(sessionProvider)
			.withQueryMap(queryMap)
			.get();

		dbOom.connect();

		final DbEntityManager dbEntityManager = dbOom.entityManager();
		dbEntityManager.reset();

		petiteContainer.addBean(beanNamePrefix() + "query", dbOom.queryConfig());
		petiteContainer.addBean(beanNamePrefix() + "oom", dbOom.config());

		// automatic configuration
		if (autoConfiguration) {
			final AutomagicDbOomConfigurator automagicDbOomConfigurator =
				new AutomagicDbOomConfigurator(dbEntityManager, true);

			automagicDbOomConfigurator.registerAsConsumer(
				joyScannerSupplier.get().getClassScanner());
		}

		dbEntityManagerConsumers.accept(dbEntityManager);

		log.info("DB OK!");
	}

@
Override
@
SuppressWarnings
(
"unchecked"
)
public
void
start
(
)
{
initLogger
(
)
;
if
(
!
databaseEnabled
)
{
log
.
info
(
"DB not enabled."
)
;
return
;
}
log
.
info
(
"DB start ----------"
)
;
final
PetiteContainer
petiteContainer
=
joyPetiteSupplier
.
get
(
)
.
getPetiteContainer
(
)
;
// connection pool
connectionProvider
=
createConnectionProviderIfNotSupplied
(
)
;
petiteContainer
.
addBean
(
beanNamePrefix
(
)
+
"pool"
,
connectionProvider
)
;
if
(
connectionProvider
instanceof
CoreConnectionPool
)
{
final
CoreConnectionPool
pool
=
(
CoreConnectionPool
)
connectionProvider
;
if
(
pool
.
getDriver
(
)
==
)
{
databaseEnabled
=
false
;
log
.
warn
(
"DB configuration not set ("
+
beanNamePrefix
(
)
+
"pool.*). DB will be disabled."
)
;
return
;
}
}
connectionProvider
.
init
(
)
;
checkConnectionProvider
(
)
;
// transactions manager
jtxManager
=
createJtxTransactionManager
(
connectionProvider
)
;
jtxManager
.
setValidateExistingTransaction
(
true
)
;
final
AnnotationTxAdviceManager
annTxAdviceManager
=
new
AnnotationTxAdviceManager
(
new
LeanJtxWorker
(
jtxManager
)
,
jtxScopePattern
)
;
AnnotationTxAdviceSupport
.
manager
=
annTxAdviceManager
;
// create proxy
joyProxettaSupplier
.
get
(
)
.
getProxetta
(
)
.
withAspect
(
createTxProxyAspects
(
annTxAdviceManager
.
getAnnotations
(
)
)
)
;
final
DbSessionProvider
sessionProvider
=
new
DbJtxSessionProvider
(
jtxManager
)
;
// querymap
final
long
startTime
=
System
.
currentTimeMillis
(
)
;
final
QueryMap
queryMap
=
new
DbPropsQueryMap
(
)
;
log
.
debug
(
"Queries loaded in "
+
(
System
.
currentTimeMillis
(
)
startTime
)
+
"ms."
)
;
log
.
debug
(
"Total queries: "
+
queryMap
.
size
(
)
)
;
// dboom
dbOom
=
DbOom
.
create
(
)
.
withConnectionProvider
(
connectionProvider
)
.
withSessionProvider
(
sessionProvider
)
.
withQueryMap
(
queryMap
)
.
get
(
)
;
dbOom
.
connect
(
)
;
final
DbEntityManager
dbEntityManager
=
dbOom
.
entityManager
(
)
;
dbEntityManager
.
reset
(
)
;
petiteContainer
.
addBean
(
beanNamePrefix
(
)
+
"query"
,
dbOom
.
queryConfig
(
)
)
;
petiteContainer
.
addBean
(
beanNamePrefix
(
)
+
"oom"
,
dbOom
.
config
(
)
)
;
// automatic configuration
if
(
autoConfiguration
)
{
final
AutomagicDbOomConfigurator
automagicDbOomConfigurator
=
new
AutomagicDbOomConfigurator
(
dbEntityManager
,
true
)
;
automagicDbOomConfigurator
.
registerAsConsumer
(
joyScannerSupplier
.
get
(
)
.
getClassScanner
(
)
)
;
}
dbEntityManagerConsumers
.
accept
(
dbEntityManager
)
;
log
.
info
(
"DB OK!"
)
;
}

Initializes database. First, creates connection pool.
and transaction manager. Then, Jodds DbEntityManager is
configured. It is also configured automagically, by scanning
the class path for entities.

Initializes database . First creates connection pool . and transaction manager . Then Jodds DbEntityManager is configured . It is also configured automagically by scanning the class path for entities .


protected void checkConnectionProvider() {
		final Connection connection = connectionProvider.getConnection();
		try {
			final DatabaseMetaData databaseMetaData = connection.getMetaData();
			String name = databaseMetaData.getDatabaseProductName();
			String version = databaseMetaData.getDatabaseProductVersion();

			if (log.isInfoEnabled()) {
				log.info("Connected to database: " + name + " v" + version);
			}
		} catch (SQLException sex) {
			log.error("DB connection failed: ", sex);
		} finally {
			connectionProvider.closeConnection(connection);
		}
	}

protected
void
checkConnectionProvider
(
)
{
final
Connection
connection
=
connectionProvider
.
getConnection
(
)
;
try
{
final
DatabaseMetaData
databaseMetaData
=
connection
.
getMetaData
(
)
;
String
name
=
databaseMetaData
.
getDatabaseProductName
(
)
;
String
version
=
databaseMetaData
.
getDatabaseProductVersion
(
)
;
if
(
log
.
isInfoEnabled
(
)
)
{
log
.
info
(
"Connected to database: "
+
name
+
" v"
+
version
)
;
}
}
catch
(
SQLException
sex
)
{
log
.
error
(
"DB connection failed: "
,
sex
)
;
}
finally
{
connectionProvider
.
closeConnection
(
connection
)
;
}
}

Checks if connection provider can return a connection.

Checks if connection provider can return a connection .


@Override
	public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
//		if ((access & AsmUtil.ACC_FINAL) != 0) {
//			return null;	// skip finals
//		}
		MethodSignatureVisitor msign = createMethodSignature(access, name, desc, signature, exceptions, thisReference, this.generics);
		String key = ProxettaAsmUtil.createMethodSignaturesKey(access, name, desc, thisReference);
		methodSignatures.put(key, msign);
		allMethodSignatures.add(msign.getCleanSignature());
		return new MethodAnnotationReader(msign);
	}

Stores method signature for target method.

Stores method signature for target method .


@Override
	public void visitEnd() {

		// prepare class annotations
		if (classAnnotations != null) {
			annotations = classAnnotations.toArray(new AnnotationInfo[0]);
			classAnnotations = null;
		}

		List<String> superList = new ArrayList<>();

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

		if (nextInterfaces != null) {
			allInterfaces.addAll(nextInterfaces);
		}

		// check all public super methods that are not overridden in superclass
		while (nextSupername != null) {
			InputStream inputStream = null;
			ClassReader cr;

			try {
				inputStream = ClassLoaderUtil.getClassAsStream(nextSupername, classLoader);
				cr = new ClassReader(inputStream);
			} catch (IOException ioex) {
				throw new ProxettaException("Unable to inspect super class: " + nextSupername, ioex);
			} finally {
				StreamUtil.close(inputStream);
			}

			superList.add(nextSupername);
			superClassReaders.add(cr);	// remember the super class reader
			cr.accept(new SuperClassVisitor(), 0);

			if (cr.getInterfaces() != null) {
				Collections.addAll(allInterfaces, cr.getInterfaces());
			}
		}
		superClasses = superList.toArray(new String[0]);

		// check all interface methods that are not overridden in super-interface

		Set<String> todoInterfaces = new HashSet<>(allInterfaces);
		Set<String> newCollectedInterfaces = new HashSet<>();

		while (true) {

			for (String next : todoInterfaces) {
				InputStream inputStream = null;
				ClassReader cr;
				try {
					inputStream = ClassLoaderUtil.getClassAsStream(next, classLoader);
					cr = new ClassReader(inputStream);
				}
				catch (IOException ioex) {
					throw new ProxettaException("Unable to inspect super interface: " + next, ioex);
				}
				finally {
					StreamUtil.close(inputStream);
				}
				superClassReaders.add(cr);				// remember the super class reader
				cr.accept(new SuperClassVisitor(), 0);

				if (cr.getInterfaces() != null) {
					for (String newInterface : cr.getInterfaces()) {
						if (!allInterfaces.contains(newInterface) && !todoInterfaces.contains(newInterface)) {
							// new interface found
							newCollectedInterfaces.add(newInterface);
						}
					}
				}
			}

			// perform collection
			allInterfaces.addAll(todoInterfaces);

			if (newCollectedInterfaces.isEmpty()) {
				// no new interface found
				break;
			}
			todoInterfaces.clear();
			todoInterfaces.addAll(newCollectedInterfaces);

			newCollectedInterfaces.clear();
		}
	}

Stores signatures for all super public methods not already overridden by target class.
All this methods will be accepted for proxyfication.

Stores signatures for all super public methods not already overridden by target class . All this methods will be accepted for proxyfication .


protected MethodSignatureVisitor createMethodSignature(
			final int access,
			final String methodName,
			final String description,
			final String signature,
			final String[] exceptions,
			final String classname,
			final Map<String, String> declaredTypeGenerics) {
		MethodSignatureVisitor v = new MethodSignatureVisitor(methodName, access, classname, description, exceptions, signature, declaredTypeGenerics, this);
		new SignatureReader(signature != null ? signature : description).accept(v);
		return v;
	}

protected MethodSignatureVisitor createMethodSignature ( final int access , final String methodName , final String description , final String signature , final String [ ] exceptions , final String classname , final Map < String , String > declaredTypeGenerics ) { MethodSignatureVisitor v = new MethodSignatureVisitor ( methodName , access , classname , description , exceptions , signature , declaredTypeGenerics , this ) ; new SignatureReader ( signature != null ? signature : description ) . accept ( v ) ; return v ; }

Creates method signature from method name.

Creates method signature from method name .


public static String toCsvString(final Object... elements) {
		StringBuilder line = new StringBuilder();
		int last = elements.length -1;
		for (int i = 0; i < elements.length; i++) {
			if (elements[i] == null) {
				if (i != last) {
					line.append(FIELD_SEPARATOR);
				}
				continue;
			}
			String field = elements[i].toString();

			// check for special cases
			int ndx = field.indexOf(FIELD_SEPARATOR);
			if (ndx == -1) {
				ndx = field.indexOf(FIELD_QUOTE);
			}
			if (ndx == -1) {
				if (field.startsWith(StringPool.SPACE) || field.endsWith(StringPool.SPACE)) {
					ndx = 1;
				}
			}
			if (ndx == -1) {
				ndx = StringUtil.indexOfChars(field, SPECIAL_CHARS);
			}

			// add field
			if (ndx != -1) {
				line.append(FIELD_QUOTE);
			}
			field = StringUtil.replace(field, StringPool.QUOTE, DOUBLE_QUOTE);
			line.append(field);
			if (ndx != -1) {
				line.append(FIELD_QUOTE);
			}

			// last
			if (i != last) {
				line.append(FIELD_SEPARATOR);
			}
		}
		return line.toString();
	}

public
static
String
toCsvString
(
final
Object
...
elements
)
{
StringBuilder
line
=
new
StringBuilder
(
)
;
int
last
=
elements
.
length
1
;
for
(
int
i
=
0
;
i
<
elements
.
length
;
i
++
)
{
if
(
elements
[
i
]
==
)
{
if
(
i
!=
last
)
{
line
.
append
(
FIELD_SEPARATOR
)
;
}
continue
;
}
String
field
=
elements
[
i
]
.
toString
(
)
;
// check for special cases
int
ndx
=
field
.
indexOf
(
FIELD_SEPARATOR
)
;
if
(
ndx
==
1
)
{
ndx
=
field
.
indexOf
(
FIELD_QUOTE
)
;
}
if
(
ndx
==
1
)
{
if
(
field
.
startsWith
(
StringPool
.
SPACE
)
||
field
.
endsWith
(
StringPool
.
SPACE
)
)
{
ndx
=
1
;
}
}
if
(
ndx
==
1
)
{
ndx
=
StringUtil
.
indexOfChars
(
field
,
SPECIAL_CHARS
)
;
}
// add field
if
(
ndx
!=
1
)
{
line
.
append
(
FIELD_QUOTE
)
;
}
field
=
StringUtil
.
replace
(
field
,
StringPool
.
QUOTE
,
DOUBLE_QUOTE
)
;
line
.
append
(
field
)
;
if
(
ndx
!=
1
)
{
line
.
append
(
FIELD_QUOTE
)
;
}
// last
if
(
i
!=
last
)
{
line
.
append
(
FIELD_SEPARATOR
)
;
}
}
return
line
.
toString
(
)
;
}


public static String[] toStringArray(final String line) {
		List<String> row = new ArrayList<>();

        boolean inQuotedField = false;
        int fieldStart = 0;

        final int len = line.length();
        for (int i = 0; i < len; i++) {
            char c = line.charAt(i);
            if (c == FIELD_SEPARATOR) {
                if (!inQuotedField) {	// ignore we are quoting
                    addField(row, line, fieldStart, i, inQuotedField);
                    fieldStart = i + 1;
                }
            } else if (c == FIELD_QUOTE) {
                if (inQuotedField) {
                    if (i + 1 == len || line.charAt(i + 1) == FIELD_SEPARATOR) {	// we are already quoting - peek to see if this is the end of the field
                        addField(row, line, fieldStart, i, inQuotedField);
                        fieldStart = i + 2;
                        i++; // and skip the comma
                        inQuotedField = false;
                    }
                } else if (fieldStart == i) {
                    inQuotedField = true;	// this is a beginning of a quote
                    fieldStart++;			// move field start
                }
            }
        }
        // add last field - but only if string was not empty
        if (len > 0 && fieldStart <= len) {
            addField(row, line, fieldStart, len, inQuotedField);
        }
        return row.toArray(new String[0]);
	}


public CtorInjectionPoint resolve(final Class type, final boolean useAnnotation) {
		// lookup methods
		ClassDescriptor cd = ClassIntrospector.get().lookup(type);
		CtorDescriptor[] allCtors = cd.getAllCtorDescriptors();
		Constructor foundedCtor = null;
		Constructor defaultCtor = null;
		BeanReferences[] references = null;

		for (CtorDescriptor ctorDescriptor : allCtors) {
			Constructor<?> ctor = ctorDescriptor.getConstructor();

			Class<?>[] paramTypes = ctor.getParameterTypes();
			if (paramTypes.length == 0) {
				defaultCtor = ctor;     // detects default ctors
			}

			if (!useAnnotation) {
				continue;
			}

			BeanReferences[] ctorReferences = referencesResolver.readAllReferencesFromAnnotation(ctor);

			if (ctorReferences == null) {
				continue;
			}
			if (foundedCtor != null) {
				throw new PetiteException("Two or more constructors are annotated as injection points in the bean: " + type.getName());
			}

			foundedCtor = ctor;
			references = ctorReferences;
		}

		if (foundedCtor == null) {
			// there is no annotated constructor
			if (allCtors.length == 1) {
				foundedCtor = allCtors[0].getConstructor();
			} else {
				foundedCtor = defaultCtor;
			}

			if (foundedCtor == null) {
				// no matching ctor found
				// still this is not an error if bean is already instantiated.
				return CtorInjectionPoint.EMPTY;
			}

			references = referencesResolver.readAllReferencesFromAnnotation(foundedCtor);

			if (references == null) {
				references = new BeanReferences[0];
			}
		}

		return new CtorInjectionPoint(foundedCtor, references);
	}

Resolves constructor injection point from type. Looks for single annotated constructor.
If no annotated constructors found, the total number of constructors will be checked.
If there is only one constructor, that one will be used as injection point. If more
constructors exist, the default one will be used as injection point. Otherwise, exception
is thrown.

Resolves constructor injection point from type . Looks for single annotated constructor . If no annotated constructors found the total number of constructors will be checked . If there is only one constructor that one will be used as injection point . If more constructors exist the default one will be used as injection point . Otherwise exception is thrown .


private ClassReader createAdviceClassReader(final Class<? extends ProxyAdvice> advice) {
		InputStream inputStream = null;
		try {
			inputStream = ClassLoaderUtil.getClassAsStream(advice);
			return new ClassReader(inputStream);
		} catch (IOException ioex) {
			throw new ProxettaException(ioex);
		} finally {
			StreamUtil.close(inputStream);
		}
	}

private ClassReader createAdviceClassReader ( final Class < ? extends ProxyAdvice > advice ) { InputStream inputStream = null ; try { inputStream = ClassLoaderUtil . getClassAsStream ( advice ) ; return new ClassReader ( inputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( ioex ) ; } finally { StreamUtil . close ( inputStream ) ; } }


private ClassReader getCachedAdviceClassReader(final Class<? extends ProxyAdvice> advice) {
		if (adviceClassReaderCache == null) {
			adviceClassReaderCache = TypeCache.createDefault();
		}
		ClassReader adviceReader = adviceClassReaderCache.get(advice);
		if (adviceReader == null) {
			adviceReader = createAdviceClassReader(advice);
			adviceClassReaderCache.put(advice, adviceReader);
		}
		return adviceReader;
	}

private ClassReader getCachedAdviceClassReader ( final Class < ? extends ProxyAdvice > advice ) { if ( adviceClassReaderCache == null ) { adviceClassReaderCache = TypeCache . createDefault ( ) ; } ClassReader adviceReader = adviceClassReaderCache . get ( advice ) ; if ( adviceReader == null ) { adviceReader = createAdviceClassReader ( advice ) ; adviceClassReaderCache . put ( advice , adviceReader ) ; } return adviceReader ; }


public String encrypt(final String str) {
		try {
			byte[] utf8 = StringUtil.getBytes(str);		// encode the string into bytes using utf-8
			byte[] enc = ecipher.doFinal(utf8); 	// encrypt
			return Base64.encodeToString(enc);		// encode bytes to base64 to get a string
		} catch (Throwable ignore) {
			return null;
		}
	}


public String decrypt(String str) {
		try {
			str = StringUtil.replaceChar(str, ' ', '+');	// replace spaces with chars.
			byte[] dec = Base64.decode(str);    	// decode base64 to get bytes
			byte[] utf8 = dcipher.doFinal(dec);     // decrypt
			return new String(utf8, UTF_8);			// decode using utf-8
		} catch (Throwable ignore) {
			return null;
		}
	}

public
String
decrypt
(
String
str
)
{
try
{
str
=
StringUtil
.
replaceChar
(
str
,
'
'
,
'
'
)
;
// replace spaces with chars.
byte
[
]
dec
=
Base64
.
decode
(
str
)
;
// decode base64 to get bytes
byte
[
]
utf8
=
dcipher
.
doFinal
(
dec
)
;
// decrypt
return
new
String
(
utf8
,
UTF_8
)
;
// decode using utf-8
}
catch
(
Throwable
ignore
)
{
return
;
}
}


public static Logger getLogger(final String name) {
		if (loggers == null) {
			return loggerProvider.apply(name);
		}
		return loggers.computeIfAbsent(name, loggerProvider);
	}

public static Logger getLogger ( final String name ) { if ( loggers == null ) { return loggerProvider . apply ( name ) ; } return loggers . computeIfAbsent ( name , loggerProvider ) ; }

Returns logger for given name. Repeated calls to this method with the
same argument should return the very same instance of the logger.

Returns logger for given name . Repeated calls to this method with the same argument should return the very same instance of the logger .


private void setName(final String name) {
		if (name.contains(";") || name.contains(",") || name.startsWith("$")) {
			throw new IllegalArgumentException("Invalid cookie name:" + name);
		}

		for (int n = 0; n < name.length(); n++) {
			char c = name.charAt(n);
			if (c <= 0x20 || c >= 0x7f) {
				throw new IllegalArgumentException("Invalid cookie name:" + name);
			}
		}
		this.name = name;
	}

private
void
setName
(
final
String
name
)
{
if
(
name
.
contains
(
";"
)
||
name
.
contains
(
","
)
||
name
.
startsWith
(
"$"
)
)
{
throw
new
IllegalArgumentException
(
"Invalid cookie name:"
+
name
)
;
}
for
(
int
n
=
0
;
n
<
name
.
length
(
)
;
n
++
)
{
char
c
=
name
.
charAt
(
n
)
;
if
(
c
<=
0x20
||
c
>=
0x7f
)
{
throw
new
IllegalArgumentException
(
"Invalid cookie name:"
+
name
)
;
}
}
this
.
name
=
name
;
}

Sets the cookie name and checks for validity.

Sets the cookie name and checks for validity .


protected ActionRequest createActionRequest(
		final String actionPath,
		final String[] actionPathChunks,
		final ActionRuntime actionRuntime,
		final Object action,
		final HttpServletRequest servletRequest,
		final HttpServletResponse servletResponse) {

		return new ActionRequest(this, actionPath, actionPathChunks, actionRuntime, action, servletRequest, servletResponse);
	}

protected ActionRequest createActionRequest ( final String actionPath , final String [ ] actionPathChunks , final ActionRuntime actionRuntime , final Object action , final HttpServletRequest servletRequest , final HttpServletResponse servletResponse ) { return new ActionRequest ( this , actionPath , actionPathChunks , actionRuntime , action , servletRequest , servletResponse ) ; }

Creates new action request.
@param actionPath		action path
@param actionRuntime		action runtime
@param action			action object
@param servletRequest	http request
@param servletResponse	http response
@return action request


@Override
	protected <R extends ActionFilter> R createWrapper(final Class<R> wrapperClass) {
		return petiteContainer.createBean(wrapperClass);
	}

@ Override protected < R extends ActionFilter > R createWrapper ( final Class < R > wrapperClass ) { return petiteContainer . createBean ( wrapperClass ) ; }


protected void destroyBean(final BeanData beanData) {
		if (destroyableBeans == null) {
			return;
		}
		if (!isBeanDestroyable(beanData)) {
			return;
		}
		if (destroyableBeans.remove(beanData)) {
			beanData.callDestroyMethods();
		}
	}

protected void destroyBean ( final BeanData beanData ) { if ( destroyableBeans == null ) { return ; } if ( ! isBeanDestroyable ( beanData ) ) { return ; } if ( destroyableBeans . remove ( beanData ) ) { beanData . callDestroyMethods ( ) ; } }

Removes destroyable bean from the list and calls it destroy methods.
If bean is not destroyable, does nothing. Bean gets destroyed only once.

Removes destroyable bean from the list and calls it destroy methods . If bean is not destroyable does nothing . Bean gets destroyed only once .


@Override
	public void shutdown() {
		if (destroyableBeans == null) {
			return;
		}

		for (final BeanData destroyableBean : destroyableBeans) {
			destroyableBean.callDestroyMethods();
		}

		destroyableBeans.clear();
	}

@ Override public void shutdown ( ) { if ( destroyableBeans == null ) { return ; } for ( final BeanData destroyableBean : destroyableBeans ) { destroyableBean . callDestroyMethods ( ) ; } destroyableBeans . clear ( ) ; }

Shutdowns the scope and calls all collected destroyable beans.

Shutdowns the scope and calls all collected destroyable beans .


public ReceivedEmail[] get() {
		if (fromFolder != null) {
			session.useFolder(fromFolder);
		}

		return session.receiveMessages(filter, flagsToSet, flagsToUnset, envelopeOnly, messages -> {
			if (targetFolder != null) {
				try {
					session.folder.copyMessages(messages, session.getFolder(targetFolder));
				} catch (MessagingException e) {
					throw new MailException("Copying messages failed");
				}
			}
		});
	}

public
ReceivedEmail
[
]
get
(
)
{
if
(
fromFolder
!=
)
{
session
.
useFolder
(
fromFolder
)
;
}
return
session
.
receiveMessages
(
filter
,
flagsToSet
,
flagsToUnset
,
envelopeOnly
,
messages
->
{
if
(
targetFolder
!=
)
{
try
{
session
.
folder
.
copyMessages
(
messages
,
session
.
getFolder
(
targetFolder
)
)
;
}
catch
(
MessagingException
e
)
{
throw
new
MailException
(
"Copying messages failed"
)
;
}
}
}
)
;
}

Receives the emails as specified by the builder.

Receives the emails as specified by the builder .


public static void main(final String[] args)
    {
        loadPropertiesFiles(args);

        try (ClusteredServiceContainer container = launch())
        {
            container.context().shutdownSignalBarrier().await();

            System.out.println("Shutdown ClusteredServiceContainer...");
        }
    }

public
static
void
main
(
final
String
[
]
args
)
{
loadPropertiesFiles
(
args
)
;
try
(
ClusteredServiceContainer
container
=
launch
(
)
)
{
container
.
context
(
)
.
shutdownSignalBarrier
(
)
.
await
(
)
;
System
.
out
.
println
(
"Shutdown ClusteredServiceContainer..."
)
;
}
}

Launch the clustered service container and await a shutdown signal.

@param args command line argument which is a list for properties files as URLs or filenames.

Launch the clustered service container and await a shutdown signal .


public void run()
    {
        do
        {
            LockSupport.parkNanos(parkNs);

            final long currentTotalMessages = totalMessages;
            final long currentTotalBytes = totalBytes;
            final long currentTimestamp = System.nanoTime();

            final long timeSpanNs = currentTimestamp - lastTimestamp;
            final double messagesPerSec =
                ((currentTotalMessages - lastTotalMessages) * (double)reportIntervalNs) / (double)timeSpanNs;
            final double bytesPerSec =
                ((currentTotalBytes - lastTotalBytes) * (double)reportIntervalNs) / (double)timeSpanNs;

            reportingFunc.onReport(messagesPerSec, bytesPerSec, currentTotalMessages, currentTotalBytes);

            lastTotalBytes = currentTotalBytes;
            lastTotalMessages = currentTotalMessages;
            lastTimestamp = currentTimestamp;
        }
        while (!halt);
    }

public void run ( ) { do { LockSupport . parkNanos ( parkNs ) ; final long currentTotalMessages = totalMessages ; final long currentTotalBytes = totalBytes ; final long currentTimestamp = System . nanoTime ( ) ; final long timeSpanNs = currentTimestamp - lastTimestamp ; final double messagesPerSec = ( ( currentTotalMessages - lastTotalMessages ) * ( double ) reportIntervalNs ) / ( double ) timeSpanNs ; final double bytesPerSec = ( ( currentTotalBytes - lastTotalBytes ) * ( double ) reportIntervalNs ) / ( double ) timeSpanNs ; reportingFunc . onReport ( messagesPerSec , bytesPerSec , currentTotalMessages , currentTotalBytes ) ; lastTotalBytes = currentTotalBytes ; lastTotalMessages = currentTotalMessages ; lastTimestamp = currentTimestamp ; } while ( ! halt ) ; }


@SuppressWarnings("unused")
    public static void printError(
        final String channel,
        final int streamId,
        final int sessionId,
        final String message,
        final HeaderFlyweight cause)
    {
        System.out.println(message);
    }

@ SuppressWarnings ( "unused" ) public static void printError ( final String channel , final int streamId , final int sessionId , final String message , final HeaderFlyweight cause ) { System . out . println ( message ) ; }

Generic error handler that just prints message to stdout.

@param channel   for the error
@param streamId  for the error
@param sessionId for the error, if source
@param message   indicating what the error was
@param cause     of the error

Generic error handler that just prints message to stdout .


public static void printRate(
        final double messagesPerSec,
        final double bytesPerSec,
        final long totalMessages,
        final long totalBytes)
    {
        System.out.println(String.format(
            "%.02g msgs/sec, %.02g payload bytes/sec, totals %d messages %d MB",
            messagesPerSec, bytesPerSec, totalMessages, totalBytes / (1024 * 1024)));
    }

Print the rates to stdout

@param messagesPerSec being reported
@param bytesPerSec    being reported
@param totalMessages  being reported
@param totalBytes     being reported


public static MappedByteBuffer mapExistingFileReadOnly(final File location)
    {
        if (!location.exists())
        {
            final String msg = "file not found: " + location.getAbsolutePath();
            throw new IllegalStateException(msg);
        }

        MappedByteBuffer mappedByteBuffer = null;
        try (RandomAccessFile file = new RandomAccessFile(location, "r");
            FileChannel channel = file.getChannel())
        {
            mappedByteBuffer = channel.map(READ_ONLY, 0, channel.size());
        }
        catch (final IOException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }

        return mappedByteBuffer;
    }

public
static
MappedByteBuffer
mapExistingFileReadOnly
(
final
File
location
)
{
if
(
!
location
.
exists
(
)
)
{
final
String
msg
=
"file not found: "
+
location
.
getAbsolutePath
(
)
;
throw
new
IllegalStateException
(
msg
)
;
}
MappedByteBuffer
mappedByteBuffer
=
;
try
(
RandomAccessFile
file
=
new
RandomAccessFile
(
location
,
"r"
)
;
FileChannel
channel
=
file
.
getChannel
(
)
)
{
mappedByteBuffer
=
channel
.
map
(
READ_ONLY
,
0
,
channel
.
size
(
)
)
;
}
catch
(
final
IOException
ex
)
{
LangUtil
.
rethrowUnchecked
(
ex
)
;
}
return
mappedByteBuffer
;
}

Map an existing file as a read only buffer.

@param location of file to map.
@return the mapped file.

Map an existing file as a read only buffer .


public void close()
    {
        final State state = this.state;
        if (State.CLOSED != state)
        {
            if (isReplayActive)
            {
                isReplayActive = false;
                archive.stopReplay(replaySessionId);
            }

            if (State.MERGED != state)
            {
                subscription.removeDestination(replayDestination);
            }

            state(State.CLOSED);
        }
    }

public void close ( ) { final State state = this . state ; if ( State . CLOSED != state ) { if ( isReplayActive ) { isReplayActive = false ; archive . stopReplay ( replaySessionId ) ; } if ( State . MERGED != state ) { subscription . removeDestination ( replayDestination ) ; } state ( State . CLOSED ) ; } }

Close the merge and stop any active replay. Will remove the replay destination from the subscription. Will
NOT remove the live destination if it has been added.

Close the merge and stop any active replay . Will remove the replay destination from the subscription . Will NOT remove the live destination if it has been added .


public int doWork()
    {
        int workCount = 0;

        switch (state)
        {
            case AWAIT_INITIAL_RECORDING_POSITION:
                workCount += awaitInitialRecordingPosition();
                break;

            case AWAIT_REPLAY:
                workCount += awaitReplay();
                break;

            case AWAIT_CATCH_UP:
                workCount += awaitCatchUp();
                break;

            case AWAIT_CURRENT_RECORDING_POSITION:
                workCount += awaitUpdatedRecordingPosition();
                break;

            case AWAIT_STOP_REPLAY:
                workCount += awaitStopReplay();
                break;
        }

        return workCount;
    }

public int doWork ( ) { int workCount = 0 ; switch ( state ) { case AWAIT_INITIAL_RECORDING_POSITION : workCount += awaitInitialRecordingPosition ( ) ; break ; case AWAIT_REPLAY : workCount += awaitReplay ( ) ; break ; case AWAIT_CATCH_UP : workCount += awaitCatchUp ( ) ; break ; case AWAIT_CURRENT_RECORDING_POSITION : workCount += awaitUpdatedRecordingPosition ( ) ; break ; case AWAIT_STOP_REPLAY : workCount += awaitStopReplay ( ) ; break ; } return workCount ; }

Process the operation of the merge. Do not call the processing of fragments on the subscription.

@return indication of work done processing the merge.

Process the operation of the merge . Do not call the processing of fragments on the subscription .


public long position()
    {
        if (isClosed)
        {
            return CLOSED;
        }

        final long rawTail = rawTailVolatile(logMetaDataBuffer);
        final int termOffset = termOffset(rawTail, termBufferLength);

        return computePosition(termId(rawTail), termOffset, positionBitsToShift, initialTermId);
    }

public long position ( ) { if ( isClosed ) { return CLOSED ; } final long rawTail = rawTailVolatile ( logMetaDataBuffer ) ; final int termOffset = termOffset ( rawTail , termBufferLength ) ; return computePosition ( termId ( rawTail ) , termOffset , positionBitsToShift , initialTermId ) ; }

Get the current position to which the publication has advanced for this stream.

@return the current position to which the publication has advanced for this stream or {@link #CLOSED}.

Get the current position to which the publication has advanced for this stream .


public long offer(final DirectBufferVector[] vectors, final ReservedValueSupplier reservedValueSupplier)
    {
        final int length = DirectBufferVector.validateAndComputeLength(vectors);
        long newPosition = CLOSED;

        if (!isClosed)
        {
            final long limit = positionLimit.getVolatile();
            final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
            final long position = termBeginPosition + termOffset;

            if (position < limit)
            {
                final int result;
                if (length <= maxPayloadLength)
                {
                    result = termAppender.appendUnfragmentedMessage(
                        termId, termOffset, headerWriter, vectors, length, reservedValueSupplier);
                }
                else
                {
                    checkMaxMessageLength(length);
                    result = termAppender.appendFragmentedMessage(
                        termId,
                        termOffset,
                        headerWriter,
                        vectors,
                        length,
                        maxPayloadLength,
                        reservedValueSupplier);
                }

                newPosition = newPosition(result);
            }
            else
            {
                newPosition = backPressureStatus(position, length);
            }
        }

        return newPosition;
    }

public long offer ( final DirectBufferVector [ ] vectors , final ReservedValueSupplier reservedValueSupplier ) { final int length = DirectBufferVector . validateAndComputeLength ( vectors ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { final int result ; if ( length <= maxPayloadLength ) { result = termAppender . appendUnfragmentedMessage ( termId , termOffset , headerWriter , vectors , length , reservedValueSupplier ) ; } else { checkMaxMessageLength ( length ) ; result = termAppender . appendFragmentedMessage ( termId , termOffset , headerWriter , vectors , length , maxPayloadLength , reservedValueSupplier ) ; } newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }

Non-blocking publish by gathering buffer vectors into a message.

@param vectors               which make up the message.
@param reservedValueSupplier {@link ReservedValueSupplier} for the frame.
@return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
{@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.

Non - blocking publish by gathering buffer vectors into a message .


public long appendPadding(final int length)
    {
        checkMaxMessageLength(length);
        long newPosition = CLOSED;

        if (!isClosed)
        {
            final long limit = positionLimit.getVolatile();
            final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
            final long position = termBeginPosition + termOffset;

            if (position < limit)
            {
                checkPositiveLength(length);
                final int result = termAppender.appendPadding(termId, termOffset, headerWriter, length);
                newPosition = newPosition(result);
            }
            else
            {
                newPosition = backPressureStatus(position, length);
            }
        }

        return newPosition;
    }

public long appendPadding ( final int length ) { checkMaxMessageLength ( length ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { checkPositiveLength ( length ) ; final int result = termAppender . appendPadding ( termId , termOffset , headerWriter , length ) ; newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }

Append a padding record log of a given length to make up the log to a position.

@param length of the range to claim, in bytes..
@return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
{@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
@throws IllegalArgumentException if the length is greater than {@link #maxMessageLength()}.

Append a padding record log of a given length to make up the log to a position .


public void close()
    {
        lock.lock();
        try
        {
            if (!isClosed)
            {
                isClosed = true;
                archiveProxy.closeSession(controlSessionId);

                if (!context.ownsAeronClient())
                {
                    CloseHelper.close(controlResponsePoller.subscription());
                    CloseHelper.close(archiveProxy.publication());
                }

                context.close();
            }
        }
        finally
        {
            lock.unlock();
        }
    }

public void close ( ) { lock . lock ( ) ; try { if ( ! isClosed ) { isClosed = true ; archiveProxy . closeSession ( controlSessionId ) ; if ( ! context . ownsAeronClient ( ) ) { CloseHelper . close ( controlResponsePoller . subscription ( ) ) ; CloseHelper . close ( archiveProxy . publication ( ) ) ; } context . close ( ) ; } } finally { lock . unlock ( ) ; } }

Notify the archive that this control session is closed so it can promptly release resources then close the
local resources associated with the client.

Notify the archive that this control session is closed so it can promptly release resources then close the local resources associated with the client .


public String pollForErrorResponse()
    {
        lock.lock();
        try
        {
            ensureOpen();

            if (controlResponsePoller.poll() != 0 && controlResponsePoller.isPollComplete())
            {
                if (controlResponsePoller.controlSessionId() == controlSessionId &&
                    controlResponsePoller.templateId() == ControlResponseDecoder.TEMPLATE_ID &&
                    controlResponsePoller.code() == ControlResponseCode.ERROR)
                {
                    return controlResponsePoller.errorMessage();
                }
            }

            return null;
        }
        finally
        {
            lock.unlock();
        }
    }

public String pollForErrorResponse ( ) { lock . lock ( ) ; try { ensureOpen ( ) ; if ( controlResponsePoller . poll ( ) != 0 && controlResponsePoller . isPollComplete ( ) ) { if ( controlResponsePoller . controlSessionId ( ) == controlSessionId && controlResponsePoller . templateId ( ) == ControlResponseDecoder . TEMPLATE_ID && controlResponsePoller . code ( ) == ControlResponseCode . ERROR ) { return controlResponsePoller . errorMessage ( ) ; } } return null ; } finally { lock . unlock ( ) ; } }

Poll the response stream once for an error. If another message is present then it will be skipped over
so only call when not expecting another response.

@return the error String otherwise null if no error is found.

Poll the response stream once for an error . If another message is present then it will be skipped over so only call when not expecting another response .


public void stopReplay(final long replaySessionId)
    {
        lock.lock();
        try
        {
            ensureOpen();

            final long correlationId = aeron.nextCorrelationId();

            if (!archiveProxy.stopReplay(replaySessionId, correlationId, controlSessionId))
            {
                throw new ArchiveException("failed to send stop replay request");
            }

            pollForResponse(correlationId);
        }
        finally
        {
            lock.unlock();
        }
    }

public
void
stopReplay
(
final
long
replaySessionId
)
{
lock
.
lock
(
)
;
try
{
ensureOpen
(
)
;
final
long
correlationId
=
aeron
.
nextCorrelationId
(
)
;
if
(
!
archiveProxy
.
stopReplay
(
replaySessionId
,
correlationId
,
controlSessionId
)
)
{
throw
new
ArchiveException
(
"failed to send stop replay request"
)
;
}
pollForResponse
(
correlationId
)
;
}
finally
{
lock
.
unlock
(
)
;
}
}

Stop a replay session.

@param replaySessionId to stop replay for.


public static void eventAvailableImage(final Image image)
    {
        final Subscription subscription = image.subscription();
        System.out.format(
            "new image on %s streamId %x sessionId %x from %s%n",
            subscription.channel(), subscription.streamId(), image.sessionId(), image.sourceIdentity());
    }

Print the information for an available image to stdout.

@param image that has been created

Print the information for an available image to stdout .


public static void eventUnavailableImage(final Image image)
    {
        final Subscription subscription = image.subscription();
        System.out.format(
            "inactive image on %s streamId %d sessionId %x%n",
            subscription.channel(), subscription.streamId(), image.sessionId());
    }

This handler is called when image is unavailable

@param image that has gone inactive


public static StatusIndicatorReader sendChannelStatus(final CountersReader countersReader, final String channel)
    {
        StatusIndicatorReader statusReader = null;
        final MutableInteger id = new MutableInteger(-1);

        countersReader.forEach(
            (counterId, typeId, keyBuffer, label) ->
            {
                if (typeId == SendChannelStatus.SEND_CHANNEL_STATUS_TYPE_ID)
                {
                    if (channel.startsWith(keyBuffer.getStringAscii(ChannelEndpointStatus.CHANNEL_OFFSET)))
                    {
                        id.value = counterId;
                    }
                }
            });

        if (Aeron.NULL_VALUE != id.value)
        {
            statusReader = new UnsafeBufferStatusIndicator(countersReader.valuesBuffer(), id.value);
        }

        return statusReader;
    }

public static StatusIndicatorReader sendChannelStatus ( final CountersReader countersReader , final String channel ) { StatusIndicatorReader statusReader = null ; final MutableInteger id = new MutableInteger ( - 1 ) ; countersReader . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( typeId == SendChannelStatus . SEND_CHANNEL_STATUS_TYPE_ID ) { if ( channel . startsWith ( keyBuffer . getStringAscii ( ChannelEndpointStatus . CHANNEL_OFFSET ) ) ) { id . value = counterId ; } } } ) ; if ( Aeron . NULL_VALUE != id . value ) { statusReader = new UnsafeBufferStatusIndicator ( countersReader . valuesBuffer ( ) , id . value ) ; } return statusReader ; }

Return the read-only status indicator for the given send channel URI.

@param countersReader that holds the status indicator.
@param channel        for the send channel.
@return read-only status indicator that can be used to query the status of the send channel or null
@see ChannelEndpointStatus for status values and indications.

Return the read - only status indicator for the given send channel URI .


public static StatusIndicatorReader receiveChannelStatus(final CountersReader countersReader, final String channel)
    {
        StatusIndicatorReader statusReader = null;
        final MutableInteger id = new MutableInteger(-1);

        countersReader.forEach(
            (counterId, typeId, keyBuffer, label) ->
            {
                if (typeId == ReceiveChannelStatus.RECEIVE_CHANNEL_STATUS_TYPE_ID)
                {
                    if (channel.startsWith(keyBuffer.getStringAscii(ChannelEndpointStatus.CHANNEL_OFFSET)))
                    {
                        id.value = counterId;
                    }
                }
            });

        if (Aeron.NULL_VALUE != id.value)
        {
            statusReader = new UnsafeBufferStatusIndicator(countersReader.valuesBuffer(), id.value);
        }

        return statusReader;
    }

public static StatusIndicatorReader receiveChannelStatus ( final CountersReader countersReader , final String channel ) { StatusIndicatorReader statusReader = null ; final MutableInteger id = new MutableInteger ( - 1 ) ; countersReader . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( typeId == ReceiveChannelStatus . RECEIVE_CHANNEL_STATUS_TYPE_ID ) { if ( channel . startsWith ( keyBuffer . getStringAscii ( ChannelEndpointStatus . CHANNEL_OFFSET ) ) ) { id . value = counterId ; } } } ) ; if ( Aeron . NULL_VALUE != id . value ) { statusReader = new UnsafeBufferStatusIndicator ( countersReader . valuesBuffer ( ) , id . value ) ; } return statusReader ; }

Return the read-only status indicator for the given receive channel URI.

@param countersReader that holds the status indicator.
@param channel        for the receive channel.
@return read-only status indicator that can be used to query the status of the receive channel or null.
@see ChannelEndpointStatus for status values and indications.

Return the read - only status indicator for the given receive channel URI .


public void limit(final int limit)
    {
        if (limit < 0 || limit >= buffer.capacity())
        {
            throw new IllegalArgumentException(
                "limit outside range: capacity=" + buffer.capacity() + " limit=" + limit);
        }

        this.limit = limit;
    }

public
void
limit
(
final
int
limit
)
{
if
(
limit
<
0
||
limit
>=
buffer
.
capacity
(
)
)
{
throw
new
IllegalArgumentException
(
"limit outside range: capacity="
+
buffer
.
capacity
(
)
+
" limit="
+
limit
)
;
}
this
.
limit
=
limit
;
}

Set this limit for this buffer as the position at which the next append operation will occur.

@param limit to be the new value.

Set this limit for this buffer as the position at which the next append operation will occur .


public BufferBuilder append(final DirectBuffer srcBuffer, final int srcOffset, final int length)
    {
        ensureCapacity(length);

        buffer.putBytes(limit, srcBuffer, srcOffset, length);
        limit += length;

        return this;
    }

public BufferBuilder append ( final DirectBuffer srcBuffer , final int srcOffset , final int length ) { ensureCapacity ( length ) ; buffer . putBytes ( limit , srcBuffer , srcOffset , length ) ; limit += length ; return this ; }

Append a source buffer to the end of the internal buffer, resizing the internal buffer as required.

@param srcBuffer from which to copy.
@param srcOffset in the source buffer from which to copy.
@param length    in bytes to copy from the source buffer.
@return the builder for fluent API usage.

Append a source buffer to the end of the internal buffer resizing the internal buffer as required .


public int poll()
    {
        controlSessionId = -1;
        correlationId = -1;
        relevantId = -1;
        templateId = -1;
        errorMessage = null;
        pollComplete = false;

        return subscription.controlledPoll(fragmentAssembler, fragmentLimit);
    }

public int poll ( ) { controlSessionId = - 1 ; correlationId = - 1 ; relevantId = - 1 ; templateId = - 1 ; errorMessage = null ; pollComplete = false ; return subscription . controlledPoll ( fragmentAssembler , fragmentLimit ) ; }

Poll for control response events.

@return the number of fragments read during the operation. Zero if no events are available.


public static MappedByteBuffer mapLossReport(final String aeronDirectoryName, final int reportFileLength)
    {
        return mapNewFile(file(aeronDirectoryName), reportFileLength, false);
    }

public static MappedByteBuffer mapLossReport ( final String aeronDirectoryName , final int reportFileLength ) { return mapNewFile ( file ( aeronDirectoryName ) , reportFileLength , false ) ; }

Map a new loss report in the Aeron directory for a given length.

@param aeronDirectoryName in which to create the file.
@param reportFileLength   for the file.
@return the newly mapped buffer for the file.

Map a new loss report in the Aeron directory for a given length .