@SuppressWarnings({"unchecked"})
	protected <E> E prepareGetValue(final T t, final Class<E> destinationType) {
		if (t == null) {
			return null;
		}
		if (destinationType == null) {
			return (E) t;
		}
		return TypeConverterManager.get().convertType(t, destinationType);
	}

@ SuppressWarnings ( { "unchecked" } ) protected < E > E prepareGetValue ( final T t , final Class < E > destinationType ) { if ( t == null ) { return null ; } if ( destinationType == null ) { return ( E ) t ; } return TypeConverterManager . get ( ) . convertType ( t , destinationType ) ; }

Once when value is read from result set, prepare it to match destination type.
@param t get value
@param destinationType destination type

Once when value is read from result set prepare it to match destination type .


protected Set<T> getAll() {
		final Set<T> set = new HashSet<>(wrappers.size());
		set.addAll(wrappers.values());
		return set;
	}

protected Set < T > getAll ( ) { final Set < T > set = new HashSet <> ( wrappers . size ( ) ) ; set . addAll ( wrappers . values ( ) ) ; return set ; }

Returns all action wrappers. Returns a copy in new set.

Returns all action wrappers . Returns a copy in new set .


public T resolve(final Class<? extends T> wrapperClass) {
		String wrapperClassName = wrapperClass.getName();

		T wrapper = lookup(wrapperClassName);

		if (wrapper == null) {
			wrapper = createWrapper(wrapperClass);

			initializeWrapper(wrapper);

			wrappers.put(wrapperClassName, wrapper);
		}
		return wrapper;
	}

public T resolve ( final Class < ? extends T > wrapperClass ) { String wrapperClassName = wrapperClass . getName ( ) ; T wrapper = lookup ( wrapperClassName ) ; if ( wrapper == null ) { wrapper = createWrapper ( wrapperClass ) ; initializeWrapper ( wrapper ) ; wrappers . put ( wrapperClassName , wrapper ) ; } return wrapper ; }

Resolves single wrapper. Creates new wrapper instance if not already registered.
Does not expand the wrappers.

Resolves single wrapper . Creates new wrapper instance if not already registered . Does not expand the wrappers .


protected <R extends T> R createWrapper(final Class<R> wrapperClass) {
		try {
		    return ClassUtil.newInstance(wrapperClass);
		} catch (Exception ex) {
			throw new MadvocException("Invalid Madvoc wrapper: " + wrapperClass, ex);
		}
	}

protected
<
R
extends
T
>
R
createWrapper
(
final
Class
<
R
>
wrapperClass
)
{
try
{
return
ClassUtil
.
newInstance
(
wrapperClass
)
;
}
catch
(
Exception
ex
)
{
throw
new
MadvocException
(
"Invalid Madvoc wrapper: "
+
wrapperClass
,
ex
)
;
}
}


public static String separatorsToSystem(final String path) {
		if (path == null) {
			return null;
		}
		if (SYSTEM_SEPARATOR == WINDOWS_SEPARATOR) {
			return separatorsToWindows(path);
		} else {
			return separatorsToUnix(path);
		}
	}

public static String separatorsToSystem ( final String path ) { if ( path == null ) { return null ; } if ( SYSTEM_SEPARATOR == WINDOWS_SEPARATOR ) { return separatorsToWindows ( path ) ; } else { return separatorsToUnix ( path ) ; } }

Converts all separators to the system separator.

@param path  the path to be changed, null ignored
@return the updated path

Converts all separators to the system separator .


private static String doGetPath(final String filename, final int separatorAdd) {
		if (filename == null) {
			return null;
		}
		int prefix = getPrefixLength(filename);
		if (prefix < 0) {
			return null;
		}
		int index = indexOfLastSeparator(filename);
        int endIndex = index + separatorAdd;
        if (prefix >= filename.length() || index < 0 || prefix >= endIndex) {
			return StringPool.EMPTY;
		}
        return filename.substring(prefix, endIndex);
	}

private static String doGetPath ( final String filename , final int separatorAdd ) { if ( filename == null ) { return null ; } int prefix = getPrefixLength ( filename ) ; if ( prefix < 0 ) { return null ; } int index = indexOfLastSeparator ( filename ) ; int endIndex = index + separatorAdd ; if ( prefix >= filename . length ( ) || index < 0 || prefix >= endIndex ) { return StringPool . EMPTY ; } return filename . substring ( prefix , endIndex ) ; }

Does the work of getting the path.

@param filename  the filename
@param separatorAdd  0 to omit the end separator, 1 to return it
@return the path


public static String[] split(final String filename) {
		String prefix = getPrefix(filename);
		if (prefix == null) {
			prefix = StringPool.EMPTY;
		}
		int lastSeparatorIndex = indexOfLastSeparator(filename);
		int lastExtensionIndex = indexOfExtension(filename);

		String path;
		String baseName;
		String extension;

		if (lastSeparatorIndex == -1) {
			path = StringPool.EMPTY;
			if (lastExtensionIndex == -1) {
				baseName = filename.substring(prefix.length());
				extension = StringPool.EMPTY;
			} else {
				baseName = filename.substring(prefix.length(), lastExtensionIndex);
				extension = filename.substring(lastExtensionIndex + 1);
			}
		} else {
			path = filename.substring(prefix.length(), lastSeparatorIndex + 1);
			if (lastExtensionIndex == -1) {
				baseName = filename.substring(prefix.length() + path.length());
				extension = StringPool.EMPTY;
			} else {
				baseName = filename.substring(prefix.length() + path.length(), lastExtensionIndex);
				extension = filename.substring(lastExtensionIndex + 1);
			}
		}
		return new String[] {prefix, path, baseName, extension};
	}

public static String [ ] split ( final String filename ) { String prefix = getPrefix ( filename ) ; if ( prefix == null ) { prefix = StringPool . EMPTY ; } int lastSeparatorIndex = indexOfLastSeparator ( filename ) ; int lastExtensionIndex = indexOfExtension ( filename ) ; String path ; String baseName ; String extension ; if ( lastSeparatorIndex == - 1 ) { path = StringPool . EMPTY ; if ( lastExtensionIndex == - 1 ) { baseName = filename . substring ( prefix . length ( ) ) ; extension = StringPool . EMPTY ; } else { baseName = filename . substring ( prefix . length ( ) , lastExtensionIndex ) ; extension = filename . substring ( lastExtensionIndex + 1 ) ; } } else { path = filename . substring ( prefix . length ( ) , lastSeparatorIndex + 1 ) ; if ( lastExtensionIndex == - 1 ) { baseName = filename . substring ( prefix . length ( ) + path . length ( ) ) ; extension = StringPool . EMPTY ; } else { baseName = filename . substring ( prefix . length ( ) + path . length ( ) , lastExtensionIndex ) ; extension = filename . substring ( lastExtensionIndex + 1 ) ; } } return new String [ ] { prefix , path , baseName , extension } ; }

Splits filename into a array of four Strings containing prefix, path, basename and extension.
Path will contain ending separator.

Splits filename into a array of four Strings containing prefix path basename and extension . Path will contain ending separator .


public static String relativePath(final String targetPath, final String basePath) {
		return new File(basePath).toPath().relativize(new File(targetPath).toPath()).toString();
	}

public static String relativePath ( final String targetPath , final String basePath ) { return new File ( basePath ) . toPath ( ) . relativize ( new File ( targetPath ) . toPath ( ) ) . toString ( ) ; }

Calculates relative path of target path on base path.

Calculates relative path of target path on base path .


public WebApp registerComponent(final Class<?> madvocComponent) {
		Objects.requireNonNull(madvocComponent);
		madvocComponents.add(ClassConsumer.of(madvocComponent));
		return this;
	}

public WebApp registerComponent ( final Class < ? > madvocComponent ) { Objects . requireNonNull ( madvocComponent ) ; madvocComponents . add ( ClassConsumer . of ( madvocComponent ) ) ; return this ; }

Registers additional Madvoc components after the registration of default components.

Registers additional Madvoc components after the registration of default components .


public <A extends ActionConfig> WebApp withActionConfig(final Class<A> actionConfigType, final Consumer<A> actionConfigConsumer) {
		withRegisteredComponent(ActionConfigManager.class, acm -> acm.with(actionConfigType, actionConfigConsumer));
		return this;
	}

public < A extends ActionConfig > WebApp withActionConfig ( final Class < A > actionConfigType , final Consumer < A > actionConfigConsumer ) { withRegisteredComponent ( ActionConfigManager . class , acm -> acm . with ( actionConfigType , actionConfigConsumer ) ) ; return this ; }


public WebApp start() {
		log = LoggerFactory.getLogger(WebApp.class);

		log.debug("Initializing Madvoc WebApp");

		//// params & props
		for (final Map<String, Object> params : paramsList) {
			madvocContainer.defineParams(params);
		}
		for (final Props props : propsList) {
			madvocContainer.defineParams(props);
		}
		propsList = null;

		//// components
		registerMadvocComponents();

		madvocComponents.forEach(
			madvocComponent -> madvocContainer.registerComponent(madvocComponent.type(), madvocComponent.consumer()));
		madvocComponents = null;

		madvocComponentInstances.forEach(madvocContainer::registerComponentInstance);
		madvocComponentInstances = null;

		configureDefaults();

		//// listeners
		madvocContainer.fireEvent(Init.class);

		//// component configuration
		componentConfigs.accept(madvocContainer);
		componentConfigs = null;

		initialized();

		madvocContainer.fireEvent(Start.class);

		if (!madvocRouterConsumers.isEmpty()) {

			final MadvocRouter madvocRouter = MadvocRouter.create();

			madvocContainer.registerComponentInstance(madvocRouter);

			madvocRouterConsumers.accept(madvocRouter);
		}
		madvocRouterConsumers = null;

		started();

		madvocContainer.fireEvent(Ready.class);

		ready();

		return this;
	}

public
WebApp
start
(
)
{
log
=
LoggerFactory
.
getLogger
(
WebApp
.
class
)
;
log
.
debug
(
"Initializing Madvoc WebApp"
)
;
//// params & props
for
(
final
Map
<
String
,
Object
>
params
:
paramsList
)
{
madvocContainer
.
defineParams
(
params
)
;
}
for
(
final
Props
props
:
propsList
)
{
madvocContainer
.
defineParams
(
props
)
;
}
propsList
=
;
//// components
registerMadvocComponents
(
)
;
madvocComponents
.
forEach
(
madvocComponent
->
madvocContainer
.
registerComponent
(
madvocComponent
.
type
(
)
,
madvocComponent
.
consumer
(
)
)
)
;
madvocComponents
=
;
madvocComponentInstances
.
forEach
(
madvocContainer
::
registerComponentInstance
)
;
madvocComponentInstances
=
;
configureDefaults
(
)
;
//// listeners
madvocContainer
.
fireEvent
(
Init
.
class
)
;
//// component configuration
componentConfigs
.
accept
(
madvocContainer
)
;
componentConfigs
=
;
initialized
(
)
;
madvocContainer
.
fireEvent
(
Start
.
class
)
;
if
(
!
madvocRouterConsumers
.
isEmpty
(
)
)
{
final
MadvocRouter
madvocRouter
=
MadvocRouter
.
create
(
)
;
madvocContainer
.
registerComponentInstance
(
madvocRouter
)
;
madvocRouterConsumers
.
accept
(
madvocRouter
)
;
}
madvocRouterConsumers
=
;
started
(
)
;
madvocContainer
.
fireEvent
(
Ready
.
class
)
;
ready
(
)
;
return
this
;
}

Initializes and starts web application .


protected void configureDefaults() {
		final ActionConfigManager actionConfigManager =
			madvocContainer.lookupComponent(ActionConfigManager.class);

		actionConfigManager.registerAnnotation(Action.class);
		actionConfigManager.registerAnnotation(RestAction.class);
	}

protected void configureDefaults ( ) { final ActionConfigManager actionConfigManager = madvocContainer . lookupComponent ( ActionConfigManager . class ) ; actionConfigManager . registerAnnotation ( Action . class ) ; actionConfigManager . registerAnnotation ( RestAction . class ) ; }


protected void registerMadvocComponents() {
		if (madvocContainer == null) {
			throw new MadvocException("Madvoc WebApp not initialized.");
		}

		log.debug("Registering Madvoc WebApp components");

		madvocContainer.registerComponent(MadvocEncoding.class);

		madvocContainer.registerComponentInstance(new ServletContextProvider(servletContext));

		madvocContainer.registerComponent(ActionConfigManager.class);
		madvocContainer.registerComponent(ActionMethodParamNameResolver.class);
		madvocContainer.registerComponent(ActionMethodParser.class);
		madvocContainer.registerComponent(ActionPathRewriter.class);
		madvocContainer.registerComponent(ActionsManager.class);
		madvocContainer.registerComponent(ContextInjectorComponent.class);
		madvocContainer.registerComponent(InterceptorsManager.class);
		madvocContainer.registerComponent(FiltersManager.class);
		madvocContainer.registerComponent(MadvocController.class);
		madvocContainer.registerComponent(RootPackages.class);
		madvocContainer.registerComponent(ResultsManager.class);
		madvocContainer.registerComponent(ResultMapper.class);
		madvocContainer.registerComponent(ScopeResolver.class);
		madvocContainer.registerComponent(ScopeDataInspector.class);
		madvocContainer.registerComponent(AsyncActionExecutor.class);
		madvocContainer.registerComponent(FileUploader.class);
	}

protected
void
registerMadvocComponents
(
)
{
if
(
madvocContainer
==
)
{
throw
new
MadvocException
(
"Madvoc WebApp not initialized."
)
;
}
log
.
debug
(
"Registering Madvoc WebApp components"
)
;
madvocContainer
.
registerComponent
(
MadvocEncoding
.
class
)
;
madvocContainer
.
registerComponentInstance
(
new
ServletContextProvider
(
servletContext
)
)
;
madvocContainer
.
registerComponent
(
ActionConfigManager
.
class
)
;
madvocContainer
.
registerComponent
(
ActionMethodParamNameResolver
.
class
)
;
madvocContainer
.
registerComponent
(
ActionMethodParser
.
class
)
;
madvocContainer
.
registerComponent
(
ActionPathRewriter
.
class
)
;
madvocContainer
.
registerComponent
(
ActionsManager
.
class
)
;
madvocContainer
.
registerComponent
(
ContextInjectorComponent
.
class
)
;
madvocContainer
.
registerComponent
(
InterceptorsManager
.
class
)
;
madvocContainer
.
registerComponent
(
FiltersManager
.
class
)
;
madvocContainer
.
registerComponent
(
MadvocController
.
class
)
;
madvocContainer
.
registerComponent
(
RootPackages
.
class
)
;
madvocContainer
.
registerComponent
(
ResultsManager
.
class
)
;
madvocContainer
.
registerComponent
(
ResultMapper
.
class
)
;
madvocContainer
.
registerComponent
(
ScopeResolver
.
class
)
;
madvocContainer
.
registerComponent
(
ScopeDataInspector
.
class
)
;
madvocContainer
.
registerComponent
(
AsyncActionExecutor
.
class
)
;
madvocContainer
.
registerComponent
(
FileUploader
.
class
)
;
}


public ClassScanner excludeJars(final String... excludedJars) {
		for (final String excludedJar : excludedJars) {
			rulesJars.exclude(excludedJar);
		}
		return this;
	}

public ClassScanner excludeJars ( final String ... excludedJars ) { for ( final String excludedJar : excludedJars ) { rulesJars . exclude ( excludedJar ) ; } return this ; }


public ClassScanner includeJars(final String... includedJars) {
		for (final String includedJar : includedJars) {
			rulesJars.include(includedJar);
		}
		return this;
	}

public ClassScanner includeJars ( final String ... includedJars ) { for ( final String includedJar : includedJars ) { rulesJars . include ( includedJar ) ; } return this ; }


public ClassScanner includeEntries(final String... includedEntries) {
		for (final String includedEntry : includedEntries) {
			rulesEntries.include(includedEntry);
		}
		return this;
	}

public ClassScanner includeEntries ( final String ... includedEntries ) { for ( final String includedEntry : includedEntries ) { rulesEntries . include ( includedEntry ) ; } return this ; }

Sets included set of names that will be considered during configuration.
@see InExRules

Sets included set of names that will be considered during configuration .


public ClassScanner excludeEntries(final String... excludedEntries) {
		for (final String excludedEntry : excludedEntries) {
			rulesEntries.exclude(excludedEntry);
		}
		return this;
	}

public ClassScanner excludeEntries ( final String ... excludedEntries ) { for ( final String excludedEntry : excludedEntries ) { rulesEntries . exclude ( excludedEntry ) ; } return this ; }

Sets excluded names that narrows included set of packages.
@see InExRules

Sets excluded names that narrows included set of packages .


protected void scanJarFile(final File file) {
		final ZipFile zipFile;
		try {
			zipFile = new ZipFile(file);
		} catch (IOException ioex) {
			if (!ignoreException) {
				throw new FindFileException("Invalid zip: " + file.getName(), ioex);
			}
			return;
		}
		final Enumeration entries = zipFile.entries();
		while (entries.hasMoreElements()) {
			final ZipEntry zipEntry = (ZipEntry) entries.nextElement();
			final String zipEntryName = zipEntry.getName();
			try {
				if (StringUtil.endsWithIgnoreCase(zipEntryName, CLASS_FILE_EXT)) {
					final String entryName = prepareEntryName(zipEntryName, true);
					final ClassPathEntry classPathEntry = new ClassPathEntry(entryName, zipFile, zipEntry);
					try {
						scanEntry(classPathEntry);
					} finally {
						classPathEntry.closeInputStream();
					}
				} else if (includeResources) {
					final String entryName = prepareEntryName(zipEntryName, false);
					final ClassPathEntry classPathEntry = new ClassPathEntry(entryName, zipFile, zipEntry);
					try {
						scanEntry(classPathEntry);
					} finally {
						classPathEntry.closeInputStream();
					}
				}
			} catch (RuntimeException rex) {
				if (!ignoreException) {
					ZipUtil.close(zipFile);
					throw rex;
				}
			}
		}
		ZipUtil.close(zipFile);
	}

protected
void
scanJarFile
(
final
File
file
)
{
final
ZipFile
zipFile
;
try
{
zipFile
=
new
ZipFile
(
file
)
;
}
catch
(
IOException
ioex
)
{
if
(
!
ignoreException
)
{
throw
new
FindFileException
(
"Invalid zip: "
+
file
.
getName
(
)
,
ioex
)
;
}
return
;
}
final
Enumeration
entries
=
zipFile
.
entries
(
)
;
while
(
entries
.
hasMoreElements
(
)
)
{
final
ZipEntry
zipEntry
=
(
ZipEntry
)
entries
.
nextElement
(
)
;
final
String
zipEntryName
=
zipEntry
.
getName
(
)
;
try
{
if
(
StringUtil
.
endsWithIgnoreCase
(
zipEntryName
,
CLASS_FILE_EXT
)
)
{
final
String
entryName
=
prepareEntryName
(
zipEntryName
,
true
)
;
final
ClassPathEntry
classPathEntry
=
new
ClassPathEntry
(
entryName
,
zipFile
,
zipEntry
)
;
try
{
scanEntry
(
classPathEntry
)
;
}
finally
{
classPathEntry
.
closeInputStream
(
)
;
}
}
else
if
(
includeResources
)
{
final
String
entryName
=
prepareEntryName
(
zipEntryName
,
false
)
;
final
ClassPathEntry
classPathEntry
=
new
ClassPathEntry
(
entryName
,
zipFile
,
zipEntry
)
;
try
{
scanEntry
(
classPathEntry
)
;
}
finally
{
classPathEntry
.
closeInputStream
(
)
;
}
}
}
catch
(
RuntimeException
rex
)
{
if
(
!
ignoreException
)
{
ZipUtil
.
close
(
zipFile
)
;
throw
rex
;
}
}
}
ZipUtil
.
close
(
zipFile
)
;
}

Scans classes inside single JAR archive. Archive is scanned as a zip file.
@see #onEntry(ClassPathEntry)

Scans classes inside single JAR archive . Archive is scanned as a zip file .


protected void scanClassPath(final File root) {
		String rootPath = root.getAbsolutePath();
		if (!rootPath.endsWith(File.separator)) {
			rootPath += File.separatorChar;
		}

		final FindFile ff = FindFile.create().includeDirs(false).recursive(true).searchPath(rootPath);
		File file;
		while ((file = ff.nextFile()) != null) {
			final String filePath = file.getAbsolutePath();
			try {
				if (StringUtil.endsWithIgnoreCase(filePath, CLASS_FILE_EXT)) {
					scanClassFile(filePath, rootPath, file, true);
				} else if (includeResources) {
					scanClassFile(filePath, rootPath, file, false);
				}
			} catch (RuntimeException rex) {
				if (!ignoreException) {
					throw rex;
				}
			}
		}
	}

protected void scanClassPath ( final File root ) { String rootPath = root . getAbsolutePath ( ) ; if ( ! rootPath . endsWith ( File . separator ) ) { rootPath += File . separatorChar ; } final FindFile ff = FindFile . create ( ) . includeDirs ( false ) . recursive ( true ) . searchPath ( rootPath ) ; File file ; while ( ( file = ff . nextFile ( ) ) != null ) { final String filePath = file . getAbsolutePath ( ) ; try { if ( StringUtil . endsWithIgnoreCase ( filePath , CLASS_FILE_EXT ) ) { scanClassFile ( filePath , rootPath , file , true ) ; } else if ( includeResources ) { scanClassFile ( filePath , rootPath , file , false ) ; } } catch ( RuntimeException rex ) { if ( ! ignoreException ) { throw rex ; } } } }

Scans single classpath directory.
@see #onEntry(ClassPathEntry)


public static byte[] bytecodeSignatureOfType(final Class type) {
		final String name = 'L' + type.getName().replace('.', '/') + ';';
		return name.getBytes();
	}

public static byte [ ] bytecodeSignatureOfType ( final Class type ) { final String name = ' ' + type . getName ( ) . replace ( ' ' , ' ' ) + ' ' ; return name . getBytes ( ) ; }

Returns type signature bytes used for searching in class file.

Returns type signature bytes used for searching in class file .


public ClassScanner scan(final String... paths) {
		for (final String path : paths) {
			filesToScan.add(new File(path));
		}
		return this;
	}

public ClassScanner scan ( final String ... paths ) { for ( final String path : paths ) { filesToScan . add ( new File ( path ) ) ; } return this ; }


public void start() {
		if (detectEntriesMode) {
			rulesEntries.detectMode();
		}

		filesToScan.forEach(file -> {
			final String path = file.getAbsolutePath();
			if (StringUtil.endsWithIgnoreCase(path, JAR_FILE_EXT)) {
				if (!acceptJar(file)) {
					return;
				}
				scanJarFile(file);
			} else if (file.isDirectory()) {
				scanClassPath(file);
			}
		});
	}

public void start ( ) { if ( detectEntriesMode ) { rulesEntries . detectMode ( ) ; } filesToScan . forEach ( file -> { final String path = file . getAbsolutePath ( ) ; if ( StringUtil . endsWithIgnoreCase ( path , JAR_FILE_EXT ) ) { if ( ! acceptJar ( file ) ) { return ; } scanJarFile ( file ) ; } else if ( file . isDirectory ( ) ) { scanClassPath ( file ) ; } } ) ; }


@Override
	protected JtxTransaction createNewTransaction(final JtxTransactionMode tm, final Object scope, final boolean active) {
		return new DbJtxTransaction(this, tm, scope, active);
	}

@ Override protected JtxTransaction createNewTransaction ( final JtxTransactionMode tm , final Object scope , final boolean active ) { return new DbJtxTransaction ( this , tm , scope , active ) ; }


@SuppressWarnings("unchecked")
	public <S extends MadvocScope> S defaultOrScopeType(final Class<S> scopeClass) {
		if (scopeClass == null) {
			return (S) getOrInitScope(RequestScope.class);
		}

		return (S) getOrInitScope(scopeClass);
	}

@ SuppressWarnings ( "unchecked" ) public < S extends MadvocScope > S defaultOrScopeType ( final Class < S > scopeClass ) { if ( scopeClass == null ) { return ( S ) getOrInitScope ( RequestScope . class ) ; } return ( S ) getOrInitScope ( scopeClass ) ; }

Lookups the scope instance of given scope annotation.
If instance does not exist, it will be created, cached and returned.

Lookups the scope instance of given scope annotation . If instance does not exist it will be created cached and returned .


protected MadvocScope getOrInitScope(final Class<? extends MadvocScope> madvocScopeType) {
		for (final MadvocScope s : allScopes) {
			if (s.getClass().equals(madvocScopeType)) {
				return s;
			}
		}

		// new scope detected
		final MadvocScope newScope;
		try {
			newScope = madpc.createBean(madvocScopeType);
		} catch (Exception ex) {
			throw new MadvocException("Unable to create scope: " + madvocScopeType, ex);
		}

		allScopes.add(newScope);

		return newScope;
	}

protected
MadvocScope
getOrInitScope
(
final
Class
<
extends
MadvocScope
>
madvocScopeType
)
{
for
(
final
MadvocScope
s
:
allScopes
)
{
if
(
s
.
getClass
(
)
.
equals
(
madvocScopeType
)
)
{
return
s
;
}
}
// new scope detected
final
MadvocScope
newScope
;
try
{
newScope
=
madpc
.
createBean
(
madvocScopeType
)
;
}
catch
(
Exception
ex
)
{
throw
new
MadvocException
(
"Unable to create scope: "
+
madvocScopeType
,
ex
)
;
}
allScopes
.
add
(
newScope
)
;
return
newScope
;
}

Performs search for the scope class and returns it's instance.

Performs search for the scope class and returns it s instance .


public void forScope(final Class<? extends MadvocScope> scopeType, final Consumer<MadvocScope> madvocScopeConsumer) {
		final MadvocScope scope = getOrInitScope(scopeType);
		madvocScopeConsumer.accept(scope);
	}

public void forScope ( final Class < ? extends MadvocScope > scopeType , final Consumer < MadvocScope > madvocScopeConsumer ) { final MadvocScope scope = getOrInitScope ( scopeType ) ; madvocScopeConsumer . accept ( scope ) ; }


public static byte[] decode(final char[] arr) {
		int length = arr.length;
		if (length == 0) {
			return new byte[0];
		}

		int sndx = 0, endx = length - 1;
		int pad = arr[endx] == '=' ? (arr[endx - 1] == '=' ? 2 : 1) : 0;
		int cnt = endx - sndx + 1;
		int sepCnt = length > 76 ? (arr[76] == '\r' ? cnt / 78 : 0) << 1 : 0;
		int len = ((cnt - sepCnt) * 6 >> 3) - pad;
		byte[] dest = new byte[len];

		int d = 0;
		for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
			int i = INV[arr[sndx++]] << 18 | INV[arr[sndx++]] << 12 | INV[arr[sndx++]] << 6 | INV[arr[sndx++]];

			dest[d++] = (byte) (i >> 16);
			dest[d++] = (byte) (i >> 8);
			dest[d++] = (byte) i;

			if (sepCnt > 0 && ++cc == 19) {
				sndx += 2;
				cc = 0;
			}
		}

		if (d < len) {
			int i = 0;
			for (int j = 0; sndx <= endx - pad; j++) {
				i |= INV[arr[sndx++]] << (18 - j * 6);
			}
			for (int r = 16; d < len; r -= 8) {
				dest[d++] = (byte) (i >> r);
			}
		}

		return dest;
	}

public static byte [ ] decode ( final char [ ] arr ) { int length = arr . length ; if ( length == 0 ) { return new byte [ 0 ] ; } int sndx = 0 , endx = length - 1 ; int pad = arr [ endx ] == ' ' ? ( arr [ endx - 1 ] == ' ' ? 2 : 1 ) : 0 ; int cnt = endx - sndx + 1 ; int sepCnt = length > 76 ? ( arr [ 76 ] == ' ' ? cnt / 78 : 0 ) << 1 : 0 ; int len = ( ( cnt - sepCnt ) * 6 >> 3 ) - pad ; byte [ ] dest = new byte [ len ] ; int d = 0 ; for ( int cc = 0 , eLen = ( len / 3 ) * 3 ; d < eLen ; ) { int i = INV [ arr [ sndx ++ ] ] << 18 | INV [ arr [ sndx ++ ] ] << 12 | INV [ arr [ sndx ++ ] ] << 6 | INV [ arr [ sndx ++ ] ] ; dest [ d ++ ] = ( byte ) ( i >> 16 ) ; dest [ d ++ ] = ( byte ) ( i >> 8 ) ; dest [ d ++ ] = ( byte ) i ; if ( sepCnt > 0 && ++ cc == 19 ) { sndx += 2 ; cc = 0 ; } } if ( d < len ) { int i = 0 ; for ( int j = 0 ; sndx <= endx - pad ; j ++ ) { i |= INV [ arr [ sndx ++ ] ] << ( 18 - j * 6 ) ; } for ( int r = 16 ; d < len ; r -= 8 ) { dest [ d ++ ] = ( byte ) ( i >> r ) ; } } return dest ; }


@SuppressWarnings({"unchecked"})
	public static String prepareCsrfToken(final HttpSession session, final int timeToLive) {
		Set<Token> tokenSet = (Set<Token>) session.getAttribute(CSRF_TOKEN_SET);
		if (tokenSet == null) {
			tokenSet = new HashSet<>();
			session.setAttribute(CSRF_TOKEN_SET, tokenSet);
		}
		String value;
		boolean unique;
		do {
			value = RandomString.get().randomAlphaNumeric(32);
			assureSize(tokenSet);
			unique = tokenSet.add(new Token(value, timeToLive));
		} while (!unique);
		return value;
	}

@ SuppressWarnings ( { "unchecked" } ) public static String prepareCsrfToken ( final HttpSession session , final int timeToLive ) { Set < Token > tokenSet = ( Set < Token > ) session . getAttribute ( CSRF_TOKEN_SET ) ; if ( tokenSet == null ) { tokenSet = new HashSet <> ( ) ; session . setAttribute ( CSRF_TOKEN_SET , tokenSet ) ; } String value ; boolean unique ; do { value = RandomString . get ( ) . randomAlphaNumeric ( 32 ) ; assureSize ( tokenSet ) ; unique = tokenSet . add ( new Token ( value , timeToLive ) ) ; } while ( ! unique ) ; return value ; }

Generates new CSRF token and puts it in the session. Returns generated token value.

Generates new CSRF token and puts it in the session . Returns generated token value .


protected static void assureSize(final Set<Token> tokenSet) {
		if (tokenSet.size() < maxTokensPerSession) {
			return;
		}
		long validUntilMin = Long.MAX_VALUE;
		Token tokenToRemove = null;
		Iterator<Token> iterator = tokenSet.iterator();
		while (iterator.hasNext()) {
			Token token = iterator.next();
			if (token.isExpired()) {
				iterator.remove();
				continue;
			}
			if (token.validUntil < validUntilMin) {
				validUntilMin = token.validUntil;
				tokenToRemove = token;
			}
		}
		if ((tokenToRemove != null) && (tokenSet.size() >= maxTokensPerSession)) {
			tokenSet.remove(tokenToRemove);
		}
	}

protected static void assureSize ( final Set < Token > tokenSet ) { if ( tokenSet . size ( ) < maxTokensPerSession ) { return ; } long validUntilMin = Long . MAX_VALUE ; Token tokenToRemove = null ; Iterator < Token > iterator = tokenSet . iterator ( ) ; while ( iterator . hasNext ( ) ) { Token token = iterator . next ( ) ; if ( token . isExpired ( ) ) { iterator . remove ( ) ; continue ; } if ( token . validUntil < validUntilMin ) { validUntilMin = token . validUntil ; tokenToRemove = token ; } } if ( ( tokenToRemove != null ) && ( tokenSet . size ( ) >= maxTokensPerSession ) ) { tokenSet . remove ( tokenToRemove ) ; } }

Removes expired tokens if token set is full.
@see #setMaxTokensPerSession(int)

Removes expired tokens if token set is full .


@SuppressWarnings({"unchecked"})
	public static boolean checkCsrfToken(final HttpSession session, final String tokenValue) {
		Set<Token> tokenSet = (Set<Token>) session.getAttribute(CSRF_TOKEN_SET);
		if ((tokenSet == null) && (tokenValue == null)) {
			return true;
		}
		if ((tokenSet == null) || (tokenValue == null)) {
			return false;
		}
		boolean found = false;
		Iterator<Token> it = tokenSet.iterator();
		while (it.hasNext()) {
			Token t = it.next();
			if (t.isExpired()) {
				it.remove();
				continue;
			}
			if (t.getValue().equals(tokenValue)) {
				it.remove();
				found = true;
			}
		}
		return found;
	}

@ SuppressWarnings ( { "unchecked" } ) public static boolean checkCsrfToken ( final HttpSession session , final String tokenValue ) { Set < Token > tokenSet = ( Set < Token > ) session . getAttribute ( CSRF_TOKEN_SET ) ; if ( ( tokenSet == null ) && ( tokenValue == null ) ) { return true ; } if ( ( tokenSet == null ) || ( tokenValue == null ) ) { return false ; } boolean found = false ; Iterator < Token > it = tokenSet . iterator ( ) ; while ( it . hasNext ( ) ) { Token t = it . next ( ) ; if ( t . isExpired ( ) ) { it . remove ( ) ; continue ; } if ( t . getValue ( ) . equals ( tokenValue ) ) { it . remove ( ) ; found = true ; } } return found ; }


public static BeanCopy from(final Object source) {
		BeanCopy beanCopy = new BeanCopy(source);

		beanCopy.isSourceMap = source instanceof Map;

		return beanCopy;
	}

public static BeanCopy from ( final Object source ) { BeanCopy beanCopy = new BeanCopy ( source ) ; beanCopy . isSourceMap = source instanceof Map ; return beanCopy ; }


public void copy() {
		beanUtil = new BeanUtilBean()
						.declared(declared)
						.forced(forced)
						.silent(true);
		visit();
	}

public void copy ( ) { beanUtil = new BeanUtilBean ( ) . declared ( declared ) . forced ( forced ) . silent ( true ) ; visit ( ) ; }


@Override
	protected boolean visitProperty(String name, final Object value) {
		if (isTargetMap) {
			name = LEFT_SQ_BRACKET + name + RIGHT_SQ_BRACKET;
		}

		beanUtil.setProperty(destination, name, value);

		return true;
	}

@ Override protected boolean visitProperty ( String name , final Object value ) { if ( isTargetMap ) { name = LEFT_SQ_BRACKET + name + RIGHT_SQ_BRACKET ; } beanUtil . setProperty ( destination , name , value ) ; return true ; }

Copies single property to the destination.
Exceptions are ignored, so copying continues if
destination does not have some of the sources properties.

Copies single property to the destination . Exceptions are ignored so copying continues if destination does not have some of the sources properties .


@Override
	public void init(final TemplateData templateData) {
		super.init(templateData);
		if (entity != null) {
			ded = lookupType(entity);
		} else {
			Object object = templateData.getObjectReference(entityName);
			if (object != null) {
				ded = lookupType(resolveClass(object));
			} else {
				ded = lookupName(entityName);
			}
		}
		String tableReference = this.tableReference;

		if (tableReference == null) {
			tableReference = tableAlias;
		}
		if (tableReference == null) {
			tableReference = entityName;
		}
		if (tableReference == null) {
			tableReference = ded.getEntityName();
		}
		templateData.registerTableReference(tableReference, ded, tableAlias);
	}

@ Override public void init ( final TemplateData templateData ) { super . init ( templateData ) ; if ( entity != null ) { ded = lookupType ( entity ) ; } else { Object object = templateData . getObjectReference ( entityName ) ; if ( object != null ) { ded = lookupType ( resolveClass ( object ) ) ; } else { ded = lookupName ( entityName ) ; } } String tableReference = this . tableReference ; if ( tableReference == null ) { tableReference = tableAlias ; } if ( tableReference == null ) { tableReference = entityName ; } if ( tableReference == null ) { tableReference = ded . getEntityName ( ) ; } templateData . registerTableReference ( tableReference , ded , tableAlias ) ; }

Resolves and registers table references.

Resolves and registers table references .


@SuppressWarnings("unchecked")
	public <S extends Scope> S resolveScope(final Class<S> scopeType) {
		S scope = (S) scopes.get(scopeType);
		if (scope == null) {

			try {
				scope = newInternalInstance(scopeType, (PetiteContainer) this);
			} catch (Exception ex) {
				throw new PetiteException("Invalid Petite scope: " + scopeType.getName(), ex);
			}

			registerScope(scopeType, scope);
			scopes.put(scopeType, scope);
		}
		return scope;
	}

@
SuppressWarnings
(
"unchecked"
)
public
<
S
extends
Scope
>
S
resolveScope
(
final
Class
<
S
>
scopeType
)
{
S
scope
=
(
S
)
scopes
.
get
(
scopeType
)
;
if
(
scope
==
)
{
try
{
scope
=
newInternalInstance
(
scopeType
,
(
PetiteContainer
)
this
)
;
}
catch
(
Exception
ex
)
{
throw
new
PetiteException
(
"Invalid Petite scope: "
+
scopeType
.
getName
(
)
,
ex
)
;
}
registerScope
(
scopeType
,
scope
)
;
scopes
.
put
(
scopeType
,
scope
)
;
}
return
scope
;
}

Resolves and registers scope from a scope type.

Resolves and registers scope from a scope type .


public <T> BeanDefinition<T> registerPetiteBean(
		final Class<T> type, String name,
		Class<? extends Scope> scopeType,
		WiringMode wiringMode,
		final boolean define,
		final Consumer<T> consumer
	) {

		if (name == null) {
			name = resolveBeanName(type);
		}
		if (wiringMode == null) {
			wiringMode = annotationResolver.resolveBeanWiringMode(type);
		}
		if (wiringMode == WiringMode.DEFAULT) {
			wiringMode = petiteConfig.getDefaultWiringMode();
		}
		if (scopeType == null) {
			scopeType = annotationResolver.resolveBeanScopeType(type);
		}
		if (scopeType == null) {
			scopeType = SingletonScope.class;
		}

		// remove existing bean
		BeanDefinition existing = removeBean(name);
		if (existing != null) {
			if (petiteConfig.getDetectDuplicatedBeanNames()) {
				throw new PetiteException(
						"Duplicated bean name detected while registering class '" + type.getName() + "'. Petite bean class '" +
						existing.type.getName() + "' is already registered with the name: " + name);
			}
		}

		// check if type is valid
		if (type.isInterface()) {
			throw new PetiteException("PetiteBean can not be an interface: " + type.getName());
		}

		// registration
		if (log.isDebugEnabled()) {
			log.info("Petite bean: [" + name +
					"] --> " + type.getName() +
					" @ " + scopeType.getSimpleName() +
					":" + wiringMode.toString());
		}

		// register
		Scope scope = resolveScope(scopeType);
		BeanDefinition<T> beanDefinition = createBeanDefinitionForRegistration(name, type, scope, wiringMode, consumer);

		registerBean(name, beanDefinition);

		// providers
		ProviderDefinition[] providerDefinitions = petiteResolvers.resolveProviderDefinitions(type, name);

		if (providerDefinitions != null) {
			for (ProviderDefinition providerDefinition : providerDefinitions) {
				providers.put(providerDefinition.name, providerDefinition);
			}
		}

		// define
		if (define) {
			beanDefinition.ctor = petiteResolvers.resolveCtorInjectionPoint(beanDefinition.type());
			beanDefinition.properties = PropertyInjectionPoint.EMPTY;
			beanDefinition.methods = MethodInjectionPoint.EMPTY;
			beanDefinition.initMethods = InitMethodPoint.EMPTY;
			beanDefinition.destroyMethods = DestroyMethodPoint.EMPTY;
		}

		// return
		return beanDefinition;
	}

Registers or defines a bean.

@param type bean type, must be specified
@param name bean name, if null it will be resolved from the class (name or annotation)
@param scopeType bean scope, if null it will be resolved from the class (annotation or default one)
@param wiringMode wiring mode, if null it will be resolved from the class (annotation or default one)
@param define when set to true bean will be defined - all injection points will be set to none


protected void registerBean(final String name, final BeanDefinition beanDefinition) {
		beans.put(name, beanDefinition);

		if (!petiteConfig.isUseAltBeanNames()) {
			return;
		}

		Class type = beanDefinition.type();

		if (annotationResolver.beanHasAnnotationName(type)) {
			return;
		}

		Class[] interfaces = ClassUtil.resolveAllInterfaces(type);

		for (Class anInterface : interfaces) {
			String altName = annotationResolver.resolveBeanName(anInterface, petiteConfig.getUseFullTypeNames());

			if (name.equals(altName)) {
				continue;
			}

			if (beans.containsKey(altName)) {
				continue;
			}

			if (beansAlt.containsKey(altName)) {
				BeanDefinition existing = beansAlt.get(altName);

				if (existing != null) {
					beansAlt.put(altName, null);		// store null as value to mark that alt name is duplicate
				}
			}
			else {
				beansAlt.put(altName, beanDefinition);
			}
		}
	}

Registers bean definition by putting it in the beans map. If bean does
not have petite name explicitly defined, alternative bean names
will be registered.

Registers bean definition by putting it in the beans map . If bean does not have petite name explicitly defined alternative bean names will be registered .


public void removeBean(final Class type) {
		// collect bean names
		Set<String> beanNames = new HashSet<>();

		for (BeanDefinition def : beans.values()) {
			if (def.type.equals(type)) {
				beanNames.add(def.name);
			}
		}

		// remove collected bean names
		for (String beanName : beanNames) {
			removeBean(beanName);
		}
	}

public
void
removeBean
(
final
Class
type
)
{
// collect bean names
Set
<
String
>
beanNames
=
new
HashSet
<>
(
)
;
for
(
BeanDefinition
def
:
beans
.
values
(
)
)
{
if
(
def
.
type
.
equals
(
type
)
)
{
beanNames
.
add
(
def
.
name
)
;
}
}
// remove collected bean names
for
(
String
beanName
:
beanNames
)
{
removeBean
(
beanName
)
;
}
}

Removes all petite beans of provided type. Bean name is not resolved from a type!
Instead, all beans are iterated and only beans with equal types are removed.
@see #removeBean(String)

Removes all petite beans of provided type . Bean name is not resolved from a type! Instead all beans are iterated and only beans with equal types are removed .


protected String[] resolveBeanNamesForType(final Class type) {
		String[] beanNames = beanCollections.get(type);
		if (beanNames != null) {
			return beanNames;
		}

		ArrayList<String> list = new ArrayList<>();

		for (Map.Entry<String, BeanDefinition> entry : beans.entrySet()) {
			BeanDefinition beanDefinition = entry.getValue();

			if (ClassUtil.isTypeOf(beanDefinition.type, type)) {
				String beanName = entry.getKey();
				list.add(beanName);
			}
		}

		if (list.isEmpty()) {
			beanNames = StringPool.EMPTY_ARRAY;
		} else {
			beanNames = list.toArray(new String[0]);
		}

		beanCollections.put(type, beanNames);
		return beanNames;
	}

protected String [ ] resolveBeanNamesForType ( final Class type ) { String [ ] beanNames = beanCollections . get ( type ) ; if ( beanNames != null ) { return beanNames ; } ArrayList < String > list = new ArrayList <> ( ) ; for ( Map . Entry < String , BeanDefinition > entry : beans . entrySet ( ) ) { BeanDefinition beanDefinition = entry . getValue ( ) ; if ( ClassUtil . isTypeOf ( beanDefinition . type , type ) ) { String beanName = entry . getKey ( ) ; list . add ( beanName ) ; } } if ( list . isEmpty ( ) ) { beanNames = StringPool . EMPTY_ARRAY ; } else { beanNames = list . toArray ( new String [ 0 ] ) ; } beanCollections . put ( type , beanNames ) ; return beanNames ; }


public void registerPetiteCtorInjectionPoint(final String beanName, final Class[] paramTypes, final String[] references) {
		BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName);

		ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type);
		Constructor constructor = null;

		if (paramTypes == null) {
			CtorDescriptor[] ctors = cd.getAllCtorDescriptors();
			if (ctors != null && ctors.length > 0) {
				if (ctors.length > 1) {
					throw new PetiteException(ctors.length + " suitable constructor found as injection point for: " + beanDefinition.type.getName());
				}
				constructor = ctors[0].getConstructor();
			}
		} else {
			CtorDescriptor ctorDescriptor = cd.getCtorDescriptor(paramTypes, true);

			if (ctorDescriptor != null) {
				constructor = ctorDescriptor.getConstructor();
			}
		}

		if (constructor == null) {
			throw new PetiteException("Constructor not found: " + beanDefinition.type.getName());
		}

		BeanReferences[] ref = referencesResolver.resolveReferenceFromValues(constructor, references);

		beanDefinition.ctor = new CtorInjectionPoint(constructor, ref);
	}

Registers constructor injection point.

@param beanName bean name
@param paramTypes constructor parameter types, may be null
@param references references for arguments


public void registerPetitePropertyInjectionPoint(final String beanName, final String property, final String reference) {
		BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName);

		ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type);
		PropertyDescriptor propertyDescriptor = cd.getPropertyDescriptor(property, true);

		if (propertyDescriptor == null) {
			throw new PetiteException("Property not found: " + beanDefinition.type.getName() + '#' + property);
		}

		BeanReferences ref = referencesResolver.resolveReferenceFromValue(propertyDescriptor, reference);

		PropertyInjectionPoint pip = new PropertyInjectionPoint(propertyDescriptor, ref);

		beanDefinition.addPropertyInjectionPoint(pip);
	}

public
void
registerPetitePropertyInjectionPoint
(
final
String
beanName
,
final
String
property
,
final
String
reference
)
{
BeanDefinition
beanDefinition
=
lookupExistingBeanDefinition
(
beanName
)
;
ClassDescriptor
cd
=
ClassIntrospector
.
get
(
)
.
lookup
(
beanDefinition
.
type
)
;
PropertyDescriptor
propertyDescriptor
=
cd
.
getPropertyDescriptor
(
property
,
true
)
;
if
(
propertyDescriptor
==
)
{
throw
new
PetiteException
(
"Property not found: "
+
beanDefinition
.
type
.
getName
(
)
+
'
'
+
property
)
;
}
BeanReferences
ref
=
referencesResolver
.
resolveReferenceFromValue
(
propertyDescriptor
,
reference
)
;
PropertyInjectionPoint
pip
=
new
PropertyInjectionPoint
(
propertyDescriptor
,
ref
)
;
beanDefinition
.
addPropertyInjectionPoint
(
pip
)
;
}

Registers property injection point.

@param beanName bean name
@param property property name
@param reference explicit injection reference, may be null


public void registerPetiteSetInjectionPoint(final String beanName, final String property) {
		BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName);
		ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type);

		PropertyDescriptor propertyDescriptor = cd.getPropertyDescriptor(property, true);

		if (propertyDescriptor == null) {
			throw new PetiteException("Property not found: " + beanDefinition.type.getName() + '#' + property);
		}

		SetInjectionPoint sip = new SetInjectionPoint(propertyDescriptor);

		beanDefinition.addSetInjectionPoint(sip);
	}

public
void
registerPetiteSetInjectionPoint
(
final
String
beanName
,
final
String
property
)
{
BeanDefinition
beanDefinition
=
lookupExistingBeanDefinition
(
beanName
)
;
ClassDescriptor
cd
=
ClassIntrospector
.
get
(
)
.
lookup
(
beanDefinition
.
type
)
;
PropertyDescriptor
propertyDescriptor
=
cd
.
getPropertyDescriptor
(
property
,
true
)
;
if
(
propertyDescriptor
==
)
{
throw
new
PetiteException
(
"Property not found: "
+
beanDefinition
.
type
.
getName
(
)
+
'
'
+
property
)
;
}
SetInjectionPoint
sip
=
new
SetInjectionPoint
(
propertyDescriptor
)
;
beanDefinition
.
addSetInjectionPoint
(
sip
)
;
}

Registers set injection point.

@param beanName bean name
@param property set property name


public void registerPetiteMethodInjectionPoint(final String beanName, final String methodName, final Class[] arguments, final String[] references) {
		BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName);

		ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type);

		Method method = null;
		if (arguments == null) {
			MethodDescriptor[] methods = cd.getAllMethodDescriptors(methodName);

			if (methods != null && methods.length > 0) {
				if (methods.length > 1) {
					throw new PetiteException(methods.length + " suitable methods found as injection points for: " + beanDefinition.type.getName() + '#' + methodName);
				}
				method = methods[0].getMethod();
			}
		} else {
			MethodDescriptor md = cd.getMethodDescriptor(methodName, arguments, true);
			if (md != null) {
				method = md.getMethod();
			}
		}
		if (method == null) {
			throw new PetiteException("Method not found: " + beanDefinition.type.getName() + '#' + methodName);
		}

		BeanReferences[] ref = referencesResolver.resolveReferenceFromValues(method, references);

		MethodInjectionPoint mip = new MethodInjectionPoint(method, ref);

		beanDefinition.addMethodInjectionPoint(mip);
	}

Registers method injection point.

@param beanName bean name
@param methodName method name
@param arguments method arguments, may be null
@param references injection references


public void registerPetiteInitMethods(final String beanName, final InitMethodInvocationStrategy invocationStrategy, String... initMethodNames) {
		BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName);

		ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type);
		if (initMethodNames == null) {
			initMethodNames = StringPool.EMPTY_ARRAY;
		}

		int total = initMethodNames.length;
		InitMethodPoint[] initMethodPoints = new InitMethodPoint[total];

		int i;
		for (i = 0; i < initMethodNames.length; i++) {
			MethodDescriptor md = cd.getMethodDescriptor(initMethodNames[i], ClassUtil.EMPTY_CLASS_ARRAY, true);
			if (md == null) {
				throw new PetiteException("Init method not found: " + beanDefinition.type.getName() + '#' + initMethodNames[i]);
			}
			initMethodPoints[i] = new InitMethodPoint(md.getMethod(), i, invocationStrategy);
		}

		beanDefinition.addInitMethodPoints(initMethodPoints);
	}

public
void
registerPetiteInitMethods
(
final
String
beanName
,
final
InitMethodInvocationStrategy
invocationStrategy
,
String
...
initMethodNames
)
{
BeanDefinition
beanDefinition
=
lookupExistingBeanDefinition
(
beanName
)
;
ClassDescriptor
cd
=
ClassIntrospector
.
get
(
)
.
lookup
(
beanDefinition
.
type
)
;
if
(
initMethodNames
==
)
{
initMethodNames
=
StringPool
.
EMPTY_ARRAY
;
}
int
total
=
initMethodNames
.
length
;
InitMethodPoint
[
]
initMethodPoints
=
new
InitMethodPoint
[
total
]
;
int
i
;
for
(
i
=
0
;
i
<
initMethodNames
.
length
;
i
++
)
{
MethodDescriptor
md
=
cd
.
getMethodDescriptor
(
initMethodNames
[
i
]
,
ClassUtil
.
EMPTY_CLASS_ARRAY
,
true
)
;
if
(
md
==
)
{
throw
new
PetiteException
(
"Init method not found: "
+
beanDefinition
.
type
.
getName
(
)
+
'
'
+
initMethodNames
[
i
]
)
;
}
initMethodPoints
[
i
]
=
new
InitMethodPoint
(
md
.
getMethod
(
)
,
i
,
invocationStrategy
)
;
}
beanDefinition
.
addInitMethodPoints
(
initMethodPoints
)
;
}

Registers init method.

@param beanName bean name
@param invocationStrategy moment of invocation
@param initMethodNames init method names


public void registerPetiteDestroyMethods(final String beanName, String... destroyMethodNames) {
		BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName);

		ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type);
		if (destroyMethodNames == null) {
			destroyMethodNames = StringPool.EMPTY_ARRAY;
		}

		int total = destroyMethodNames.length;
		DestroyMethodPoint[] destroyMethodPoints = new DestroyMethodPoint[total];

		int i;
		for (i = 0; i < destroyMethodNames.length; i++) {
			MethodDescriptor md = cd.getMethodDescriptor(destroyMethodNames[i], ClassUtil.EMPTY_CLASS_ARRAY, true);
			if (md == null) {
				throw new PetiteException("Destroy method not found: " + beanDefinition.type.getName() + '#' + destroyMethodNames[i]);
			}
			destroyMethodPoints[i] = new DestroyMethodPoint(md.getMethod());
		}

		beanDefinition.addDestroyMethodPoints(destroyMethodPoints);
	}

public
void
registerPetiteDestroyMethods
(
final
String
beanName
,
String
...
destroyMethodNames
)
{
BeanDefinition
beanDefinition
=
lookupExistingBeanDefinition
(
beanName
)
;
ClassDescriptor
cd
=
ClassIntrospector
.
get
(
)
.
lookup
(
beanDefinition
.
type
)
;
if
(
destroyMethodNames
==
)
{
destroyMethodNames
=
StringPool
.
EMPTY_ARRAY
;
}
int
total
=
destroyMethodNames
.
length
;
DestroyMethodPoint
[
]
destroyMethodPoints
=
new
DestroyMethodPoint
[
total
]
;
int
i
;
for
(
i
=
0
;
i
<
destroyMethodNames
.
length
;
i
++
)
{
MethodDescriptor
md
=
cd
.
getMethodDescriptor
(
destroyMethodNames
[
i
]
,
ClassUtil
.
EMPTY_CLASS_ARRAY
,
true
)
;
if
(
md
==
)
{
throw
new
PetiteException
(
"Destroy method not found: "
+
beanDefinition
.
type
.
getName
(
)
+
'
'
+
destroyMethodNames
[
i
]
)
;
}
destroyMethodPoints
[
i
]
=
new
DestroyMethodPoint
(
md
.
getMethod
(
)
)
;
}
beanDefinition
.
addDestroyMethodPoints
(
destroyMethodPoints
)
;
}

Registers destroy method.

@param beanName bean name
@param destroyMethodNames destroy method names


public void registerPetiteProvider(final String providerName, final String beanName, final String methodName, final Class[] arguments) {
		BeanDefinition beanDefinition = lookupBeanDefinition(beanName);

		if (beanDefinition == null) {
			throw new PetiteException("Bean not found: " + beanName);
		}

		Class beanType = beanDefinition.type;

		ClassDescriptor cd = ClassIntrospector.get().lookup(beanType);
		MethodDescriptor md = cd.getMethodDescriptor(methodName, arguments, true);

		if (md == null) {
			throw new PetiteException("Provider method not found: " + methodName);
		}

		ProviderDefinition providerDefinition = new ProviderDefinition(providerName, beanName, md.getMethod());

		providers.put(providerName, providerDefinition);
	}

public
void
registerPetiteProvider
(
final
String
providerName
,
final
String
beanName
,
final
String
methodName
,
final
Class
[
]
arguments
)
{
BeanDefinition
beanDefinition
=
lookupBeanDefinition
(
beanName
)
;
if
(
beanDefinition
==
)
{
throw
new
PetiteException
(
"Bean not found: "
+
beanName
)
;
}
Class
beanType
=
beanDefinition
.
type
;
ClassDescriptor
cd
=
ClassIntrospector
.
get
(
)
.
lookup
(
beanType
)
;
MethodDescriptor
md
=
cd
.
getMethodDescriptor
(
methodName
,
arguments
,
true
)
;
if
(
md
==
)
{
throw
new
PetiteException
(
"Provider method not found: "
+
methodName
)
;
}
ProviderDefinition
providerDefinition
=
new
ProviderDefinition
(
providerName
,
beanName
,
md
.
getMethod
(
)
)
;
providers
.
put
(
providerName
,
providerDefinition
)
;
}

Registers instance method provider.

@param providerName provider name
@param beanName bean name
@param methodName instance method name
@param arguments method argument types


public void registerPetiteProvider(final String providerName, final Class type, final String staticMethodName, final Class[] arguments) {
		ClassDescriptor cd = ClassIntrospector.get().lookup(type);
		MethodDescriptor md = cd.getMethodDescriptor(staticMethodName, arguments, true);

		if (md == null) {
			throw new PetiteException("Provider method not found: " + staticMethodName);
		}

		ProviderDefinition providerDefinition = new ProviderDefinition(providerName, md.getMethod());

		providers.put(providerName, providerDefinition);
	}

public
void
registerPetiteProvider
(
final
String
providerName
,
final
Class
type
,
final
String
staticMethodName
,
final
Class
[
]
arguments
)
{
ClassDescriptor
cd
=
ClassIntrospector
.
get
(
)
.
lookup
(
type
)
;
MethodDescriptor
md
=
cd
.
getMethodDescriptor
(
staticMethodName
,
arguments
,
true
)
;
if
(
md
==
)
{
throw
new
PetiteException
(
"Provider method not found: "
+
staticMethodName
)
;
}
ProviderDefinition
providerDefinition
=
new
ProviderDefinition
(
providerName
,
md
.
getMethod
(
)
)
;
providers
.
put
(
providerName
,
providerDefinition
)
;
}

Registers static method provider.

@param providerName provider name
@param type class type
@param staticMethodName static method name
@param arguments method argument types


public void forEachBeanType(final Class type, final Consumer<String> beanNameConsumer) {
		forEachBean(bd -> {
			if (ClassUtil.isTypeOf(bd.type, type)) {
				beanNameConsumer.accept(bd.name);
			}
		});
	}

public void forEachBeanType ( final Class type , final Consumer < String > beanNameConsumer ) { forEachBean ( bd -> { if ( ClassUtil . isTypeOf ( bd . type , type ) ) { beanNameConsumer . accept ( bd . name ) ; } } ) ; }

Iterates all beans that are of given type.

Iterates all beans that are of given type .


public void defineParameters(final Map<?, ?> properties) {
		for (Map.Entry<?, ?> entry : properties.entrySet()) {
			defineParameter(entry.getKey().toString(), entry.getValue());
		}
	}

public void defineParameters ( final Map < ? , ? > properties ) { for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { defineParameter ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } }


@Override
	public Object intercept(final ActionRequest actionRequest) throws Exception {
		printBefore(actionRequest);
		long startTime = System.currentTimeMillis();
		Object result = null;
		try {
			result = actionRequest.invoke();
		} catch (Exception ex) {
			result = "<exception>";
			throw ex;
		} catch (Throwable th) {
			result = "<throwable>";
			throw new Exception(th);
		} finally {
			long executionTime = System.currentTimeMillis() - startTime;
			printAfter(actionRequest, executionTime, result);
		}
		return result;
	}

@ Override public Object intercept ( final ActionRequest actionRequest ) throws Exception { printBefore ( actionRequest ) ; long startTime = System . currentTimeMillis ( ) ; Object result = null ; try { result = actionRequest . invoke ( ) ; } catch ( Exception ex ) { result = "<exception>" ; throw ex ; } catch ( Throwable th ) { result = "<throwable>" ; throw new Exception ( th ) ; } finally { long executionTime = System . currentTimeMillis ( ) - startTime ; printAfter ( actionRequest , executionTime , result ) ; } return result ; }


public static int resolveJavaVersion(final int version) {
		final int javaVersionNumber = SystemUtil.info().getJavaVersionNumber();
		final int platformVersion = javaVersionNumber - 8 + 52;

		return version > platformVersion ? version : platformVersion;
	}

public static int resolveJavaVersion ( final int version ) { final int javaVersionNumber = SystemUtil . info ( ) . getJavaVersionNumber ( ) ; final int platformVersion = javaVersionNumber - 8 + 52 ; return version > platformVersion ? version : platformVersion ; }

Resolves Java version from current version.

Resolves Java version from current version .


public static void pushInt(final MethodVisitor mv, final int value) {
		if (value <= 5) {
			mv.visitInsn(ICONST_0 + value);
		} else if (value <= Byte.MAX_VALUE) {
			mv.visitIntInsn(BIPUSH, value);
		}  else {
			mv.visitIntInsn(SIPUSH, value);
		}
	}

public static void pushInt ( final MethodVisitor mv , final int value ) { if ( value <= 5 ) { mv . visitInsn ( ICONST_0 + value ) ; } else if ( value <= Byte . MAX_VALUE ) { mv . visitIntInsn ( BIPUSH , value ) ; } else { mv . visitIntInsn ( SIPUSH , value ) ; } }


public static void checkArgumentIndex(final MethodInfo methodInfo, final int argIndex) {
		if ((argIndex < 1) || (argIndex > methodInfo.getArgumentsCount())) {
			throw new ProxettaException("Invalid argument index: " + argIndex);
		}
	}

public
static
void
checkArgumentIndex
(
final
MethodInfo
methodInfo
,
final
int
argIndex
)
{
if
(
(
argIndex
<
1
)
||
(
argIndex
>
methodInfo
.
getArgumentsCount
(
)
)
)
{
throw
new
ProxettaException
(
"Invalid argument index: "
+
argIndex
)
;
}
}


public static String adviceFieldName(final String name, final int index) {
		return ProxettaNames.fieldPrefix + name + ProxettaNames.fieldDivider + index;
	}

public static String adviceFieldName ( final String name , final int index ) { return ProxettaNames . fieldPrefix + name + ProxettaNames . fieldDivider + index ; }


public static String adviceMethodName(final String name, final int index) {
		return ProxettaNames.methodPrefix + name + ProxettaNames.methodDivider + index;
	}

public static String adviceMethodName ( final String name , final int index ) { return ProxettaNames . methodPrefix + name + ProxettaNames . methodDivider + index ; }


public static void loadSpecialMethodArguments(final MethodVisitor mv, final MethodInfo methodInfo) {
		mv.visitVarInsn(ALOAD, 0);
		for (int i = 1; i <= methodInfo.getArgumentsCount(); i++) {
			loadMethodArgument(mv, methodInfo, i);
		}
	}

public static void loadSpecialMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { mv . visitVarInsn ( ALOAD , 0 ) ; for ( int i = 1 ; i <= methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }

Loads all method arguments before INVOKESPECIAL call.

Loads all method arguments before INVOKESPECIAL call .


public static void loadStaticMethodArguments(final MethodVisitor mv, final MethodInfo methodInfo) {
		for (int i = 0; i < methodInfo.getArgumentsCount(); i++) {
			loadMethodArgument(mv, methodInfo, i);
		}
	}

public static void loadStaticMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { for ( int i = 0 ; i < methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }

Loads all method arguments before INVOKESTATIC call.

Loads all method arguments before INVOKESTATIC call .


public static void loadVirtualMethodArguments(final MethodVisitor mv, final MethodInfo methodInfo) {
		for (int i = 1; i <= methodInfo.getArgumentsCount(); i++) {
			loadMethodArgument(mv, methodInfo, i);
		}
	}

public static void loadVirtualMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { for ( int i = 1 ; i <= methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }

Loads all method arguments before INVOKEVIRTUAL call.

Loads all method arguments before INVOKEVIRTUAL call .


public static void loadMethodArgument(final MethodVisitor mv, final MethodInfo methodInfo, final int index) {
		int offset = methodInfo.getArgumentOffset(index);
		int type = methodInfo.getArgument(index).getOpcode();
		switch (type) {
			case 'V':
				break;
			case 'B':
			case 'C':
			case 'S':
			case 'I':
			case 'Z':
				mv.visitVarInsn(ILOAD, offset);
				break;
			case 'J':
				mv.visitVarInsn(LLOAD, offset);
				break;
			case 'F':
				mv.visitVarInsn(FLOAD, offset);
				break;
			case 'D':
				mv.visitVarInsn(DLOAD, offset);
				break;
			default:
				mv.visitVarInsn(ALOAD, offset);
		}
	}

public static void loadMethodArgument ( final MethodVisitor mv , final MethodInfo methodInfo , final int index ) { int offset = methodInfo . getArgumentOffset ( index ) ; int type = methodInfo . getArgument ( index ) . getOpcode ( ) ; switch ( type ) { case ' ' : break ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : mv . visitVarInsn ( ILOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( LLOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( FLOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( DLOAD , offset ) ; break ; default : mv . visitVarInsn ( ALOAD , offset ) ; } }

Loads one argument. Index is 1-based. No conversion occurs.

Loads one argument . Index is 1 - based . No conversion occurs .


public static void storeMethodArgument(final MethodVisitor mv, final MethodInfo methodInfo, final int index) {
		int offset = methodInfo.getArgumentOffset(index);
		int type = methodInfo.getArgument(index).getOpcode();
		switch (type) {
			case 'V':
				break;
			case 'B':
			case 'C':
			case 'S':
			case 'I':
			case 'Z':
				mv.visitVarInsn(ISTORE, offset); break;
			case 'J':
				mv.visitVarInsn(LSTORE, offset); break;
			case 'F':
				mv.visitVarInsn(FSTORE, offset); break;
			case 'D':
				mv.visitVarInsn(DSTORE, offset); break;
			default:
				mv.visitVarInsn(ASTORE, offset);
		}
	}

public static void storeMethodArgument ( final MethodVisitor mv , final MethodInfo methodInfo , final int index ) { int offset = methodInfo . getArgumentOffset ( index ) ; int type = methodInfo . getArgument ( index ) . getOpcode ( ) ; switch ( type ) { case ' ' : break ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : mv . visitVarInsn ( ISTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( LSTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( FSTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( DSTORE , offset ) ; break ; default : mv . visitVarInsn ( ASTORE , offset ) ; } }

Stores one argument. Index is 1-based. No conversion occurs.

Stores one argument . Index is 1 - based . No conversion occurs .


public static void prepareReturnValue(final MethodVisitor mv, final MethodInfo methodInfo, int varOffset) {
		varOffset += methodInfo.getAllArgumentsSize();
		switch (methodInfo.getReturnType().getOpcode()) {
			case 'V':
				mv.visitInsn(ACONST_NULL);
				break;
			case 'B':
				AsmUtil.valueOfByte(mv);
				break;
			case 'C':
				AsmUtil.valueOfCharacter(mv);
				break;
			case 'S':
				AsmUtil.valueOfShort(mv);
				break;
			case 'I':
				AsmUtil.valueOfInteger(mv);
				break;
			case 'Z':
				AsmUtil.valueOfBoolean(mv);
				break;
			case 'J':
				AsmUtil.valueOfLong(mv);
				break;
			case 'F':
				AsmUtil.valueOfFloat(mv);
				break;
			case 'D':
				AsmUtil.valueOfDouble(mv);
				break;

		}
	}

public static void prepareReturnValue ( final MethodVisitor mv , final MethodInfo methodInfo , int varOffset ) { varOffset += methodInfo . getAllArgumentsSize ( ) ; switch ( methodInfo . getReturnType ( ) . getOpcode ( ) ) { case ' ' : mv . visitInsn ( ACONST_NULL ) ; break ; case ' ' : AsmUtil . valueOfByte ( mv ) ; break ; case ' ' : AsmUtil . valueOfCharacter ( mv ) ; break ; case ' ' : AsmUtil . valueOfShort ( mv ) ; break ; case ' ' : AsmUtil . valueOfInteger ( mv ) ; break ; case ' ' : AsmUtil . valueOfBoolean ( mv ) ; break ; case ' ' : AsmUtil . valueOfLong ( mv ) ; break ; case ' ' : AsmUtil . valueOfFloat ( mv ) ; break ; case ' ' : AsmUtil . valueOfDouble ( mv ) ; break ; } }


public static String createMethodSignaturesKey(final int access, final String methodName, final String description, final String className) {
		return new StringBand(7)
			.append(access)
			.append(COLON)
			.append(description)
			.append(StringPool.UNDERSCORE)
			.append(className)
			.append(StringPool.HASH)
			.append(methodName)
			.toString();
	}

public static String createMethodSignaturesKey ( final int access , final String methodName , final String description , final String className ) { return new StringBand ( 7 ) . append ( access ) . append ( COLON ) . append ( description ) . append ( StringPool . UNDERSCORE ) . append ( className ) . append ( StringPool . HASH ) . append ( methodName ) . toString ( ) ; }

Creates unique key for method signatures map.

Creates unique key for method signatures map .


public static void newArray(final MethodVisitor mv, final Class componentType) {
		if (componentType == int.class) {
			mv.visitIntInsn(NEWARRAY, T_INT);
			return;
		}
		if (componentType == long.class) {
			mv.visitIntInsn(NEWARRAY, T_LONG);
			return;
		}
		if (componentType == float.class) {
			mv.visitIntInsn(NEWARRAY, T_FLOAT);
			return;
		}
		if (componentType == double.class) {
			mv.visitIntInsn(NEWARRAY, T_DOUBLE);
			return;
		}
		if (componentType == byte.class) {
			mv.visitIntInsn(NEWARRAY, T_BYTE);
			return;
		}
		if (componentType == short.class) {
			mv.visitIntInsn(NEWARRAY, T_SHORT);
			return;
		}
		if (componentType == boolean.class) {
			mv.visitIntInsn(NEWARRAY, T_BOOLEAN);
			return;
		}
		if (componentType == char.class) {
			mv.visitIntInsn(NEWARRAY, T_CHAR);
			return;
		}

		mv.visitTypeInsn(ANEWARRAY, AsmUtil.typeToSignature(componentType));
	}

public static void newArray ( final MethodVisitor mv , final Class componentType ) { if ( componentType == int . class ) { mv . visitIntInsn ( NEWARRAY , T_INT ) ; return ; } if ( componentType == long . class ) { mv . visitIntInsn ( NEWARRAY , T_LONG ) ; return ; } if ( componentType == float . class ) { mv . visitIntInsn ( NEWARRAY , T_FLOAT ) ; return ; } if ( componentType == double . class ) { mv . visitIntInsn ( NEWARRAY , T_DOUBLE ) ; return ; } if ( componentType == byte . class ) { mv . visitIntInsn ( NEWARRAY , T_BYTE ) ; return ; } if ( componentType == short . class ) { mv . visitIntInsn ( NEWARRAY , T_SHORT ) ; return ; } if ( componentType == boolean . class ) { mv . visitIntInsn ( NEWARRAY , T_BOOLEAN ) ; return ; } if ( componentType == char . class ) { mv . visitIntInsn ( NEWARRAY , T_CHAR ) ; return ; } mv . visitTypeInsn ( ANEWARRAY , AsmUtil . typeToSignature ( componentType ) ) ; }


public static void storeIntoArray(final MethodVisitor mv, final Class componentType) {
		if (componentType == int.class) {
			mv.visitInsn(IASTORE);
			return;
		}
		if (componentType == long.class) {
			mv.visitInsn(LASTORE);
			return;
		}
		if (componentType == float.class) {
			mv.visitInsn(FASTORE);
			return;
		}
		if (componentType == double.class) {
			mv.visitInsn(DASTORE);
			return;
		}
		if (componentType == byte.class) {
			mv.visitInsn(BASTORE);
			return;
		}
		if (componentType == short.class) {
			mv.visitInsn(SASTORE);
			return;
		}
		if (componentType == boolean.class) {
			mv.visitInsn(BASTORE);
			return;
		}
		if (componentType == char.class) {
			mv.visitInsn(CASTORE);
			return;
		}

		mv.visitInsn(AASTORE);
	}

public static void storeIntoArray ( final MethodVisitor mv , final Class componentType ) { if ( componentType == int . class ) { mv . visitInsn ( IASTORE ) ; return ; } if ( componentType == long . class ) { mv . visitInsn ( LASTORE ) ; return ; } if ( componentType == float . class ) { mv . visitInsn ( FASTORE ) ; return ; } if ( componentType == double . class ) { mv . visitInsn ( DASTORE ) ; return ; } if ( componentType == byte . class ) { mv . visitInsn ( BASTORE ) ; return ; } if ( componentType == short . class ) { mv . visitInsn ( SASTORE ) ; return ; } if ( componentType == boolean . class ) { mv . visitInsn ( BASTORE ) ; return ; } if ( componentType == char . class ) { mv . visitInsn ( CASTORE ) ; return ; } mv . visitInsn ( AASTORE ) ; }


public static String extractEncoding(final String contentType, String defaultEncoding) {
		String encoding = extractEncoding(contentType);

		if (encoding == null) {
			if (defaultEncoding == null) {
				defaultEncoding = JoddCore.encoding;
			}
			encoding = defaultEncoding;
		}
		return encoding;
	}

public static String extractEncoding ( final String contentType , String defaultEncoding ) { String encoding = extractEncoding ( contentType ) ; if ( encoding == null ) { if ( defaultEncoding == null ) { defaultEncoding = JoddCore . encoding ; } encoding = defaultEncoding ; } return encoding ; }

Extracts encoding from a given content type.

@param contentType     content type.
@param defaultEncoding Default encoding to be used if extract returns {@code null}.
If defaultEncoding is {@code null}, {@link JoddCore#encoding} will be used.
@return Encoding from the content type.
@see #extractEncoding(String)

Extracts encoding from a given content type .


public static boolean isEmptyFlags(Flags flags) {
		if (flags == null) return true;
		Flags.Flag[] systemFlags = flags.getSystemFlags();
		if (systemFlags != null && systemFlags.length > 0) {
			return false;
		}
		String[] userFlags = flags.getUserFlags();
		if (userFlags != null && userFlags.length > 0) {
			return false;
		}

		return true;
	}

public static boolean isEmptyFlags ( Flags flags ) { if ( flags == null ) return true ; Flags . Flag [ ] systemFlags = flags . getSystemFlags ( ) ; if ( systemFlags != null && systemFlags . length > 0 ) { return false ; } String [ ] userFlags = flags . getUserFlags ( ) ; if ( userFlags != null && userFlags . length > 0 ) { return false ; } return true ; }

Check whether flags is a empty flags
@param flags a flags of message to check
@return whether the flags is empty


public static String resolveAuthBearerToken(final HttpServletRequest request) {
		String header = request.getHeader(HEADER_AUTHORIZATION);
		if (header == null) {
			return null;
		}
		int ndx = header.indexOf("Bearer ");
		if (ndx == -1) {
			return null;
		}

		return header.substring(ndx + 7).trim();
	}

public
static
String
resolveAuthBearerToken
(
final
HttpServletRequest
request
)
{
String
header
=
request
.
getHeader
(
HEADER_AUTHORIZATION
)
;
if
(
header
==
)
{
return
;
}
int
ndx
=
header
.
indexOf
(
"Bearer "
)
;
if
(
ndx
==
1
)
{
return
;
}
return
header
.
substring
(
ndx
+
7
)
.
trim
(
)
;
}


public static void requireAuthentication(final HttpServletResponse resp, final String realm) throws IOException {
		resp.setHeader(WWW_AUTHENTICATE, "Basic realm=\"" + realm + '\"');
		resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
	}

public
static
void
requireAuthentication
(
final
HttpServletResponse
resp
,
final
String
realm
)
throws
IOException
{
resp
.
setHeader
(
WWW_AUTHENTICATE
,
"Basic realm=\""
+
realm
+
'
'
)
;
resp
.
sendError
(
HttpServletResponse
.
SC_UNAUTHORIZED
)
;
}

Sends correct headers to require basic authentication for the given realm.

Sends correct headers to require basic authentication for the given realm .


public static void prepareDownload(final HttpServletResponse response, final File file, final String mimeType) {
		if (!file.exists()) {
			throw new IllegalArgumentException("File not found: " + file);
		}
		if (file.length() > Integer.MAX_VALUE) {
			throw new IllegalArgumentException("File too big: " + file);
		}
		prepareResponse(response, file.getAbsolutePath(), mimeType, (int) file.length());
	}

public
static
void
prepareDownload
(
final
HttpServletResponse
response
,
final
File
file
,
final
String
mimeType
)
{
if
(
!
file
.
exists
(
)
)
{
throw
new
IllegalArgumentException
(
"File not found: "
+
file
)
;
}
if
(
file
.
length
(
)
>
Integer
.
MAX_VALUE
)
{
throw
new
IllegalArgumentException
(
"File too big: "
+
file
)
;
}
prepareResponse
(
response
,
file
.
getAbsolutePath
(
)
,
mimeType
,
(
int
)
file
.
length
(
)
)
;
}

Prepares response for file download with provided mime type.

Prepares response for file download with provided mime type .


public static void prepareResponse(final HttpServletResponse response, final String fileName, String mimeType, final int fileSize) {
		if ((mimeType == null) && (fileName != null)) {
			String extension = FileNameUtil.getExtension(fileName);
			mimeType = MimeTypes.getMimeType(extension);
		}

		if (mimeType != null) {
			response.setContentType(mimeType);
		}

		if (fileSize >= 0) {
			response.setContentLength(fileSize);
		}

		// support internationalization
		// See https://tools.ietf.org/html/rfc6266#section-5 for more information.
		if (fileName != null) {
			String name = FileNameUtil.getName(fileName);
			String encodedFileName = URLCoder.encode(name);

			response.setHeader(CONTENT_DISPOSITION,
				"attachment;filename=\"" + name + "\";filename*=utf8''" + encodedFileName);
		}
	}

Prepares response for various provided data.

@param response http response
@param fileName file name, if full path then file name will be stripped, if null, will be ignored.
@param mimeType mime type with optional charset, may be null
@param fileSize if less then 0 it will be ignored

Prepares response for various provided data .


public static Cookie[] getAllCookies(final HttpServletRequest request, final String cookieName) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			return null;
		}
		ArrayList<Cookie> list = new ArrayList<>(cookies.length);
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(cookieName)) {
				list.add(cookie);
			}
		}
		if (list.isEmpty()) {
			return null;
		}
		return list.toArray(new Cookie[0]);
	}

public static Cookie [ ] getAllCookies ( final HttpServletRequest request , final String cookieName ) { Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies == null ) { return null ; } ArrayList < Cookie > list = new ArrayList <> ( cookies . length ) ; for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( cookieName ) ) { list . add ( cookie ) ; } } if ( list . isEmpty ( ) ) { return null ; } return list . toArray ( new Cookie [ 0 ] ) ; }

Returns all cookies from client that matches provided name.
@see #getCookie(javax.servlet.http.HttpServletRequest, String)

Returns all cookies from client that matches provided name .


public static String readRequestBodyFromReader(final HttpServletRequest request) throws IOException {
		BufferedReader buff = request.getReader();
		StringWriter out = new StringWriter();
		StreamUtil.copy(buff, out);
		return out.toString();
	}

public static String readRequestBodyFromReader ( final HttpServletRequest request ) throws IOException { BufferedReader buff = request . getReader ( ) ; StringWriter out = new StringWriter ( ) ; StreamUtil . copy ( buff , out ) ; return out . toString ( ) ; }

Reads HTTP request body using the request reader. Once body is read,
it cannot be read again!

Reads HTTP request body using the request reader . Once body is read it cannot be read again!


public static String readRequestBodyFromStream(final HttpServletRequest request) throws IOException {
		String charEncoding = request.getCharacterEncoding();
		if (charEncoding == null) {
			charEncoding = JoddCore.encoding;
		}
		CharArrayWriter charArrayWriter = new CharArrayWriter();
		BufferedReader bufferedReader = null;

		try {
			InputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charEncoding));

				StreamUtil.copy(bufferedReader, charArrayWriter);
			} else {
				return StringPool.EMPTY;
			}
		} finally {
			StreamUtil.close(bufferedReader);
		}

		return charArrayWriter.toString();
	}

public static String readRequestBodyFromStream ( final HttpServletRequest request ) throws IOException { String charEncoding = request . getCharacterEncoding ( ) ; if ( charEncoding == null ) { charEncoding = JoddCore . encoding ; } CharArrayWriter charArrayWriter = new CharArrayWriter ( ) ; BufferedReader bufferedReader = null ; try { InputStream inputStream = request . getInputStream ( ) ; if ( inputStream != null ) { bufferedReader = new BufferedReader ( new InputStreamReader ( inputStream , charEncoding ) ) ; StreamUtil . copy ( bufferedReader , charArrayWriter ) ; } else { return StringPool . EMPTY ; } } finally { StreamUtil . close ( bufferedReader ) ; } return charArrayWriter . toString ( ) ; }

Reads HTTP request body using the request stream. Once body is read,
it cannot be read again!

Reads HTTP request body using the request stream . Once body is read it cannot be read again!


public static void storeContextPath(final PageContext pageContext, final String contextPathVariableName) {
		String ctxPath = getContextPath(pageContext);

		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		request.setAttribute(contextPathVariableName, ctxPath);

		ServletContext servletContext = pageContext.getServletContext();
		servletContext.setAttribute(contextPathVariableName, ctxPath);
	}

public static void storeContextPath ( final PageContext pageContext , final String contextPathVariableName ) { String ctxPath = getContextPath ( pageContext ) ; HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; request . setAttribute ( contextPathVariableName , ctxPath ) ; ServletContext servletContext = pageContext . getServletContext ( ) ; servletContext . setAttribute ( contextPathVariableName , ctxPath ) ; }

Stores context path in server context and request scope.

Stores context path in server context and request scope .


public static void storeContextPath(final ServletContext servletContext, final String contextPathVariableName) {
		String ctxPath = getContextPath(servletContext);

		servletContext.setAttribute(contextPathVariableName, ctxPath);
	}

public static void storeContextPath ( final ServletContext servletContext , final String contextPathVariableName ) { String ctxPath = getContextPath ( servletContext ) ; servletContext . setAttribute ( contextPathVariableName , ctxPath ) ; }

Stores context path in page context and request scope.

Stores context path in page context and request scope .


public boolean isGetParameter(final HttpServletRequest request, String name) {
		name = URLCoder.encodeQueryParam(name) + '=';
		String query = request.getQueryString();
		String[] nameValuePairs = StringUtil.splitc(query, '&');
		for (String nameValuePair : nameValuePairs) {
			if (nameValuePair.startsWith(name)) {
				return true;
			}
		}
		return false;
	}

public boolean isGetParameter ( final HttpServletRequest request , String name ) { name = URLCoder . encodeQueryParam ( name ) + ' ' ; String query = request . getQueryString ( ) ; String [ ] nameValuePairs = StringUtil . splitc ( query , ' ' ) ; for ( String nameValuePair : nameValuePairs ) { if ( nameValuePair . startsWith ( name ) ) { return true ; } } return false ; }

Checks if some parameter is in GET parameters.

Checks if some parameter is in GET parameters .


public static String[] prepareParameters(
		final String[] paramValues,
		final boolean treatEmptyParamsAsNull,
		final boolean ignoreEmptyRequestParams) {

		if (treatEmptyParamsAsNull || ignoreEmptyRequestParams) {
			int emptyCount = 0;
			int total = paramValues.length;
			for (int i = 0; i < paramValues.length; i++) {
				String paramValue = paramValues[i];
				if (paramValue == null) {
					emptyCount++;
					continue;
				}
				if (paramValue.length() == 0) {
					emptyCount++;
					if (treatEmptyParamsAsNull) {
						paramValue = null;
					}
				}
				paramValues[i] = paramValue;
			}
			if ((ignoreEmptyRequestParams) && (emptyCount == total)) {
				return null;
			}
		}
		return paramValues;
	}

public static String [ ] prepareParameters ( final String [ ] paramValues , final boolean treatEmptyParamsAsNull , final boolean ignoreEmptyRequestParams ) { if ( treatEmptyParamsAsNull || ignoreEmptyRequestParams ) { int emptyCount = 0 ; int total = paramValues . length ; for ( int i = 0 ; i < paramValues . length ; i ++ ) { String paramValue = paramValues [ i ] ; if ( paramValue == null ) { emptyCount ++ ; continue ; } if ( paramValue . length ( ) == 0 ) { emptyCount ++ ; if ( treatEmptyParamsAsNull ) { paramValue = null ; } } paramValues [ i ] = paramValue ; } if ( ( ignoreEmptyRequestParams ) && ( emptyCount == total ) ) { return null ; } } return paramValues ; }

Prepares parameters for further processing.
@param paramValues	string array of param values
@param treatEmptyParamsAsNull	empty parameters should be treated as null
@param ignoreEmptyRequestParams	if all parameters are empty, return null

Prepares parameters for further processing .


public static void copyParamsToAttributes(
		final HttpServletRequest servletRequest,
		final boolean treatEmptyParamsAsNull,
		final boolean ignoreEmptyRequestParams) {

		Enumeration paramNames = servletRequest.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if (servletRequest.getAttribute(paramName) != null) {
				continue;
			}

			String[] paramValues = servletRequest.getParameterValues(paramName);
			paramValues = prepareParameters(paramValues, treatEmptyParamsAsNull, ignoreEmptyRequestParams);
			if (paramValues == null) {
				continue;
			}
			servletRequest.setAttribute(paramName, paramValues.length == 1 ? paramValues[0] : paramValues);
		}

		// multipart
		if (!(servletRequest instanceof MultipartRequestWrapper)) {
			return;
		}
		MultipartRequestWrapper multipartRequest = (MultipartRequestWrapper) servletRequest;
		if (!multipartRequest.isMultipart()) {
			return;
		}
		paramNames = multipartRequest.getFileParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if (servletRequest.getAttribute(paramName) != null) {
				continue;
			}
			FileUpload[] paramValues = multipartRequest.getFiles(paramName);
			servletRequest.setAttribute(paramName, paramValues.length == 1 ? paramValues[0] : paramValues);
		}
	}

public
static
void
copyParamsToAttributes
(
final
HttpServletRequest
servletRequest
,
final
boolean
treatEmptyParamsAsNull
,
final
boolean
ignoreEmptyRequestParams
)
{
Enumeration
paramNames
=
servletRequest
.
getParameterNames
(
)
;
while
(
paramNames
.
hasMoreElements
(
)
)
{
String
paramName
=
(
String
)
paramNames
.
nextElement
(
)
;
if
(
servletRequest
.
getAttribute
(
paramName
)
!=
)
{
continue
;
}
String
[
]
paramValues
=
servletRequest
.
getParameterValues
(
paramName
)
;
paramValues
=
prepareParameters
(
paramValues
,
treatEmptyParamsAsNull
,
ignoreEmptyRequestParams
)
;
if
(
paramValues
==
)
{
continue
;
}
servletRequest
.
setAttribute
(
paramName
,
paramValues
.
length
==
1
paramValues
[
0
]
:
paramValues
)
;
}
// multipart
if
(
!
(
servletRequest
instanceof
MultipartRequestWrapper
)
)
{
return
;
}
MultipartRequestWrapper
multipartRequest
=
(
MultipartRequestWrapper
)
servletRequest
;
if
(
!
multipartRequest
.
isMultipart
(
)
)
{
return
;
}
paramNames
=
multipartRequest
.
getFileParameterNames
(
)
;
while
(
paramNames
.
hasMoreElements
(
)
)
{
String
paramName
=
(
String
)
paramNames
.
nextElement
(
)
;
if
(
servletRequest
.
getAttribute
(
paramName
)
!=
)
{
continue
;
}
FileUpload
[
]
paramValues
=
multipartRequest
.
getFiles
(
paramName
)
;
servletRequest
.
setAttribute
(
paramName
,
paramValues
.
length
==
1
paramValues
[
0
]
:
paramValues
)
;
}
}

Copies all request parameters to attributes.

Copies all request parameters to attributes .


public static void invokeBody(final JspFragment body) throws JspException {
		if (body == null) {
			return;
		}
		try {
			body.invoke(null);
		} catch (IOException ioex) {
			throw new JspException("Tag body failed", ioex);
		}
	}

public
static
void
invokeBody
(
final
JspFragment
body
)
throws
JspException
{
if
(
body
==
)
{
return
;
}
try
{
body
.
invoke
(
)
;
}
catch
(
IOException
ioex
)
{
throw
new
JspException
(
"Tag body failed"
,
ioex
)
;
}
}


public static char[] renderBody(final JspFragment body) throws JspException {
		FastCharArrayWriter writer = new FastCharArrayWriter();
		invokeBody(body, writer);
		return writer.toCharArray();
	}

public static char [ ] renderBody ( final JspFragment body ) throws JspException { FastCharArrayWriter writer = new FastCharArrayWriter ( ) ; invokeBody ( body , writer ) ; return writer . toCharArray ( ) ; }


public static String renderBodyToString(final JspFragment body) throws JspException {
		char[] result = renderBody(body);
		return new String(result);
	}

public static String renderBodyToString ( final JspFragment body ) throws JspException { char [ ] result = renderBody ( body ) ; return new String ( result ) ; }

Renders tag body to string.
@see #renderBody(javax.servlet.jsp.tagext.JspFragment)


public void invokeInitMethods(final InitMethodInvocationStrategy invocationStrategy) {
		for (final InitMethodPoint initMethod : beanDefinition.initMethodPoints()) {
			if (invocationStrategy != initMethod.invocationStrategy) {
				continue;
			}
			try {
				initMethod.method.invoke(bean);
			} catch (Exception ex) {
				throw new PetiteException("Invalid init method: " + initMethod, ex);
			}
		}
	}

public
void
invokeInitMethods
(
final
InitMethodInvocationStrategy
invocationStrategy
)
{
for
(
final
InitMethodPoint
initMethod
:
beanDefinition
.
initMethodPoints
(
)
)
{
if
(
invocationStrategy
!=
initMethod
.
invocationStrategy
)
{
continue
;
}
try
{
initMethod
.
method
.
invoke
(
bean
)
;
}
catch
(
Exception
ex
)
{
throw
new
PetiteException
(
"Invalid init method: "
+
initMethod
,
ex
)
;
}
}
}


public void callDestroyMethods() {
		for (final DestroyMethodPoint destroyMethodPoint : beanDefinition.destroyMethodPoints()) {
			try {
				destroyMethodPoint.method.invoke(bean);
			} catch (Exception ex) {
				throw new PetiteException("Invalid destroy method: " + destroyMethodPoint.method, ex);
			}
		}
	}

public
void
callDestroyMethods
(
)
{
for
(
final
DestroyMethodPoint
destroyMethodPoint
:
beanDefinition
.
destroyMethodPoints
(
)
)
{
try
{
destroyMethodPoint
.
method
.
invoke
(
bean
)
;
}
catch
(
Exception
ex
)
{
throw
new
PetiteException
(
"Invalid destroy method: "
+
destroyMethodPoint
.
method
,
ex
)
;
}
}
}

Calls destroy methods on given BeanData. Destroy methods are called
without any order.

Calls destroy methods on given BeanData . Destroy methods are called without any order .


public Object newBeanInstance() {
		if (beanDefinition.ctor == CtorInjectionPoint.EMPTY) {
			throw new PetiteException("No constructor (annotated, single or default) founded as injection point for: " + beanDefinition.type.getName());
		}

		int paramNo = beanDefinition.ctor.references.length;
		Object[] args = new Object[paramNo];

		// wiring
		if (beanDefinition.wiringMode != WiringMode.NONE) {
			for (int i = 0; i < paramNo; i++) {
				args[i] = pc.getBean(beanDefinition.ctor.references[i]);
				if (args[i] == null) {
					if ((beanDefinition.wiringMode == WiringMode.STRICT)) {
						throw new PetiteException(
							"Wiring constructor failed. References '" + beanDefinition.ctor.references[i] +
								"' not found for constructor: " + beanDefinition.ctor.constructor);
					}
				}
			}
		}

		// create instance
		final Object bean;
		try {
			bean = beanDefinition.ctor.constructor.newInstance(args);
		} catch (Exception ex) {
			throw new PetiteException("Failed to create new bean instance '" + beanDefinition.type.getName() + "' using constructor: " + beanDefinition.ctor.constructor, ex);
		}

		return bean;
	}


public void injectParams(final ParamManager paramManager, final boolean implicitParamInjection) {
		if (beanDefinition.name == null) {
			return;
		}

		if (implicitParamInjection) {
			// implicit
			final int len = beanDefinition.name.length() + 1;
			for (final String param : beanDefinition.params) {
				final Object value = paramManager.get(param);
				final String destination = param.substring(len);
				try {
					BeanUtil.declared.setProperty(bean, destination, value);
				} catch (Exception ex) {
					throw new PetiteException("Unable to set parameter: '" + param + "' to bean: " + beanDefinition.name, ex);
				}
			}
		}

		// explicit
		for (final ValueInjectionPoint pip : beanDefinition.values) {
			final String value = paramManager.parseKeyTemplate(pip.valueTemplate);

			try {
				BeanUtil.declared.setProperty(bean, pip.property, value);
			} catch (Exception ex) {
				throw new PetiteException("Unable to set value for: '" + pip.valueTemplate + "' to bean: " + beanDefinition.name, ex);
			}
		}
	}

public
void
injectParams
(
final
ParamManager
paramManager
,
final
boolean
implicitParamInjection
)
{
if
(
beanDefinition
.
name
==
)
{
return
;
}
if
(
implicitParamInjection
)
{
// implicit
final
int
len
=
beanDefinition
.
name
.
length
(
)
+
1
;
for
(
final
String
param
:
beanDefinition
.
params
)
{
final
Object
value
=
paramManager
.
get
(
param
)
;
final
String
destination
=
param
.
substring
(
len
)
;
try
{
BeanUtil
.
declared
.
setProperty
(
bean
,
destination
,
value
)
;
}
catch
(
Exception
ex
)
{
throw
new
PetiteException
(
"Unable to set parameter: '"
+
param
+
"' to bean: "
+
beanDefinition
.
name
,
ex
)
;
}
}
}
// explicit
for
(
final
ValueInjectionPoint
pip
:
beanDefinition
.
values
)
{
final
String
value
=
paramManager
.
parseKeyTemplate
(
pip
.
valueTemplate
)
;
try
{
BeanUtil
.
declared
.
setProperty
(
bean
,
pip
.
property
,
value
)
;
}
catch
(
Exception
ex
)
{
throw
new
PetiteException
(
"Unable to set value for: '"
+
pip
.
valueTemplate
+
"' to bean: "
+
beanDefinition
.
name
,
ex
)
;
}
}
}


@SuppressWarnings({"UnusedDeclaration"})
	public String rewrite(final HttpServletRequest servletRequest, final String actionPath, final String httpMethod) {
		return actionPath;
	}

@ SuppressWarnings ( { "UnusedDeclaration" } ) public String rewrite ( final HttpServletRequest servletRequest , final String actionPath , final String httpMethod ) { return actionPath ; }


public void addHeader(final String name, final String value) {
		List<String> valuesList = super.getAll(name);
		if (valuesList.isEmpty()) {
			super.add(name, value);
			return;
		}
		super.remove(name);
		valuesList.add(value);
		super.addAll(name, valuesList);
	}

public void addHeader ( final String name , final String value ) { List < String > valuesList = super . getAll ( name ) ; if ( valuesList . isEmpty ( ) ) { super . add ( name , value ) ; return ; } super . remove ( name ) ; valuesList . add ( value ) ; super . addAll ( name , valuesList ) ; }

Adds new header value. If existing value exist, it will be removed
so the store the new key value.

Adds new header value . If existing value exist it will be removed so the store the new key value .


protected void put(final String profile, final Map<String, PropsEntry> map, final String key, final String value, final boolean append) {
		String realValue = value;
		if (append || appendDuplicateProps) {
			PropsEntry pv = map.get(key);
			if (pv != null) {
				realValue = pv.value + APPEND_SEPARATOR + realValue;
			}
		}
		PropsEntry propsEntry = new PropsEntry(key, realValue, profile, this);

		// update position pointers
		if (first == null) {
			first = propsEntry;
		} else {
			last.next = propsEntry;
		}
		last = propsEntry;

		// add to the map
		map.put(key, propsEntry);
	}

protected
void
put
(
final
String
profile
,
final
Map
<
String
,
PropsEntry
>
map
,
final
String
key
,
final
String
value
,
final
boolean
append
)
{
String
realValue
=
value
;
if
(
append
||
appendDuplicateProps
)
{
PropsEntry
pv
=
map
.
get
(
key
)
;
if
(
pv
!=
)
{
realValue
=
pv
.
value
+
APPEND_SEPARATOR
+
realValue
;
}
}
PropsEntry
propsEntry
=
new
PropsEntry
(
key
,
realValue
,
profile
,
this
)
;
// update position pointers
if
(
first
==
)
{
first
=
propsEntry
;
}
else
{
last
.
next
=
propsEntry
;
}
last
=
propsEntry
;
// add to the map
map
.
put
(
key
,
propsEntry
)
;
}

Puts key-value pair into the map, with respect of appending duplicate properties

Puts key - value pair into the map with respect of appending duplicate properties


public void putBaseProperty(final String key, final String value, final boolean append) {
		put(null, baseProperties, key, value, append);
	}

public void putBaseProperty ( final String key , final String value , final boolean append ) { put ( null , baseProperties , key , value , append ) ; }


public void putProfileProperty(final String key, final String value, final String profile, final boolean append) {
		Map<String, PropsEntry> map = profileProperties.computeIfAbsent(profile, k -> new HashMap<>());
		put(profile, map, key, value, append);
	}

public void putProfileProperty ( final String key , final String value , final String profile , final boolean append ) { Map < String , PropsEntry > map = profileProperties . computeIfAbsent ( profile , k -> new HashMap <> ( ) ) ; put ( profile , map , key , value , append ) ; }


public PropsEntry getProfileProperty(final String profile, final String key) {
		final Map<String, PropsEntry> profileMap = profileProperties.get(profile);
		if (profileMap == null) {
			return null;
		}
		return profileMap.get(key);
	}

public PropsEntry getProfileProperty ( final String profile , final String key ) { final Map < String , PropsEntry > profileMap = profileProperties . get ( profile ) ; if ( profileMap == null ) { return null ; } return profileMap . get ( key ) ; }


public String resolveMacros(String value, final String... profiles) {
		// create string template parser that will be used internally
		StringTemplateParser stringTemplateParser = new StringTemplateParser();
		stringTemplateParser.setResolveEscapes(false);

		if (!ignoreMissingMacros) {
			stringTemplateParser.setReplaceMissingKey(false);
		} else {
			stringTemplateParser.setReplaceMissingKey(true);
			stringTemplateParser.setMissingKeyReplacement(StringPool.EMPTY);
		}

		final Function<String, String> macroResolver = macroName -> {
			String[] lookupProfiles = profiles;

			int leftIndex = macroName.indexOf('<');
			if (leftIndex != -1) {
				int rightIndex = macroName.indexOf('>');

				String profiles1 = macroName.substring(leftIndex + 1, rightIndex);
				macroName = macroName.substring(0, leftIndex).concat(macroName.substring(rightIndex + 1));

				lookupProfiles = StringUtil.splitc(profiles1, ',');

				StringUtil.trimAll(lookupProfiles);
			}

			return lookupValue(macroName, lookupProfiles);
		};

		// start parsing
		int loopCount = 0;

		while (loopCount++ < MAX_INNER_MACROS) {
			final String newValue = stringTemplateParser.parse(value, macroResolver);

			if (newValue.equals(value)) {
				break;
			}

			if (skipEmptyProps) {
				if (newValue.length() == 0) {
					return null;
				}
			}

			value = newValue;
		}

		return value;
	}

Resolves all macros in this props set. Called on property lookup.

Resolves all macros in this props set . Called on property lookup .


public Map extract(Map target, final String[] profiles, final String[] wildcardPatterns, String prefix) {
		if (target == null) {
			target = new HashMap();
		}

		// make sure prefix ends with a dot
		if (prefix != null) {
			if (!StringUtil.endsWithChar(prefix, '.')) {
				prefix += StringPool.DOT;
			}
		}

		if (profiles != null) {
			for (String profile : profiles) {
				while (true) {
					final Map<String, PropsEntry> map = this.profileProperties.get(profile);
					if (map != null) {
						extractMap(target, map, profiles, wildcardPatterns, prefix);
					}

					final int ndx = profile.lastIndexOf('.');
					if (ndx == -1) {
						break;
					}
					profile = profile.substring(0, ndx);
				}
			}
		}

		extractMap(target, this.baseProperties, profiles, wildcardPatterns, prefix);

		return target;
	}

public
Map
extract
(
Map
target
,
final
String
[
]
profiles
,
final
String
[
]
wildcardPatterns
,
String
prefix
)
{
if
(
target
==
)
{
target
=
new
HashMap
(
)
;
}
// make sure prefix ends with a dot
if
(
prefix
!=
)
{
if
(
!
StringUtil
.
endsWithChar
(
prefix
,
'
'
)
)
{
prefix
+=
StringPool
.
DOT
;
}
}
if
(
profiles
!=
)
{
for
(
String
profile
:
profiles
)
{
while
(
true
)
{
final
Map
<
String
,
PropsEntry
>
map
=
this
.
profileProperties
.
get
(
profile
)
;
if
(
map
!=
)
{
extractMap
(
target
,
map
,
profiles
,
wildcardPatterns
,
prefix
)
;
}
final
int
ndx
=
profile
.
lastIndexOf
(
'
'
)
;
if
(
ndx
==
1
)
{
break
;
}
profile
=
profile
.
substring
(
0
,
ndx
)
;
}
}
}
extractMap
(
target
,
this
.
baseProperties
,
profiles
,
wildcardPatterns
,
prefix
)
;
return
target
;
}

Extracts props to target map. This is all-in-one method, that does many things at once.

Extracts props to target map . This is all - in - one method that does many things at once .


private static int streamtoword(byte[] data, int[] offp) {
		int i;
		int word = 0;
		int off = offp[0];

		for (i = 0; i < 4; i++) {
			word = (word << 8) | (data[off] & 0xff);
			off = (off + 1) % data.length;
		}

		offp[0] = off;
		return word;
	}

private static int streamtoword ( byte [ ] data , int [ ] offp ) { int i ; int word = 0 ; int off = offp [ 0 ] ; for ( i = 0 ; i < 4 ; i ++ ) { word = ( word << 8 ) | ( data [ off ] & 0xff ) ; off = ( off + 1 ) % data . length ; } offp [ 0 ] = off ; return word ; }

Cycically extract a word of key material.

@param data the string to extract the data from
@param offp a "pointer" (as a one-entry array) to the
current offset into data
@return the next word of material from data

Cycically extract a word of key material .