protected final void merge(final VelocityContext context, final String artifactName, final String templateName, final String filename)
            throws GenerateException {

        final GeneratedFile genFile = getTargetFile(artifactName, filename, templateName);
        if (genFile.isSkip()) {
            LOG.debug("Omitted already existing file: {} [{}]", genFile, templateName);
        } else {
            LOG.debug("Start merging velocity template: {} [{}]", genFile, templateName);
            // Merge content
            try {
                final Writer writer = new FileWriter(genFile.getTmpFile());
                try {
                    final Template template = ve.getTemplate(templateName);
                    template.merge(context, writer);
                } finally {
                    writer.close();
                }
                genFile.persist();

            } catch (final IOException ex) {
                throw new GenerateException("Error merging template '" + templateName + "' to '" + filename + "'!", ex);
            }
        }

    }

Merges the template and context into a file. If the directory of the file does not exists, the full directory path to it will be
created.

@param context
Context to use.
@param artifactName
Unique name of the generated artifact.
@param templateName
Name of the template to use.
@param filename
Filename relative to the target directory.

@throws GenerateException
Error merging the template

Merges the template and context into a file . If the directory of the file does not exists the full directory path to it will be created .


public final File getModelDir() {
        if ((modelDir == null) && (modelPath != null)) {
            modelDir = Utils4J.getCanonicalFile(new File(modelPath));
        }
        return modelDir;
    }

public final File getModelDir ( ) { if ( ( modelDir == null ) && ( modelPath != null ) ) { modelDir = Utils4J . getCanonicalFile ( new File ( modelPath ) ) ; } return modelDir ; }

Returns the model directory.

@return Model directory or NULL.


public final File getTemplateDir() {
        if ((templateDir == null) && (templatePath != null)) {
            try {
                templateDir = new File(templatePath).getCanonicalFile();
            } catch (final IOException ex) {
                throw new RuntimeException("Couldn't determine canonical template file: " + templatePath, ex);
            }
        }
        return templateDir;
    }

Returns the template directory.

@return Template directory or NULL.


@Override
	public void write(HttpServletResponse httpResponse, Object value) throws IOException {
		final Document document = (Document) value;
		document.serialize(new OutputStreamWriter(httpResponse.getOutputStream(), "UTF-8"));
	}

@ Override public void write ( HttpServletResponse httpResponse , Object value ) throws IOException { final Document document = ( Document ) value ; document . serialize ( new OutputStreamWriter ( httpResponse . getOutputStream ( ) , "UTF-8" ) ) ; }

Serialize XML document to output stream of given HTTP response.

@param httpResponse HTTP response,
@param value value object is a XML document.
@throws IOException if output stream write operation fails.

Serialize XML document to output stream of given HTTP response .


@Validate
    public  void start() {
        QApplication.invokeLater(new Runnable() {
            public void run() {
                configureApplication();
                m_logger.info("Creating a web ui...");
                synchronized (WebViewFactory.this) {
                    m_browser = new WebWindow(m_url, WebViewFactory.this);

                    configureWindow(m_browser);
                    m_browser.show();
                }
                m_logger.info("Web UI created.");
            }
        });
    }

@
Validate
public
void
start
(
)
{
QApplication
.
invokeLater
(
new
Runnable
(
)
{
public
void
run
(
)
{
configureApplication
(
)
;
m_logger
.
info
(
"Creating a web ui..."
)
;
synchronized
(
WebViewFactory
.
this
)
{
m_browser
=
new
WebWindow
(
m_url
,
WebViewFactory
.
this
)
;
configureWindow
(
m_browser
)
;
m_browser
.
show
(
)
;
}
m_logger
.
info
(
"Web UI created."
)
;
}
}
)
;
}

Starts the browser and loads the
set url in the web view.

Starts the browser and loads the set url in the web view .


private void configureWindow(WebWindow web) {

        if (m_fullscreen) {
            // We need to store the previous width and height values
            m_width = web.width();
            m_height = web.height();
            web.showFullScreen();
        } else {
            web.showNormal();
            if (! m_resizable) {
               web.setFixedSize(new QSize(m_width, m_height));
            } else {
               web.setBaseSize(new QSize(m_width, m_height));
            }
            web.resize(m_width, m_height);
        }

        if (! m_bar) {
            web.menuBar().setVisible(false);
        } else {
            web.menuBar().setVisible(true);
            if (m_icon != null) {
                QIcon icon = new QIcon(m_icon);
                web.setWindowIcon(icon);
            }
            web.setWindowTitle(m_appName);
        }

        if (! m_contextMenu) {
            web.setContextMenuPolicy(ContextMenuPolicy.PreventContextMenu);
        } else {
            web.setContextMenuPolicy(ContextMenuPolicy.DefaultContextMenu);
        }
    }

Configures the browser window.
@param web the browser window


public void print(QWebView view) {
        if (m_print) {
            QPrinter printer = new QPrinter();
            QPrintDialog printDialog = new QPrintDialog(printer, view);
            if (printDialog.exec() == QDialog.DialogCode.Accepted.value()) {
                // print ...
                view.print(printer);
            }
        } else {
            m_logger.warn("Print disabled");
        }
    }

public
void
print
(
QWebView
view
)
{
if
(
m_print
)
{
QPrinter
printer
=
new
QPrinter
(
)
;
QPrintDialog
printDialog
=
new
QPrintDialog
(
printer
,
view
)
;
if
(
printDialog
.
exec
(
)
==
QDialog
.
DialogCode
.
Accepted
.
value
(
)
)
{
// print ...
view
.
print
(
printer
)
;
}
}
else
{
m_logger
.
warn
(
"Print disabled"
)
;
}
}

Print callback.
Checks if the print feature is enabled. If so, launch the system
print job.
@param view the view to print

Print callback . Checks if the print feature is enabled . If so launch the system print job .


public static void write(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.write(b, 0, n);
        }
        in.close();
        out.close();
    }

public static void write ( InputStream in , OutputStream out ) throws IOException { byte [ ] b = new byte [ 4096 ] ; for ( int n ; ( n = in . read ( b ) ) != - 1 ; ) { out . write ( b , 0 , n ) ; } in . close ( ) ; out . close ( ) ; }

Utility method to copy a stream to another stream.
@param in the stream to copy
@param out the destination
@throws IOException the stream cannot be copied

Utility method to copy a stream to another stream .


@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		T instance = appFactory.getInstance(interfaceClass);
		return method.invoke(instance, args);
	}

@ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { T instance = appFactory . getInstance ( interfaceClass ) ; return method . invoke ( instance , args ) ; }

Retrieve managed instance from application factory and invoke given method on that instance.

@param proxy Java Proxy instance using this handler, unused by current implementation,
@param method reflexive method invoked by proxy instance caller,
@param args method invocation arguments.
@return value returned by method execution, possible null.
@throws Throwable any exception generated by method execution is bubbled up.

Retrieve managed instance from application factory and invoke given method on that instance .


public void attach(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		// takes care to not override request URL, locale and request path values if set by request pre-processor
		if (requestURL == null) {
			requestURL = httpRequest.getRequestURI();
		}
		if (locale == null) {
			locale = httpRequest.getLocale();
		}
		if (requestPath == null) {
			// request URI and context path cannot ever be null
			requestPath = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
		}

		this.httpRequest = httpRequest;
		this.httpResponse = httpResponse;
		this.attached = true;
	}

Attach this instance to HTTP servlet request. Load this instance state from HTTP servlet request and mark it as attached.

@param httpRequest current HTTP request object,
@param httpResponse HTTP response object associated to current request.

Attach this instance to HTTP servlet request . Load this instance state from HTTP servlet request and mark it as attached .


public void detach() {
		attached = false;
		locale = null;
		securityDomain = null;
		cookies = null;
		requestPath = null;
		requestURL = null;
	}

public void detach ( ) { attached = false ; locale = null ; securityDomain = null ; cookies = null ; requestPath = null ; requestURL = null ; }

Detach request context instance from HTTP servlet request. Invoking getters on this instance after detaching is
considered a bug.

Detach request context instance from HTTP servlet request . Invoking getters on this instance after detaching is considered a bug .


public Cookies getCookies() {
		assertAttached();
		if (cookies == null) {
			cookies = new Cookies(httpRequest, httpResponse);
		}
		return cookies;
	}

public Cookies getCookies ( ) { assertAttached ( ) ; if ( cookies == null ) { cookies = new Cookies ( httpRequest , httpResponse ) ; } return cookies ; }

Get request cookies.

@return request cookies.
@throws BugError if attempt to use this getter on instance not attached to a HTTP servlet request.


public void dump() {
		if (!attached) {
			return;
		}
		StringBuilder message = new StringBuilder();
		message.append("Request context |");
		message.append(httpRequest.getRequestURI());
		message.append("|:");

		message.append(System.lineSeparator());
		message.append("\t- remote-address: ");
		message.append(httpRequest.getRemoteHost());

		message.append(System.lineSeparator());
		message.append("\t- method: ");
		message.append(httpRequest.getMethod());

		message.append(System.lineSeparator());
		message.append("\t- query-string: ");
		if (httpRequest.getQueryString() != null) {
			message.append(httpRequest.getQueryString());
		}

		Enumeration<String> headerNames = httpRequest.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			message.append(System.lineSeparator());
			String headerName = headerNames.nextElement();
			message.append("\t- ");
			message.append(headerName);
			message.append(": ");
			message.append(httpRequest.getHeader(headerName));
		}
		log.error(message.toString());
	}

public
void
dump
(
)
{
if
(
!
attached
)
{
return
;
}
StringBuilder
message
=
new
StringBuilder
(
)
;
message
.
append
(
"Request context |"
)
;
message
.
append
(
httpRequest
.
getRequestURI
(
)
)
;
message
.
append
(
"|:"
)
;
message
.
append
(
System
.
lineSeparator
(
)
)
;
message
.
append
(
"\t- remote-address: "
)
;
message
.
append
(
httpRequest
.
getRemoteHost
(
)
)
;
message
.
append
(
System
.
lineSeparator
(
)
)
;
message
.
append
(
"\t- method: "
)
;
message
.
append
(
httpRequest
.
getMethod
(
)
)
;
message
.
append
(
System
.
lineSeparator
(
)
)
;
message
.
append
(
"\t- query-string: "
)
;
if
(
httpRequest
.
getQueryString
(
)
!=
)
{
message
.
append
(
httpRequest
.
getQueryString
(
)
)
;
}
Enumeration
<
String
>
headerNames
=
httpRequest
.
getHeaderNames
(
)
;
while
(
headerNames
.
hasMoreElements
(
)
)
{
message
.
append
(
System
.
lineSeparator
(
)
)
;
String
headerName
=
headerNames
.
nextElement
(
)
;
message
.
append
(
"\t- "
)
;
message
.
append
(
headerName
)
;
message
.
append
(
": "
)
;
message
.
append
(
httpRequest
.
getHeader
(
headerName
)
)
;
}
log
.
error
(
message
.
toString
(
)
)
;
}

Dump this request context state to error logger. If this instance is not attached this method is NOP.

Dump this request context state to error logger . If this instance is not attached this method is NOP .


private static List<InvocationMeter> getMeters() {
		List<InvocationMeter> invocationMeters = new ArrayList<InvocationMeter>();
		ContainerSPI container = (ContainerSPI) Factory.getAppFactory();
		for (ManagedMethodSPI managedMethod : container.getManagedMethods()) {
			invocationMeters.add(((ManagedMethod) managedMethod).getMeter());
		}
		return invocationMeters;
	}

private static List < InvocationMeter > getMeters ( ) { List < InvocationMeter > invocationMeters = new ArrayList < InvocationMeter > ( ) ; ContainerSPI container = ( ContainerSPI ) Factory . getAppFactory ( ) ; for ( ManagedMethodSPI managedMethod : container . getManagedMethods ( ) ) { invocationMeters . add ( ( ( ManagedMethod ) managedMethod ) . getMeter ( ) ) ; } return invocationMeters ; }

Collect invocation meters from application managed classes.

@return application invocation meters.

Collect invocation meters from application managed classes .


protected void config(EventStreamConfig config) {
		if (config.hasSecretKey()) {
			secretKey = config.getSecretKey();
		}
		if (config.hasKeepAlivePeriod()) {
			keepAlivePeriod = config.getKeepAlivePeriod();
		}
		parameters = config.getParameters();
	}

protected void config ( EventStreamConfig config ) { if ( config . hasSecretKey ( ) ) { secretKey = config . getSecretKey ( ) ; } if ( config . hasKeepAlivePeriod ( ) ) { keepAlivePeriod = config . getKeepAlivePeriod ( ) ; } parameters = config . getParameters ( ) ; }

Configure events stream instance from configuration object.

@param config event stream configuration object.

Configure events stream instance from configuration object .


protected void setRemoteHost(String remoteHost) {
		if (string == null) {
			string = Strings.concat('#', STREAM_ID++, ':', remoteHost);
		}
	}

protected void setRemoteHost ( String remoteHost ) { if ( string == null ) { string = Strings . concat ( ' ' , STREAM_ID ++ , ' ' , remoteHost ) ; } }

Set the host address for client connected to this event stream.

@param remoteHost client remote host address.

Set the host address for client connected to this event stream .


protected <T> T getParameter(String name, Class<T> type) {
		if (parameters == null) {
			throw new BugError("Event stream |%s| parameters not configured.", this);
		}
		String value = parameters.get(name);
		if (value == null) {
			throw new BugError("Missing event stream parameter |%s| of expected type |%s|.", name, type);
		}
		return ConverterRegistry.getConverter().asObject(value, type);
	}

Get named parameter throwing exception if not found.

@param name requested parameter name,
@param type desired parameter type.
@param <T> parameter type.
@return named parameter instance.
@throws BugError if named parameter does not exist.

Get named parameter throwing exception if not found .


public String removePrefix(final String path, final String prefix) {
		String pathWithoutPrefix = path;

		if (pathWithoutPrefix.startsWith(prefix)) {
			pathWithoutPrefix = pathWithoutPrefix.substring(prefix.length());

			while (pathWithoutPrefix.startsWith("/") || pathWithoutPrefix.startsWith("\\")) {
				pathWithoutPrefix = pathWithoutPrefix.substring(1);
			}
		}

		return pathWithoutPrefix;
	}

public String removePrefix ( final String path , final String prefix ) { String pathWithoutPrefix = path ; if ( pathWithoutPrefix . startsWith ( prefix ) ) { pathWithoutPrefix = pathWithoutPrefix . substring ( prefix . length ( ) ) ; while ( pathWithoutPrefix . startsWith ( "/" ) || pathWithoutPrefix . startsWith ( "\\" ) ) { pathWithoutPrefix = pathWithoutPrefix . substring ( 1 ) ; } } return pathWithoutPrefix ; }

Removes a prefix from a path. If the path does not start with the prefix,
the unchanged path is returned.

@param path   the full path
@param prefix prefix to remove
@return {@code path} without prefix, or {@code path} itself
unless it doesn't start with the prefix.

Removes a prefix from a path . If the path does not start with the prefix the unchanged path is returned .


public File getCommonDir(final File dir1, final File dir2) throws IOException {
		List<File> parts1 = getParentDirs(dir1);
		List<File> parts2 = getParentDirs(dir2);
		File matched = null;

		final int maxCommonSize = Math.min(parts1.size(), parts2.size());
		for (int i = 0; i < maxCommonSize; ++i) {
			if (parts1.get(i).equals(parts2.get(i))) {
				matched = parts1.get(i);
			} else {
				break;
			}
		}

		return matched;
	}

public File getCommonDir ( final File dir1 , final File dir2 ) throws IOException { List < File > parts1 = getParentDirs ( dir1 ) ; List < File > parts2 = getParentDirs ( dir2 ) ; File matched = null ; final int maxCommonSize = Math . min ( parts1 . size ( ) , parts2 . size ( ) ) ; for ( int i = 0 ; i < maxCommonSize ; ++ i ) { if ( parts1 . get ( i ) . equals ( parts2 . get ( i ) ) ) { matched = parts1 . get ( i ) ; } else { break ; } } return matched ; }

Gets the longest common parent directory path of two paths.

@param dir1 first path
@param dir2 second path
@return longest common path in {@code dir1} and {@code dir2}
@throws java.io.IOException Exception which is thrown if paths cannot be normalized

Gets the longest common parent directory path of two paths .


public String abs2rel(final String basePath, final String absPath) {
		if (!isAbsolutePath(absPath)) {
			return absPath;
		}

		if (isWindowsDrive(absPath) && isWindowsDrive(basePath) && absPath.charAt(0) != basePath.charAt(0)) {
			return absPath;
		}

		StringBuilder result = new StringBuilder();
		String[] baseParts = getParts(basePath);
		String[] absParts = getParts(absPath);

		// extract common prefix
		int start = 0;
		for (int i = 0; i < Math.min(baseParts.length, absParts.length); ++i) {
			if (baseParts[i].equals(absParts[i])) {
				start = i + 1;
			}
		}

		for (int i = start; i < baseParts.length; ++i) {
			if (result.length() > 0) {
				result.append(File.separator);
			}
			result.append("..");
		}

		for (int i = start; i < absParts.length; ++i) {
			if (result.length() > 0) {
				result.append(File.separator);
			}
			result.append(absParts[i]);
		}

		return result.toString();
	}

public
String
abs2rel
(
final
String
basePath
,
final
String
absPath
)
{
if
(
!
isAbsolutePath
(
absPath
)
)
{
return
absPath
;
}
if
(
isWindowsDrive
(
absPath
)
&&
isWindowsDrive
(
basePath
)
&&
absPath
.
charAt
(
0
)
!=
basePath
.
charAt
(
0
)
)
{
return
absPath
;
}
StringBuilder
result
=
new
StringBuilder
(
)
;
String
[
]
baseParts
=
getParts
(
basePath
)
;
String
[
]
absParts
=
getParts
(
absPath
)
;
// extract common prefix
int
start
=
0
;
for
(
int
i
=
0
;
i
<
Math
.
min
(
baseParts
.
length
,
absParts
.
length
)
;
++
i
)
{
if
(
baseParts
[
i
]
.
equals
(
absParts
[
i
]
)
)
{
start
=
i
+
1
;
}
}
for
(
int
i
=
start
;
i
<
baseParts
.
length
;
++
i
)
{
if
(
result
.
length
(
)
>
0
)
{
result
.
append
(
File
.
separator
)
;
}
result
.
append
(
".."
)
;
}
for
(
int
i
=
start
;
i
<
absParts
.
length
;
++
i
)
{
if
(
result
.
length
(
)
>
0
)
{
result
.
append
(
File
.
separator
)
;
}
result
.
append
(
absParts
[
i
]
)
;
}
return
result
.
toString
(
)
;
}

Converts an absolute path into a relative one.

@param basePath path to start from
@param absPath  path to convert
@return {@code absPath} as a relative path starting from {@code basePath}

Converts an absolute path into a relative one .


public File rel2abs(final String basePath, final String relPath) {
		String[] baseParts = getParts(basePath);
		String[] relParts = getParts(relPath);

		if (isAbsolutePath(relPath)) {
			return new File(relPath);
		}

		List<String> parts = new ArrayList<>();
		for (int i = 0; i < baseParts.length; ++i) {
			if (i > 0 || !isWindowsDrive(basePath)) {
				parts.add(baseParts[i]);
			}
		}

		for (String part : relParts) {
			if (part.equals("..") && parts.size() > 0) {
				parts.remove(parts.size() - 1);
			} else if (!part.equals(".") && !part.equals("..")) {
				parts.add(part);
			}
		}

		StringBuilder result = new StringBuilder();
		if (isWindowsDrive(basePath)) {
			result.append(baseParts[0]);
		}

		for (String part : parts) {
			result.append(File.separator);
			result.append(part);
		}

		return new File(result.toString());
	}

public File rel2abs ( final String basePath , final String relPath ) { String [ ] baseParts = getParts ( basePath ) ; String [ ] relParts = getParts ( relPath ) ; if ( isAbsolutePath ( relPath ) ) { return new File ( relPath ) ; } List < String > parts = new ArrayList <> ( ) ; for ( int i = 0 ; i < baseParts . length ; ++ i ) { if ( i > 0 || ! isWindowsDrive ( basePath ) ) { parts . add ( baseParts [ i ] ) ; } } for ( String part : relParts ) { if ( part . equals ( ".." ) && parts . size ( ) > 0 ) { parts . remove ( parts . size ( ) - 1 ) ; } else if ( ! part . equals ( "." ) && ! part . equals ( ".." ) ) { parts . add ( part ) ; } } StringBuilder result = new StringBuilder ( ) ; if ( isWindowsDrive ( basePath ) ) { result . append ( baseParts [ 0 ] ) ; } for ( String part : parts ) { result . append ( File . separator ) ; result . append ( part ) ; } return new File ( result . toString ( ) ) ; }

Converts an relative path into an absolute one.

@param basePath path to start from
@param relPath  path to convert
@return {@code relPath} as a absolute path

Converts an relative path into an absolute one .


public int dirDepth(final File path) {
		final String stringPath = path.getPath();
		return stringPath.length() - stringPath.replaceAll("[/\\\\]", "").length();
	}

public int dirDepth ( final File path ) { final String stringPath = path . getPath ( ) ; return stringPath . length ( ) - stringPath . replaceAll ( "[/\\\\]" , "" ) . length ( ) ; }

Counts the number of directories in a given path.

@param path the path to analyze
@return number of directories

Counts the number of directories in a given path .


protected static void dumpError(RequestContext context, Throwable throwable) {
		log.dump("Error on HTTP request:", throwable);
		context.dump();
	}

protected
static
void
dumpError
(
RequestContext
context
,
Throwable
throwable
)
{
log
.
dump
(
"Error on HTTP request:"
,
throwable
)
;
context
.
dump
(
)
;
}

Dump throwable stack trace and request context to application logger.

@param context request context,
@param throwable throwable to dump stack trace for.

Dump throwable stack trace and request context to application logger .


protected static void sendJsonObject(RequestContext context, Object object, int statusCode) throws IOException {
		final HttpServletResponse httpResponse = context.getResponse();
		if (httpResponse.isCommitted()) {
			log.fatal("Abort HTTP transaction. Attempt to send JSON object after reponse commited.");
			return;
		}
		log.trace("Send response object |%s|.", object.toString());

		Json json = Classes.loadService(Json.class);
		String buffer = json.stringify(object);
		byte[] bytes = buffer.getBytes("UTF-8");

		httpResponse.setStatus(statusCode);
		httpResponse.setContentType(ContentType.APPLICATION_JSON.getValue());
		httpResponse.setContentLength(bytes.length);
		httpResponse.setHeader("Content-Language", context.getLocale().toLanguageTag());

		httpResponse.getOutputStream().write(bytes);
		httpResponse.getOutputStream().flush();
	}

Send object back to client encoded JSON with given HTTP status code. Take care to set content type, length and language.
Content language is extracted from request context locale.

@param context running request context,
@param object object to serialize back to client,
@param statusCode response status code.
@throws IOException if serialization process fails.

Send object back to client encoded JSON with given HTTP status code . Take care to set content type length and language . Content language is extracted from request context locale .


public final void addParamTemplate(final ParameterizedTemplateModel paramTemplate) {
        if (paramTemplates == null) {
            paramTemplates = new ArrayList<ParameterizedTemplateModel>();
        }
        paramTemplates.add(paramTemplate);
    }

public final void addParamTemplate ( final ParameterizedTemplateModel paramTemplate ) { if ( paramTemplates == null ) { paramTemplates = new ArrayList < ParameterizedTemplateModel > ( ) ; } paramTemplates . add ( paramTemplate ) ; }

Adds another template to the list. If the list does not exist,it will be created.

@param paramTemplate
Template to add - Cannot be NULL.

Adds another template to the list . If the list does not exist it will be created .


public final void addParamTemplates(final List<ParameterizedTemplateModel> list) {
        if (list != null) {
            for (final ParameterizedTemplateModel template : list) {
                addParamTemplate(template);
            }
        }
    }

public final void addParamTemplates ( final List < ParameterizedTemplateModel > list ) { if ( list != null ) { for ( final ParameterizedTemplateModel template : list ) { addParamTemplate ( template ) ; } } }

Adds all templates to the list. If the list does not exist,it will be created.

@param list
LIst of templates to add - Cannot be NULL.

Adds all templates to the list . If the list does not exist it will be created .


public final void init(final SrcGen4JContext context, final Map<String, String> vars) {
        if (paramTemplates != null) {
            for (final ParameterizedTemplateModel paramTemplate : paramTemplates) {
                paramTemplate.init(context, vars);
            }
        }
    }

public final void init ( final SrcGen4JContext context , final Map < String , String > vars ) { if ( paramTemplates != null ) { for ( final ParameterizedTemplateModel paramTemplate : paramTemplates ) { paramTemplate . init ( context , vars ) ; } } }

Initalizes the object.

@param context
Current context.
@param vars
Variables to use.


public final List<ParameterizedTemplateModel> findReferencesTo(final File templateDir, final File templateFile) {

        final List<ParameterizedTemplateModel> result = new ArrayList<ParameterizedTemplateModel>();
        if ((paramTemplates != null) && Utils4J.fileInsideDirectory(templateDir, templateFile)) {
            for (final ParameterizedTemplateModel paramTemplate : paramTemplates) {
                if (paramTemplate.hasReferenceTo(templateDir, templateFile)) {
                    result.add(paramTemplate);
                }
            }
        }
        return result;
    }

public final List < ParameterizedTemplateModel > findReferencesTo ( final File templateDir , final File templateFile ) { final List < ParameterizedTemplateModel > result = new ArrayList < ParameterizedTemplateModel > ( ) ; if ( ( paramTemplates != null ) && Utils4J . fileInsideDirectory ( templateDir , templateFile ) ) { for ( final ParameterizedTemplateModel paramTemplate : paramTemplates ) { if ( paramTemplate . hasReferenceTo ( templateDir , templateFile ) ) { result . add ( paramTemplate ) ; } } } return result ; }

Returns a list that contains all models that reference the given template.

@param templateDir
Directory where all template files are located - Cannot be NULL.
@param templateFile
File to find references to - Cannot be NULL.

@return List - Never NULL, but may be empty.

Returns a list that contains all models that reference the given template .


public void setSaveEnabled(boolean val) {
        saveButton.setVisible(val);
        setReadOnly(!val);
        entityForm.setReadOnly(!val);
    }

public void setSaveEnabled ( boolean val ) { saveButton . setVisible ( val ) ; setReadOnly ( ! val ) ; entityForm . setReadOnly ( ! val ) ; }

Controls whether a save button is shown and fields are editable.

@param val Turns the feature on or off.

Controls whether a save button is shown and fields are editable .


protected void delete() {
        String question = "Are you sure you want to delete " + getCaption() + "?";
        ConfirmDialog.show(getUI(), question, (ConfirmDialog cd) -> {
            if (cd.isConfirmed()) {
                try {
                    onDelete();
                    close();
                } catch (IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex) {
                    onError(ex);
                } catch (RuntimeException ex) {
                    // Must explicitly send unhandled exceptions to error handler.
                    // Would otherwise get swallowed silently within callback handler.
                    getUI().getErrorHandler().error(new com.vaadin.server.ErrorEvent(ex));
                }
            }
        });
    }


protected void onDelete()
            throws IOException, IllegalArgumentException, IllegalAccessException, FileNotFoundException, IllegalStateException {
        endpoint.delete();
        eventBus.post(new ElementDeletedEvent<>(endpoint));
    }

protected void onDelete ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { endpoint . delete ( ) ; eventBus . post ( new ElementDeletedEvent <> ( endpoint ) ) ; }

Handler for deleting the element.

@throws IOException Network communication failed.
@throws IllegalArgumentException {@link HttpStatus#SC_BAD_REQUEST}
@throws IllegalAccessException {@link HttpStatus#SC_UNAUTHORIZED} or
{@link HttpStatus#SC_FORBIDDEN}
@throws FileNotFoundException {@link HttpStatus#SC_NOT_FOUND} or
{@link HttpStatus#SC_GONE}
@throws IllegalStateException {@link HttpStatus#SC_CONFLICT}
@throws RuntimeException Other non-success status code.


@SuppressWarnings("unchecked")
	@Override
	public <T> T newInstance(ManagedClassSPI managedClass, Object... args) {
		Constructor<?> constructor = managedClass.getConstructor();
		if (constructor == null) {
			throw new BugError("Local instance factory cannot instantiate |%s|. Missing constructor.", managedClass);
		}

		Object instance = null;
		try {
			instance = constructor.newInstance(args);
		} catch (IllegalArgumentException e) {
			log.error("Wrong number of arguments or bad types for |%s|: [%s].", constructor, Strings.join(Classes.getParameterTypes(args)));
			throw e;
		} catch (InstantiationException e) {
			// managed class implementation is already validated, i.e. is not abstract and
			// test for existing constructor is performed... so no obvious reasons for instantiation exception
			throw new BugError(e);
		} catch (IllegalAccessException e) {
			// constructor has accessibility true and class is tested for public access modifier
			// so there is no reason for illegal access exception
			throw new BugError(e);
		} catch (InvocationTargetException e) {
			log.error("Managed instance constructor |%s| fail due to: %s.", constructor, e.getCause());
			throw new InvocationException(e);
		}

		if (managedClass.getInstanceType().equals(InstanceType.PROXY)) {
			// there are two proxy handlers: one transactional and one not
			// the difference is that transactional proxy handler gets a reference to an external transactional resource

			ManagedProxyHandler handler = null;
			if (managedClass.isTransactional()) {
				TransactionalResource transactionalResource = managedClass.getContainer().getInstance(TransactionalResource.class);
				handler = new ManagedProxyHandler(transactionalResource, managedClass, instance);
			} else {
				handler = new ManagedProxyHandler(managedClass, instance);
			}

			final ClassLoader classLoader = managedClass.getImplementationClass().getClassLoader();
			final Class<?>[] interfaceClasses = managedClass.getInterfaceClasses();
			return (T) Proxy.newProxyInstance(classLoader, interfaceClasses, handler);
		}

		return (T) instance;
	}

Uses managed class constructor to create new instance with provided arguments. Arguments should be in order, types and
number required by constructor signature.

@param managedClass managed class,
@param args optional arguments as required by constructor signature.
@param <T> instance type;
@return newly created managed instance.
@throws IllegalArgumentException if args argument is not of types and number required by constructor.
@throws InvocationException if constructor execution fails.

Uses managed class constructor to create new instance with provided arguments . Arguments should be in order types and number required by constructor signature .


public File[] getFiles() {
		List<File> result = new ArrayList<>();
		for (FileCount fileCount : results) {
			result.add(fileCount.getFile());
		}

		Collections.sort(result, new FitFileComparator());
		return result.toArray(new File[result.size()]);
	}

public File [ ] getFiles ( ) { List < File > result = new ArrayList <> ( ) ; for ( FileCount fileCount : results ) { result . add ( fileCount . getFile ( ) ) ; } Collections . sort ( result , new FitFileComparator ( ) ) ; return result . toArray ( new File [ result . size ( ) ] ) ; }

Returns all saved filenames.

@return filenames of all results.


public Counts getSummary() {
		Counts result = new Counts();
		for (FileCount fileCount : results) {
			if (fileCount.getCounts() != null) {
				result.tally(fileCount.getCounts());
			}
		}
		return result;
	}

public Counts getSummary ( ) { Counts result = new Counts ( ) ; for ( FileCount fileCount : results ) { if ( fileCount . getCounts ( ) != null ) { result . tally ( fileCount . getCounts ( ) ) ; } } return result ; }

Returns the sum of all results.

@return sum of all results


public String getSummaryRow(final File directory) {
		StringBuilder builder = new StringBuilder();
		Counts counts = getSummary();

		builder.append("
");
		builder.append(directory.getName());
		builder.append("	");
		builder.append(counts.toString());
		builder.append("
");

		return builder.toString();
	}

public
String
getSummaryRow
(
final
File
directory
)
{
StringBuilder
builder
=
new
StringBuilder
(
)
;
Counts
counts
=
getSummary
(
)
;
builder
.
append
(
"
"
)
;
builder
.
append
(
directory
.
getName
(
)
)
;
builder
.
append
(
"	"
)
;
builder
.
append
(
counts
.
toString
(
)
)
;
builder
.
append
(
"
"
)
;
return
builder
.
toString
(
)
;
}

Returns a summary row for a whole test run.

@param directory headline of the table
@return a single HTML row

Returns a summary row for a whole test run .


public String getSubSummaryRow(final File path) throws IOException {
		Counts sum = subDirSum(path);

		return String.format("
%s	%s
",
				color(sum), FitUtils.htmlSafeFile(dirHelper.abs2rel(new File("").getAbsolutePath(), path.getAbsolutePath())), sum.toString());
	}

Generates a HTML summary row for a subdirectory.

@param path subdirectory to process
@return a single HTML row
@throws IOException if path cannot be resolved correctly

Generates a HTML summary row for a subdirectory .


@SuppressWarnings("unchecked")
	@Override
	public <I> I newInstance(ManagedClassSPI managedClass, Object... args) {
		if (args.length > 0) {
			throw new IllegalArgumentException("Service instances factory does not support arguments.");
		}
		Class<?>[] interfaceClasses = managedClass.getInterfaceClasses();
		if (interfaceClasses == null) {
			throw new BugError("Invalid managed class. Null interface classes.");
		}
		if (interfaceClasses.length != 1) {
			throw new BugError("Invalid managed class. It should have exactly one interface class.");
		}
		return (I) Classes.loadService(interfaceClasses[0]);
	}

Load service defined by managed class interface and return service instance. This factory does not support arguments.
Service provider should be present into run-time otherwise no provider exception is thrown.

@param managedClass managed class,
@param args service instances factory does not support arguments.
@return loaded service instance.
@throws IllegalArgumentException if args argument is not empty.
@throws NoProviderException if no service provider found on run-time for requested interface.

Load service defined by managed class interface and return service instance . This factory does not support arguments . Service provider should be present into run - time otherwise no provider exception is thrown .


public final Class<?> getSetupClass() {
        if (setupClass != null) {
            return setupClass;
        }
        LOG.info("Creating setup class: {}", setupClassName);
        try {
            setupClass = Class.forName(setupClassName, true, context.getClassLoader());
        } catch (final ClassNotFoundException ex) {
            throw new RuntimeException("Couldn't load setup class: " + setupClassName, ex);
        }
        return setupClass;
    }

public
final
Class
<
>
getSetupClass
(
)
{
if
(
setupClass
!=
)
{
return
setupClass
;
}
LOG
.
info
(
"Creating setup class: {}"
,
setupClassName
)
;
try
{
setupClass
=
Class
.
forName
(
setupClassName
,
true
,
context
.
getClassLoader
(
)
)
;
}
catch
(
final
ClassNotFoundException
ex
)
{
throw
new
RuntimeException
(
"Couldn't load setup class: "
+
setupClassName
,
ex
)
;
}
return
setupClass
;
}

Returns the setup class.

@return Setup class of type {@link #setupClassName}.


public final List<File> getModelDirs() {
        if ((modelDirs == null) && (modelPath != null)) {
            modelDirs = paths().stream().filter(XtextParserConfig::isFile).map(XtextParserConfig::asFile).collect(Collectors.toList());
        }
        return modelDirs;
    }

public final List < File > getModelDirs ( ) { if ( ( modelDirs == null ) && ( modelPath != null ) ) { modelDirs = paths ( ) . stream ( ) . filter ( XtextParserConfig :: isFile ) . map ( XtextParserConfig :: asFile ) . collect ( Collectors . toList ( ) ) ; } return modelDirs ; }

Returns a list of model directories to parse.

@return Directory list or NULL.

Returns a list of model directories to parse .


public final List<URI> getModelResources() {
        if ((modelResources == null) && (modelPath != null)) {
            modelResources = new ArrayList<>();
            modelResources = paths().stream().filter(XtextParserConfig::isResource).map(XtextParserConfig::asResource)
                    .collect(Collectors.toList());
        }
        return modelResources;
    }

public final List < URI > getModelResources ( ) { if ( ( modelResources == null ) && ( modelPath != null ) ) { modelResources = new ArrayList <> ( ) ; modelResources = paths ( ) . stream ( ) . filter ( XtextParserConfig :: isResource ) . map ( XtextParserConfig :: asResource ) . collect ( Collectors . toList ( ) ) ; } return modelResources ; }

Returns a list of model resources to parse.

@return List of resources or NULL.

Returns a list of model resources to parse .


public void setCandidates(Collection<T> candidates) {
        twinColSelect.setContainerDataSource(
                container = new BeanItemContainer<>(entityType, candidates));
    }

public void setCandidates ( Collection < T > candidates ) { twinColSelect . setContainerDataSource ( container = new BeanItemContainer <> ( entityType , candidates ) ) ; }

Sets a set of candidates for selection.

@param candidates The candidates for selection.

Sets a set of candidates for selection .


protected static void loadXML(InputStream inputStream, Loader loader) throws ConfigException {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader reader = parser.getXMLReader();
			reader.setContentHandler(loader);
			reader.parse(new InputSource(inputStream));
		} catch (Exception e) {
			throw new ConfigException("Fail to load configuration document from file |%s|: %s", inputStream, e);
		}
	}

Load configuration document from file.

@param inputStream configuration XML file,
@param loader SAX handler in charge of configuration loading.
@throws ConfigException if XML document loading fails.


protected void onError(Exception ex) {
        Notification.show("Error", ex.getLocalizedMessage(), Notification.Type.ERROR_MESSAGE);
    }

protected void onError ( Exception ex ) { Notification . show ( "Error" , ex . getLocalizedMessage ( ) , Notification . Type . ERROR_MESSAGE ) ; }

Handler for errors reported by REST endpoints.

@param ex The exception reported by the REST endpoint.

Handler for errors reported by REST endpoints .


private static boolean isObject(Type[] formalParameters) {
		if (formalParameters.length != 1) {
			return false;
		}
		final Type type = formalParameters[0];
		if (!(type instanceof Class)) {
			return false;
		}
		if (Types.isPrimitive(type)) {
			return false;
		}
		if (Types.isArrayLike(type)) {
			return false;
		}
		if (Types.isMap(type)) {
			return false;
		}
		if (ConverterRegistry.hasType(type)) {
			return false;
		}
		return true;
	}

private static boolean isObject ( Type [ ] formalParameters ) { if ( formalParameters . length != 1 ) { return false ; } final Type type = formalParameters [ 0 ] ; if ( ! ( type instanceof Class ) ) { return false ; } if ( Types . isPrimitive ( type ) ) { return false ; } if ( Types . isArrayLike ( type ) ) { return false ; } if ( Types . isMap ( type ) ) { return false ; } if ( ConverterRegistry . hasType ( type ) ) { return false ; } return true ; }

Test if method formal parameters designates a strict object, that is, is not primitive, array, collection or map.

@param formalParameters method formal parameters list.
@return true if formal parameters designates a strict object.

Test if method formal parameters designates a strict object that is is not primitive array collection or map .


@Override
	public Object[] read(HttpServletRequest httpRequest, Type[] formalParameters) throws IOException, IllegalArgumentException {
		JsonReader reader = new JsonReader(httpRequest.getInputStream(), expectedStartSequence(formalParameters));
		try {
			return json.parse(reader, formalParameters);
		} catch (JsonException e) {
			throw new IllegalArgumentException(e.getMessage());
		} finally {
			reader.close();
		}
	}

@ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { JsonReader reader = new JsonReader ( httpRequest . getInputStream ( ) , expectedStartSequence ( formalParameters ) ) ; try { return json . parse ( reader , formalParameters ) ; } catch ( JsonException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } finally { reader . close ( ) ; } }

Uses JSON deserializer to parse method invocation arguments accordingly formal parameters list.

@param httpRequest HTTP request,
@param formalParameters formal parameter types.
@return arguments array.
@throws IOException if reading from request input stream fails.
@throws IllegalArgumentException if arguments from HTTP request cannot be parsed.
@throws JsonException if JSON parsing fails due to invalid stream format.

Uses JSON deserializer to parse method invocation arguments accordingly formal parameters list .


@Override
	public Object read(InputStream inputStream, Type type) throws IOException {
		try {
			return json.parse(new InputStreamReader(inputStream, "UTF-8"), type);
		} catch (JsonException | ClassCastException | UnsupportedEncodingException e) {
			throw new IllegalArgumentException(e.getMessage());
		}
	}

@ Override public Object read ( InputStream inputStream , Type type ) throws IOException { try { return json . parse ( new InputStreamReader ( inputStream , "UTF-8" ) , type ) ; } catch ( JsonException | ClassCastException | UnsupportedEncodingException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } }

Parse JSON from input stream accordingly given type. Return parsed object.

@param inputStream JSON input stream,
@param type expected type.
@return parsed object.
@throws IllegalArgumentException if JSON parse or reading from stream fails.

Parse JSON from input stream accordingly given type . Return parsed object .


public static String extractCellParameter(FitCell cell) {
		final Matcher matcher = PARAMETER_PATTERN.matcher(cell.getFitValue());
		if (matcher.matches()) {
			cell.setFitValue(matcher.group(1));
			return matcher.group(2);
		} else {
			return null;
		}
	}

public static String extractCellParameter ( FitCell cell ) { final Matcher matcher = PARAMETER_PATTERN . matcher ( cell . getFitValue ( ) ) ; if ( matcher . matches ( ) ) { cell . setFitValue ( matcher . group ( 1 ) ) ; return matcher . group ( 2 ) ; } else { return null ; } }

extracts and removes parameters from a cell.

@param cell cell to process
@return the extracted parameter or {@code null}

extracts and removes parameters from a cell .


@Override
	public java.util.Map<java.lang.String, java.lang.Object> getHints() {
		return this.q.getHints();
	}

@ Override public java . util . Map < java . lang . String , java . lang . Object > getHints ( ) { return this . q . getHints ( ) ; }

javax . persistence . Query & javax . persistence . TypedQuery


public static boolean isXHR(HttpServletRequest httpRequest) {
		String requestedWith = httpRequest.getHeader(X_REQUESTED_WITH);
		return requestedWith != null ? requestedWith.equalsIgnoreCase(XML_HTTP_REQUEST) : false;
	}

public static boolean isXHR ( HttpServletRequest httpRequest ) { String requestedWith = httpRequest . getHeader ( X_REQUESTED_WITH ) ; return requestedWith != null ? requestedWith . equalsIgnoreCase ( XML_HTTP_REQUEST ) : false ; }

Test if given HTTP request is performed via XMLHttpRequest.

@param httpRequest HTTP request.
@return true if X-Requested-With header is XMLHttpRequest.

Test if given HTTP request is performed via XMLHttpRequest .


public static boolean isAndroid(HttpServletRequest httpRequest) {
		String requestedWith = httpRequest.getHeader(X_REQUESTED_WITH);
		return requestedWith != null ? requestedWith.equalsIgnoreCase(ANDROID_USER_AGENT) : false;
	}

public static boolean isAndroid ( HttpServletRequest httpRequest ) { String requestedWith = httpRequest . getHeader ( X_REQUESTED_WITH ) ; return requestedWith != null ? requestedWith . equalsIgnoreCase ( ANDROID_USER_AGENT ) : false ; }

Test if HTTP request is from Android.

@param httpRequest HTTP request.
@return true if X-Requested-With header contains j(s)-lib android signature.


@Subscribe
    public void handle(ElementEvent<TEntity> message) {
        if (message.getEndpoint().getEntityType() == this.endpoint.getEntityType()) {
            refresh();
        }
    }

@ Subscribe public void handle ( ElementEvent < TEntity > message ) { if ( message . getEndpoint ( ) . getEntityType ( ) == this . endpoint . getEntityType ( ) ) { refresh ( ) ; } }

Refresh when child elements are created or updated


public static <TAnnotation extends Annotation> List<PropertyDescriptor> getPropertiesWithAnnotation(Class<?> beanType, Class<TAnnotation> annotationType) {
        LinkedList<PropertyDescriptor> result = new LinkedList<>();
        getProperties(beanType).forEach(property -> {
            if (property.getReadMethod() != null && property.getReadMethod().getAnnotation(annotationType) != null
                    || isFieldAnnotated(beanType, property.getName(), annotationType)) {
                result.add(property);
            }
        });
        return result;
    }

public static < TAnnotation extends Annotation > List < PropertyDescriptor > getPropertiesWithAnnotation ( Class < ? > beanType , Class < TAnnotation > annotationType ) { LinkedList < PropertyDescriptor > result = new LinkedList <> ( ) ; getProperties ( beanType ) . forEach ( property -> { if ( property . getReadMethod ( ) != null && property . getReadMethod ( ) . getAnnotation ( annotationType ) != null || isFieldAnnotated ( beanType , property . getName ( ) , annotationType ) ) { result . add ( property ) ; } } ) ; return result ; }

Lists all properties on a bean type that have a specific annotation on
their getter or backing field.

@param <TAnnotation> The annotation type to look for.
@param beanType The type of bean to check for properties.
@param annotationType The annotation type to look for.
@return A list of matching properties.

Lists all properties on a bean type that have a specific annotation on their getter or backing field .


public static <TAnnotation extends Annotation> Optional<TAnnotation> getAnnotation(Class<?> beanType, PropertyDescriptor property, Class<TAnnotation> annotationType) {
        Optional<TAnnotation> annotation = stream(property.getReadMethod().getAnnotationsByType(annotationType)).findAny();
        return annotation.isPresent()
                ? annotation
                : getAnnotationOnField(beanType, property.getName(), annotationType);
    }

public static < TAnnotation extends Annotation > Optional < TAnnotation > getAnnotation ( Class < ? > beanType , PropertyDescriptor property , Class < TAnnotation > annotationType ) { Optional < TAnnotation > annotation = stream ( property . getReadMethod ( ) . getAnnotationsByType ( annotationType ) ) . findAny ( ) ; return annotation . isPresent ( ) ? annotation : getAnnotationOnField ( beanType , property . getName ( ) , annotationType ) ; }

Returns an annotation of a specific type on a property's getter or its
backing field.

@param <TAnnotation> The type of annotation to look for.
@param beanType The type of bean the property is declared on.
@param property The property to check for the annotation.
@param annotationType The type of annotation to look for.
@return The annotation if present.

Returns an annotation of a specific type on a property s getter or its backing field .


private static String log(String message, Object... args) {
		message = String.format(message, args);
		java.util.logging.Logger.getLogger(Server.class.getCanonicalName()).log(java.util.logging.Level.SEVERE, message);
		return message;
	}

private static String log ( String message , Object ... args ) { message = String . format ( message , args ) ; java . util . logging . Logger . getLogger ( Server . class . getCanonicalName ( ) ) . log ( java . util . logging . Level . SEVERE , message ) ; return message ; }

Log formatted message to Java logger since framework logger is not yet initialized.

@param message message with optional formatting elements as supported by {@link String#format(String, Object...)},
@param args optional arguments.
@return formatted message.

Log formatted message to Java logger since framework logger is not yet initialized .


public WhoisResult lookup(String domain, int timeout) {
        container.put("domain", domain);
        container.put("timeout_param", timeout);
        try {
            return (WhoisResult) container.runScriptlet(
                    JRubyWhois.class.getResourceAsStream("jruby-whois.rb"),
                    "jruby-whois.rb");
        } catch (EvalFailedException e) {
            if (e.getMessage().startsWith("(ServerNotFound)")) {
                throw new ServerNotFoundException(e);
            }
            if (e.getMessage().startsWith("(WebInterfaceError")) {
                throw new WebInterfaceErrorException(e);
            }
            throw e;
        }
    }

public WhoisResult lookup ( String domain , int timeout ) { container . put ( "domain" , domain ) ; container . put ( "timeout_param" , timeout ) ; try { return ( WhoisResult ) container . runScriptlet ( JRubyWhois . class . getResourceAsStream ( "jruby-whois.rb" ) , "jruby-whois.rb" ) ; } catch ( EvalFailedException e ) { if ( e . getMessage ( ) . startsWith ( "(ServerNotFound)" ) ) { throw new ServerNotFoundException ( e ) ; } if ( e . getMessage ( ) . startsWith ( "(WebInterfaceError" ) ) { throw new WebInterfaceErrorException ( e ) ; } throw e ; } }

Uses the Ruby Whois gem to perform a whois lookup

@param domain
domain name to lookup
@param timeout
timeout in seconds
@return


public boolean hasParserForWhoisHost(String whoisHost) {
        container.put("host", whoisHost);
        return (Boolean) container.runScriptlet(
                JRubyWhois.class.getResourceAsStream("jruby-has-parser.rb"),
                "jruby-has-parser.rb");
    }

public boolean hasParserForWhoisHost ( String whoisHost ) { container . put ( "host" , whoisHost ) ; return ( Boolean ) container . runScriptlet ( JRubyWhois . class . getResourceAsStream ( "jruby-has-parser.rb" ) , "jruby-has-parser.rb" ) ; }

Check if Ruby Whois gem has a parser for a specific registrar

@param whoisHost
whois server to check
@return


private static ManagedClassSPI getManagedClass(ContainerSPI container, String interfaceName, String requestURI) throws ClassNotFoundException {
		Class<?> interfaceClass = Classes.forOptionalName(interfaceName);
		if (interfaceClass == null) {
			log.error("HTTP-RMI request for not existing class |%s|.", interfaceName);
			throw new ClassNotFoundException(requestURI);
		}
		ManagedClassSPI managedClass = container.getManagedClass(interfaceClass);
		if (managedClass == null) {
			log.error("HTTP-RMI request for not existing managed class |%s|.", interfaceName);
			throw new ClassNotFoundException(requestURI);
		}
		if (!managedClass.isRemotelyAccessible()) {
			log.error("HTTP-RMI request for local managed class |%s|. See @Remote annotation.", interfaceName);
			throw new ClassNotFoundException(requestURI);
		}
		return managedClass;
	}

Get remotely accessible managed class registered to a certain interface class.

@param container parent container,
@param interfaceName name of the interface class identifying requested managed class,
@param requestURI request URI for logging.
@return managed class, never null.
@throws ClassNotFoundException if interface class not found on run-time class path, managed class not defined or is not
remotely accessible.

Get remotely accessible managed class registered to a certain interface class .


private static ManagedMethodSPI getManagedMethod(ManagedClassSPI managedClass, String methodName, String requestURI) throws NoSuchMethodException {
		ManagedMethodSPI managedMethod = managedClass.getNetMethod(methodName);
		if (managedMethod == null) {
			log.error("HTTP-RMI request for not existing managed method |%s#%s|.", managedClass.getInterfaceClass().getName(), methodName);
			throw new NoSuchMethodException(requestURI);
		}
		if (!managedMethod.isRemotelyAccessible()) {
			log.error("HTTP-RMI request for local managed method |%s#%s|. See @Remote annotation.", managedClass.getInterfaceClass().getName(), methodName);
			throw new NoSuchMethodException(requestURI);
		}
		if (Types.isKindOf(managedMethod.getReturnType(), Resource.class)) {
			log.error("HTTP-RMI request for managed method |%s#%s| returning a resource.", managedClass.getInterfaceClass().getName(), methodName);
			throw new NoSuchMethodException(requestURI);
		}
		return managedMethod;
	}

Get managed method that is remotely accessible and has requested name.

@param managedClass managed class where method is supposed to be declared,
@param methodName method name,
@param requestURI request URI for logging.
@return managed method, never null.
@throws NoSuchMethodException if managed class has not any method with requested name, managed method was found but is
not remotely accessible or it returns a {@link Resource}.

Get managed method that is remotely accessible and has requested name .


public void processNotContainsException(Map<String, String> parameters) {
		LoggingEvent match = getMessageWithException(parameters);

		if (match == null) {
			cell.right();
		} else {
			cell.wrong(match.getThrowableInformation().getThrowableStrRep()[0]);
		}
	}

public void processNotContainsException ( Map < String , String > parameters ) { LoggingEvent match = getMessageWithException ( parameters ) ; if ( match == null ) { cell . right ( ) ; } else { cell . wrong ( match . getThrowableInformation ( ) . getThrowableStrRep ( ) [ 0 ] ) ; } }

Checks whether the log messages contain the expected exception.

@param parameters parameters to filter the processing
(see {@link AbstractLoggingEventMatcher}

Checks whether the log messages contain the expected exception .


public void processNotContains(Map<String, String> parameters) {
		LoggingEvent match = getMessageWithString(parameters);

		if (match == null) {
            cell.right();
		} else {
			cell.wrong(match.getMessage().toString());

		}
	}

public void processNotContains ( Map < String , String > parameters ) { LoggingEvent match = getMessageWithString ( parameters ) ; if ( match == null ) { cell . right ( ) ; } else { cell . wrong ( match . getMessage ( ) . toString ( ) ) ; } }

Checks whether the log messages do not contain the expected text.

@param parameters parameters to filter the processing
(see {@link AbstractLoggingEventMatcher}

Checks whether the log messages do not contain the expected text .


public Boolean getBoolean2(String columnLabel) throws java.sql.SQLException {
		boolean value = this.rs.getBoolean(columnLabel);
		return !this.rs.wasNull() ? value : null;
	}

public Boolean getBoolean2 ( String columnLabel ) throws java . sql . SQLException { boolean value = this . rs . getBoolean ( columnLabel ) ; return ! this . rs . wasNull ( ) ? value : null ; }


@Override
	public boolean isWrapperFor(java.lang.Class<?> arg0) throws java.sql.SQLException {
		return this.rs.isWrapperFor(arg0);
	}

@ Override public boolean isWrapperFor ( java . lang . Class < ? > arg0 ) throws java . sql . SQLException { return this . rs . isWrapperFor ( arg0 ) ; }


@Override
	public void serialize(HttpServletResponse httpResponse) throws IOException {
		httpResponse.setHeader(HttpHeader.CACHE_CONTROL, HttpHeader.NO_CACHE);
		httpResponse.addHeader(HttpHeader.CACHE_CONTROL, HttpHeader.NO_STORE);
		httpResponse.setHeader(HttpHeader.PRAGMA, HttpHeader.NO_CACHE);
		httpResponse.setDateHeader(HttpHeader.EXPIRES, 0);
		httpResponse.setContentType(getContentType().getValue());

		serialize(httpResponse.getOutputStream());
	}

@ Override public void serialize ( HttpServletResponse httpResponse ) throws IOException { httpResponse . setHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_CACHE ) ; httpResponse . addHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_STORE ) ; httpResponse . setHeader ( HttpHeader . PRAGMA , HttpHeader . NO_CACHE ) ; httpResponse . setDateHeader ( HttpHeader . EXPIRES , 0 ) ; httpResponse . setContentType ( getContentType ( ) . getValue ( ) ) ; serialize ( httpResponse . getOutputStream ( ) ) ; }

Set common HTTP response headers and delegates actual serialization to subclass. This method disables cache and set
content type to value returned by subclass.

@param httpResponse HTTP response to serialize view to.
@throws IOException if view serialization fails for whatever reasons.

Set common HTTP response headers and delegates actual serialization to subclass . This method disables cache and set content type to value returned by subclass .


public String get(String name) {
		Params.notNullOrEmpty(name, "Cookie name");
		if (cookies == null) {
			return null;
		}
		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				return cookie.getValue();
			}
		}
		return null;
	}

public
String
get
(
String
name
)
{
Params
.
notNullOrEmpty
(
name
,
"Cookie name"
)
;
if
(
cookies
==
)
{
return
;
}
for
(
Cookie
cookie
:
cookies
)
{
if
(
name
.
equals
(
cookie
.
getName
(
)
)
)
{
return
cookie
.
getValue
(
)
;
}
}
return
;
}

Get value of the named cookie or null if cookie does not exist.

@param name cookie name, not null or empty.
@return cookie cookie value or null if there is no cookie with requested name.
@throws IllegalArgumentException if name argument is null or empty.

Get value of the named cookie or null if cookie does not exist .


public void add(String name, String value) {
		Params.notNullOrEmpty(name, "Cookie name");
		Params.notNull(value, "Cookie value");
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		httpResponse.addCookie(cookie);
	}

public
void
add
(
String
name
,
String
value
)
{
Params
.
notNullOrEmpty
(
name
,
"Cookie name"
)
;
Params
.
notNull
(
value
,
"Cookie value"
)
;
Cookie
cookie
=
new
Cookie
(
name
,
value
)
;
cookie
.
setPath
(
"/"
)
;
httpResponse
.
addCookie
(
cookie
)
;
}

Add cookie to HTTP response of the current request context. Override cookie value if already exists.

@param name cookie name, not null or empty,
@param value cookie value, not null or empty.
@throws IllegalArgumentException if name argument is null or empty.
@throws IllegalArgumentException if value argument is null or empty.

Add cookie to HTTP response of the current request context . Override cookie value if already exists .


public void remove(String name) {
		Params.notNullOrEmpty(name, "Cookie name");
		if (cookies == null) {
			return;
		}
		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				cookie.setMaxAge(0);
				cookie.setValue("");
				cookie.setPath("/");
				httpResponse.addCookie(cookie);
				break;
			}
		}
	}

public
void
remove
(
String
name
)
{
Params
.
notNullOrEmpty
(
name
,
"Cookie name"
)
;
if
(
cookies
==
)
{
return
;
}
for
(
Cookie
cookie
:
cookies
)
{
if
(
name
.
equals
(
cookie
.
getName
(
)
)
)
{
cookie
.
setMaxAge
(
0
)
;
cookie
.
setValue
(
""
)
;
cookie
.
setPath
(
"/"
)
;
httpResponse
.
addCookie
(
cookie
)
;
break
;
}
}
}

Remove cookie from HTTP response. If named cookie does not exist this method does nothing.

@param name the name of the cookie to be removed, not null or empty.
@throws IllegalArgumentException if name argument is null or empty.

Remove cookie from HTTP response . If named cookie does not exist this method does nothing .


public Iterator<Cookie> iterator() {
		if (cookies == null) {
			return Collections.emptyIterator();
		}
		return Arrays.asList(cookies).iterator();
	}

public Iterator < Cookie > iterator ( ) { if ( cookies == null ) { return Collections . emptyIterator ( ) ; } return Arrays . asList ( cookies ) . iterator ( ) ; }

Get cookies iterator. Return empty iterator if not cookies on HTTP request.

@return cookies iterator, possible empty.

Get cookies iterator . Return empty iterator if not cookies on HTTP request .


public final TargetFileListProducer getTargetFileListProducer() {
        if (tflProducer != null) {
            return tflProducer;
        }
        final Object obj = Utils4J.createInstance(className);
        if (!(obj instanceof TargetFileListProducer)) {
            throw new IllegalStateException(
                    "Expected class to be of type '" + TargetFileListProducer.class.getName() + "', but was: " + className);
        }
        tflProducer = (TargetFileListProducer) obj;
        return tflProducer;
    }

public
final
TargetFileListProducer
getTargetFileListProducer
(
)
{
if
(
tflProducer
!=
)
{
return
tflProducer
;
}
final
Object
obj
=
Utils4J
.
createInstance
(
className
)
;
if
(
!
(
obj
instanceof
TargetFileListProducer
)
)
{
throw
new
IllegalStateException
(
"Expected class to be of type '"
+
TargetFileListProducer
.
class
.
getName
(
)
+
"', but was: "
+
className
)
;
}
tflProducer
=
(
TargetFileListProducer
)
obj
;
return
tflProducer
;
}

Returns an existing target file list producer instance or creates a new one if it's the first call to this method.

@return TargetFileListProducer of type {@link #className}.

Returns an existing target file list producer instance or creates a new one if it s the first call to this method .


public void add(final Class<?> type, final String name) throws ClassNotFoundException {
		FieldGen fg;

		if (result != null) {
			throw new IllegalStateException("Class already generated");
		}

		fg = new FieldGen(Constants.ACC_PUBLIC | Constants.ACC_SUPER,
				Type.getType(type), name, cg.getConstantPool());
		cg.addField(fg.getField());
	}

public
void
add
(
final
Class
<
>
type
,
final
String
name
)
throws
ClassNotFoundException
{
FieldGen
fg
;
if
(
result
!=
)
{
throw
new
IllegalStateException
(
"Class already generated"
)
;
}
fg
=
new
FieldGen
(
Constants
.
ACC_PUBLIC
|
Constants
.
ACC_SUPER
,
Type
.
getType
(
type
)
,
name
,
cg
.
getConstantPool
(
)
)
;
cg
.
addField
(
fg
.
getField
(
)
)
;
}

Adds a public field to the constructed class.

@param type type of the field
@param name name of the field
@throws ClassNotFoundException indicates a problem with {@code type}

Adds a public field to the constructed class .


public final Class<?> compile() {
		if (result == null) {
			loader.loadJavaClass(cg.getClassName(), cg.getJavaClass());
			try {
				result = loader.loadClass(cg.getClassName());
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
		}
		return result;
	}

public final Class < ? > compile ( ) { if ( result == null ) { loader . loadJavaClass ( cg . getClassName ( ) , cg . getJavaClass ( ) ) ; try { result = loader . loadClass ( cg . getClassName ( ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } return result ; }

Compiles the class and returns a class object which contains all
added fields.

@return dynamic generated class with all added fields.

Compiles the class and returns a class object which contains all added fields .


public boolean verifyResponse(String token) throws NullPointerException {
		return value.equals(getValue(tokenedImageFiles.get(token)));
	}

public boolean verifyResponse ( String token ) throws NullPointerException { return value . equals ( getValue ( tokenedImageFiles . get ( token ) ) ) ; }

Test that selected image identified by given token is the right response.

@param token unique token identifying selected image, null or empty tolerated.
@return true if token identifies this challenge response.

Test that selected image identified by given token is the right response .


private static String getValue(File file) throws NullPointerException {
		if (file == null) {
			return null;
		}
		return file.getName().toLowerCase().replaceAll(EXTENSION_REX, "").replaceAll(NOT_LETTERS_REX, " ");
	}

private
static
String
getValue
(
File
file
)
throws
NullPointerException
{
if
(
file
==
)
{
return
;
}
return
file
.
getName
(
)
.
toLowerCase
(
)
.
replaceAll
(
EXTENSION_REX
,
""
)
.
replaceAll
(
NOT_LETTERS_REX
,
" "
)
;
}

Challenge value associated with image file. File name is converted to lower case, extension removed and non letter
characters replaces with space, that is, non letters are considered words separators.

@param file image file, null tolerated.
@return challenge value or null if given file is null.

Challenge value associated with image file . File name is converted to lower case extension removed and non letter characters replaces with space that is non letters are considered words separators .


@SneakyThrows
    public static URI ensureTrailingSlash(URI uri) {
        URIBuilder builder = new URIBuilder(uri);
        if (!builder.getPath().endsWith("/")) {
            builder.setPath(builder.getPath() + "/");
        }
        return builder.build();
    }

@ SneakyThrows public static URI ensureTrailingSlash ( URI uri ) { URIBuilder builder = new URIBuilder ( uri ) ; if ( ! builder . getPath ( ) . endsWith ( "/" ) ) { builder . setPath ( builder . getPath ( ) + "/" ) ; } return builder . build ( ) ; }

Adds a trailing slash to the URI if it does not already have one.

@param uri The original URI.
@return The URI with appended slash.

Adds a trailing slash to the URI if it does not already have one .


@Override
	public boolean login(String username, String password) {
		try {
			getHttpServletRequest().login(username, password);
		} catch (ServletException e) {
			// exception is thrown if request is already authenticated, servlet container authentication is not enabled or
			// credentials are not accepted
			// consider all these conditions as login fail but record the event to application logger
			log.debug(e);
			return false;
		}
		return true;
	}


private HttpServletRequest getHttpServletRequest() {
		RequestContext context = getInstance(RequestContext.class);
		HttpServletRequest request = context.getRequest();
		if (request == null) {
			throw new BugError("Attempt to use not initialized HTTP request.");
		}
		return request;
	}

Get HTTP request from current request context.

@return current HTTP request.
@throws BugError if attempt to use not initialized HTTP request.

Get HTTP request from current request context .


@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		final ManagedMethodSPI managedMethod = managedClass.getManagedMethod(method);
		log.trace("Invoke |%s|.", managedMethod);

		if (!managedMethod.isTransactional()) {
			// execute managed method that is not included within transactional boundaries
			try {
				return managedMethod.invoke(managedInstance, args);
			} catch (Throwable t) {
				throw throwable(t, "Non transactional method |%s| invocation fails.", managedMethod);
			}
		}

		if (managedMethod.isImmutable()) {
			return executeImmutableTransaction(managedMethod, args);
		}
		return executeMutableTransaction(managedMethod, args);
	}

Invocation handler implementation. Every method invocation on managed class interface is routed to this point. Here
actual container services are implemented and method is invoked against wrapped instance.

@param proxy instance of dynamically generated Java Proxy,
@param method interface Java method about to invoke,
@param args method invocation arguments.
@return value returned by implementation method.
@throws Throwable forward any exception rose by implementation method.

Invocation handler implementation . Every method invocation on managed class interface is routed to this point . Here actual container services are implemented and method is invoked against wrapped instance .


private Object executeMutableTransaction(ManagedMethodSPI managedMethod, Object[] args) throws Throwable {
		// store transaction session on current thread via transactional resource utility
		// it may happen to have multiple nested transaction on current thread
		// since all are created by the same transactional resource, all are part of the same session
		// and there is no harm if storeSession is invoked multiple times
		// also performance penalty is comparable with the effort to prevent this multiple write

		Transaction transaction = transactionalResource.createTransaction();
		transactionalResource.storeSession(transaction.getSession());

		try {
			Object result = managedMethod.invoke(managedInstance, args);
			transaction.commit();
			if (transaction.unused()) {
				log.debug("Method |%s| superfluously declared transactional.", managedMethod);
			}
			return result;
		} catch (Throwable throwable) {
			transaction.rollback();
			throw throwable(throwable, "Mutable transactional method |%s| invocation fail.", managedMethod);
		} finally {
			if (transaction.close()) {
				// it may happen to have multiple nested transaction on this thread
				// if this is the case, remove session from current thread only if outermost transaction is closed
				// of course if not nested transactions, remove at once
				transactionalResource.releaseSession();
			}
		}
	}

Helper method for mutable transaction execution.

@param managedMethod managed method to be executed into transactional scope,
@param args managed method arguments.
@return value returned by managed method.
@throws Throwable forward any error rose by method execution.

Helper method for mutable transaction execution .


private Object executeImmutableTransaction(ManagedMethodSPI managedMethod, Object[] args) throws Throwable {
		Transaction transaction = transactionalResource.createReadOnlyTransaction();
		// see mutable transaction comment
		transactionalResource.storeSession(transaction.getSession());

		try {
			Object result = managedMethod.invoke(managedInstance, args);
			if (transaction.unused()) {
				log.debug("Method |%s| superfluously declared transactional.", managedMethod);
			}
			return result;
		} catch (Throwable throwable) {
			throw throwable(throwable, "Immutable transactional method |%s| invocation fail.", managedMethod);
		} finally {
			if (transaction.close()) {
				// see mutable transaction comment
				transactionalResource.releaseSession();
			}
		}
	}

Helper method for immutable transaction execution.

@param managedMethod managed method to be executed into transactional scope,
@param args managed method arguments.
@return value returned by managed method.
@throws Throwable forward any error rose by method execution.

Helper method for immutable transaction execution .


public File[] getFiles() {
		final File[] files = directory.listFiles(filter);
		if (files == null) {
			return new File[0];
		} else {
			return files;
		}
	}

public File [ ] getFiles ( ) { final File [ ] files = directory . listFiles ( filter ) ; if ( files == null ) { return new File [ 0 ] ; } else { return files ; } }

Returns a list of all matching files.

@return all files which match the pattern


public File getLastFile() throws FileNotFoundException {
		File[] files = directory.listFiles(filter);
		if (files == null || files.length == 0) {
			throw new FileNotFoundException();
		}

		return files[files.length - 1];
	}

public File getLastFile ( ) throws FileNotFoundException { File [ ] files = directory . listFiles ( filter ) ; if ( files == null || files . length == 0 ) { throw new FileNotFoundException ( ) ; } return files [ files . length - 1 ] ; }

Returns the last matching file.

@return the matching file or null if no file matches
@throws FileNotFoundException thrown, if the directory does not exist


@SuppressWarnings("unchecked")
    protected final CONFIG_TYPE getConcreteConfig(final ParserConfig config) {
        final Config<ParserConfig> cfg = config.getConfig();
        if (cfg == null) {
            throw new IllegalStateException(
                    "The configuration is expected to be of type '" + concreteConfigClass.getName() + "', but was: null");
        } else {
            if (!(concreteConfigClass.isAssignableFrom(cfg.getConfig().getClass()))) {
                throw new IllegalStateException(
                        "The configuration is expected to be of type '" + concreteConfigClass.getName() + "', but was: "
                                + cfg.getConfig().getClass().getName() + " - Did you add the configuration class to the JXB context?");
            }
        }
        return (CONFIG_TYPE) cfg.getConfig();
    }

Returns the parser configuration.

@param config
Wrapping parser configuration that contains the concrete one.

@return Parser specific configuration.


private static boolean startsWith(String requestPath, String pathComponent) {
		if (requestPath.charAt(0) != '/') {
			return false;
		}
		int i = 1;
		for (int j = 0; i < requestPath.length(); ++i, ++j) {
			if (requestPath.charAt(i) == '/') {
				return j == pathComponent.length();
			}
			if (j == pathComponent.length()) {
				return false;
			}
			if (Character.toLowerCase(requestPath.charAt(i)) != Character.toLowerCase(pathComponent.charAt(j))) {
				return false;
			}
		}
		return false;
	}

private static boolean startsWith ( String requestPath , String pathComponent ) { if ( requestPath . charAt ( 0 ) != ' ' ) { return false ; } int i = 1 ; for ( int j = 0 ; i < requestPath . length ( ) ; ++ i , ++ j ) { if ( requestPath . charAt ( i ) == ' ' ) { return j == pathComponent . length ( ) ; } if ( j == pathComponent . length ( ) ) { return false ; } if ( Character . toLowerCase ( requestPath . charAt ( i ) ) != Character . toLowerCase ( pathComponent . charAt ( j ) ) ) { return false ; } } return false ; }

Test if request path starts with path component. This predicate returns true if first path component from given request
path equals requested path component. Comparison is not case sensitive. Request path should start with path separator,
otherwise this predicate returns false.

@param requestPath request path to test,
@param pathComponent path component that is compared with first path component from request path.
@return true if request path starts with path component.

Test if request path starts with path component . This predicate returns true if first path component from given request path equals requested path component . Comparison is not case sensitive . Request path should start with path separator otherwise this predicate returns false .


@SuppressWarnings("unchecked")
    @NotNull
    public final <MODEL> List<ArtifactFactory<MODEL>> getFactories(final Class<MODEL> modelType) {
        final List<ArtifactFactory<MODEL>> list = new ArrayList<ArtifactFactory<MODEL>>();
        if (factories == null) {
            factories = new ArrayList<ArtifactFactory<?>>();
            if (factoryConfigs != null) {
                for (final ArtifactFactoryConfig factoryConfig : factoryConfigs) {
                    factories.add(factoryConfig.getFactory());
                }
            }
        }
        for (final ArtifactFactory<?> factory : factories) {
            if (modelType.isAssignableFrom(factory.getModelType())) {
                list.add((ArtifactFactory<MODEL>) factory);
            }
        }
        return list;
    }

@ SuppressWarnings ( "unchecked" ) @ NotNull public final < MODEL > List < ArtifactFactory < MODEL > > getFactories ( final Class < MODEL > modelType ) { final List < ArtifactFactory < MODEL > > list = new ArrayList < ArtifactFactory < MODEL > > ( ) ; if ( factories == null ) { factories = new ArrayList < ArtifactFactory < ? > > ( ) ; if ( factoryConfigs != null ) { for ( final ArtifactFactoryConfig factoryConfig : factoryConfigs ) { factories . add ( factoryConfig . getFactory ( ) ) ; } } } for ( final ArtifactFactory < ? > factory : factories ) { if ( modelType . isAssignableFrom ( factory . getModelType ( ) ) ) { list . add ( ( ArtifactFactory < MODEL > ) factory ) ; } } return list ; }

Returns a list of factories for the given model type.

@param modelType
Model type to return artifact factories for.

@return List of factories that accept the given model type.

@param <MODEL>
Type of the model to create an artifact for.

Returns a list of factories for the given model type .


private HttpSession getSession(InstanceKey instanceKey) {
		RequestContext requestContext = appFactory.getInstance(RequestContext.class);
		HttpServletRequest httpRequest = requestContext.getRequest();
		if (httpRequest == null) {
			throw new BugError("Invalid web context due to null HTTP request. Cannot create managed instance for |%s| with scope SESSION.", instanceKey);
		}

		// create HTTP session if missing; accordingly API httpSession is never null if 'create' flag is true
		return httpRequest.getSession(true);
	}

Get HTTP session from current request, creating it if necessary. This method should be call inside a request context
otherwise bug error is thrown.

@param instanceKey managed instance key.
@return current request HTTP session.
@throws BugError if attempt to use this method outside a HTTP request.

Get HTTP session from current request creating it if necessary . This method should be call inside a request context otherwise bug error is thrown .


@Override
	public void serialize(HttpServletResponse httpResponse) throws IOException {
		httpResponse.setHeader(HttpHeader.CACHE_CONTROL, HttpHeader.NO_CACHE);
		httpResponse.addHeader(HttpHeader.CACHE_CONTROL, HttpHeader.NO_STORE);
		httpResponse.setHeader(HttpHeader.PRAGMA, HttpHeader.NO_CACHE);
		httpResponse.setDateHeader(HttpHeader.EXPIRES, 0);
		httpResponse.setContentType(contentType);
		httpResponse.setHeader(HttpHeader.CONTENT_LENGTH, Long.toString(file.length()));
		Files.copy(file, httpResponse.getOutputStream());
	}

@ Override public void serialize ( HttpServletResponse httpResponse ) throws IOException { httpResponse . setHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_CACHE ) ; httpResponse . addHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_STORE ) ; httpResponse . setHeader ( HttpHeader . PRAGMA , HttpHeader . NO_CACHE ) ; httpResponse . setDateHeader ( HttpHeader . EXPIRES , 0 ) ; httpResponse . setContentType ( contentType ) ; httpResponse . setHeader ( HttpHeader . CONTENT_LENGTH , Long . toString ( file . length ( ) ) ) ; Files . copy ( file , httpResponse . getOutputStream ( ) ) ; }

Serialize this file resource to HTTP response. Disable cache and set content type and content length.

@param httpResponse HTTP response.
@throws IOException if writing to underlying stream fails.

Serialize this file resource to HTTP response . Disable cache and set content type and content length .


public void readMeta()
            throws IOException, IllegalArgumentException, IllegalAccessException, FileNotFoundException, IllegalStateException {
        executeAndHandle(Request.Get(uri));
    }

public void readMeta ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { executeAndHandle ( Request . Get ( uri ) ) ; }

Fetches meta data such as links from the server.

@throws IOException Network communication failed.
@throws IllegalArgumentException {@link HttpStatus#SC_BAD_REQUEST}
@throws IllegalAccessException {@link HttpStatus#SC_UNAUTHORIZED} or
{@link HttpStatus#SC_FORBIDDEN}
@throws FileNotFoundException {@link HttpStatus#SC_NOT_FOUND} or
{@link HttpStatus#SC_GONE}
@throws IllegalStateException {@link HttpStatus#SC_CONFLICT}
@throws RuntimeException Other non-success status code.

Fetches meta data such as links from the server .


@Override
	protected void handleRequest(RequestContext context) throws ServletException, IOException {
		// for exceptions generated before response commit uses HttpServletResponse.sendError
		// on send error, servlet container prepares error response using container internal HTML for response body
		// if <error-page> is configured into deployment descriptor servlet container uses that HTML for response body

		final HttpServletRequest httpRequest = context.getRequest();
		final HttpServletResponse httpResponse = context.getResponse();

		ArgumentsReader argumentsReader = null;
		Resource resource = null;
		try {
			ManagedMethodSPI method = resourceMethods.get(key(context.getRequestPath()));
			if (method == null) {
				throw new NoSuchMethodException(httpRequest.getRequestURI());
			}

			final Type[] formalParameters = method.getParameterTypes();
			argumentsReader = argumentsReaderFactory.getArgumentsReader(httpRequest, formalParameters);
			Object[] arguments = argumentsReader.read(httpRequest, formalParameters);

			Object controller = container.getInstance(method.getDeclaringClass());
			resource = method.invoke(controller, arguments);
			if (resource == null) {
				throw new BugError("Null resource |%s|.", httpRequest.getRequestURI());
			}
		} catch (AuthorizationException e) {
			// at this point, resource is private and need to redirect to a login page
			// if application provides one, tiny container is configured with, and use it
			// otherwise servlet container should have one
			// if no login page found send back servlet container error - that could be custom error page, if declared

			String loginPage = container.getLoginPage();
			if (loginPage != null) {
				httpResponse.sendRedirect(loginPage);
			} else {
				// expected servlet container behavior:
				// if <login-config> section exist into web.xml do what is configured there
				// else send back internal page with message about SC_UNAUTHORIZED

				// authenticate can throw ServletException if fails, perhaps because is not configured
				// let servlet container handle this error, that could be custom error page is configured
				httpRequest.authenticate(httpResponse);
			}
			return;
		} catch (NoSuchMethodException | IllegalArgumentException e) {
			// do not use AppServlet#sendError since it is encoded JSON and for resources need HTML
			dumpError(context, e);
			httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, httpRequest.getRequestURI());
			return;
		} catch (InvocationException e) {
			// do not use AppServlet#sendError since it is encoded JSON and for resources need HTML
			dumpError(context, e);
			if (e.getCause() instanceof NoSuchResourceException) {
				httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, httpRequest.getRequestURI());
			} else {
				httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getCause().getMessage());
			}
			return;
		} finally {
			if (argumentsReader != null) {
				argumentsReader.clean();
			}
		}

		// once serialization process started response becomes committed
		// and is not longer possible to use HttpServletResponse#sendError

		// let servlet container handle IO exceptions but since client already start rendering
		// there is no so much to do beside closing or reseting connection

		httpResponse.setStatus(HttpServletResponse.SC_OK);
		resource.serialize(httpResponse);
	}

Handle request for a resource. Locate resource method based on request path from request context, execute method and
serialize back to client returned resource. See class description for general behavior.

@param context request context.
@throws ServletException if a servlet container service fails.
@throws IOException if reading from HTTP request or writing to HTTP response fail.

Handle request for a resource . Locate resource method based on request path from request context execute method and serialize back to client returned resource . See class description for general behavior .


@Override
	public void tearDown() throws Exception {
		if (statement != null) {
			statement.close();
			statement = null;
		}
		super.tearDown();
	}

@ Override public void tearDown ( ) throws Exception { if ( statement != null ) { statement . close ( ) ; statement = null ; } super . tearDown ( ) ; }

Closes the SQL statement.

@throws Exception propagated to fit.


@Override
	public void preDestroy() {
		if (eventStreams.isEmpty()) {
			return;
		}

		// EventStream#close signals stream loop that breaks
		// as a consequence, EventStreamServlet ends current request processing and call this#closeEventStream
		// this#closeEventStream removes event stream from this#eventStreams list resulting in concurrent change
		// to cope with this concurrent change uses a temporary array

		// toArray API is a little confusing for me regarding returned array
		// to be on safe side let toArray to determine array size
		// also I presume returned array is not altered by list updates

		for (EventStream eventStream : eventStreams.toArray(new EventStream[0])) {
			log.debug("Force close stale event stream |%s|.", eventStream);
			eventStream.close();
		}
	}

Closes all event streams still opened when event stream manager is destroyed.

Closes all event streams still opened when event stream manager is destroyed .


protected void handleAllowedMethods() {
        endpoint.isDownloadAllowed().ifPresent(this::setDownloadEnabled);
        endpoint.isUploadAllowed().ifPresent(this::setUploadEnabled);
        endpoint.isDeleteAllowed().ifPresent(this::setDeleteEnabled);
    }

protected void handleAllowedMethods ( ) { endpoint . isDownloadAllowed ( ) . ifPresent ( this :: setDownloadEnabled ) ; endpoint . isUploadAllowed ( ) . ifPresent ( this :: setUploadEnabled ) ; endpoint . isDeleteAllowed ( ) . ifPresent ( this :: setDeleteEnabled ) ; }

Enables or disabled buttons based on the "Allow" HTTP header.

Enables or disabled buttons based on the Allow HTTP header .


protected void upload() {
        try {
            onUpload();
            eventBus.post(new BlobUploadEvent(endpoint));
            Notification.show("Success", "Upload complete", Notification.Type.TRAY_NOTIFICATION);
        } catch (IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex) {
            onError(ex);
        }
    }

protected
void
upload
(
)
{
try
{
onUpload
(
)
;
eventBus
.
post
(
new
BlobUploadEvent
(
endpoint
)
)
;
Notification
.
show
(
"Success"
,
"Upload complete"
,
Notification
.
Type
.
TRAY_NOTIFICATION
)
;
}
catch
(
IOException
|
IllegalArgumentException
|
IllegalAccessException
|
IllegalStateException
ex
)
{
onError
(
ex
)
;
}
}

Called to upload new blob data to the server.

Called to upload new blob data to the server .


protected void delete() {
        String question = "Are you sure you want to delete the data from the server?";
        ConfirmDialog.show(getUI(), question, new ConfirmDialog.Listener() {
            @Override
            public void onClose(ConfirmDialog cd) {
                if (cd.isConfirmed()) {
                    try {
                        endpoint.delete();
                        close();
                    } catch (IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex) {
                        onError(ex);
                    } catch (RuntimeException ex) {
                        // Must explicitly send unhandled exceptions to error handler.
                        // Would otherwise get swallowed silently within callback handler.
                        getUI().getErrorHandler().error(new com.vaadin.server.ErrorEvent(ex));
                    }
                }
            }
        });
    }


protected String[] extractColumnParameters(FitRow row) {
        final List<String> result = new ArrayList<>();

        for (FitCell cell : row.cells()) {
            result.add(FitUtils.extractCellParameter(cell));
        }

        return result.toArray(new String[result.size()]);
    }

protected String [ ] extractColumnParameters ( FitRow row ) { final List < String > result = new ArrayList <> ( ) ; for ( FitCell cell : row . cells ( ) ) { result . add ( FitUtils . extractCellParameter ( cell ) ) ; } return result . toArray ( new String [ result . size ( ) ] ) ; }

extracts and removes parameters from a row.

@param row row to process
@return extracted parameters

extracts and removes parameters from a row .


protected String[] getArgNames() {
        if (args == null) {
            return new String[]{};
        }

        return args.keySet().toArray(new String[args.keySet().size()]);
    }

protected String [ ] getArgNames ( ) { if ( args == null ) { return new String [ ] { } ; } return args . keySet ( ) . toArray ( new String [ args . keySet ( ) . size ( ) ] ) ; }

Returns all argument names.

@return a list of all given argument names.
@see #getArg(String, String) getArg
@see #copyParamsToFixture()  copyParamsToFixture


public synchronized void period(final PeriodicTask periodicTask, long period) {
		TimerTask task = new PeriodicTaskImpl(periodicTask);
		this.tasks.put(periodicTask, task);
		this.timer.schedule(task, 0L, period);
	}

public synchronized void period ( final PeriodicTask periodicTask , long period ) { TimerTask task = new PeriodicTaskImpl ( periodicTask ) ; this . tasks . put ( periodicTask , task ) ; this . timer . schedule ( task , 0L , period ) ; }

Schedule periodic task execution.

@param periodicTask periodic task instance,
@param period requested execution period, milliseconds.


public synchronized void timeout(final TimeoutTask timeoutTask, long timeout) {
		TimerTask task = this.tasks.get(timeoutTask);
		if (task != null) {
			task.cancel();
			this.tasks.values().remove(task);
		}
		task = new TimeoutTaskImpl(timeoutTask);
		this.tasks.put(timeoutTask, task);
		this.timer.schedule(task, timeout);
	}

public synchronized void timeout ( final TimeoutTask timeoutTask , long timeout ) { TimerTask task = this . tasks . get ( timeoutTask ) ; if ( task != null ) { task . cancel ( ) ; this . tasks . values ( ) . remove ( task ) ; } task = new TimeoutTaskImpl ( timeoutTask ) ; this . tasks . put ( timeoutTask , task ) ; this . timer . schedule ( task , timeout ) ; }

Schedule timeout task, reseting timeout period if given timeout task is already pending.

@param timeoutTask timeout task instance,
@param timeout timeout value, milliseconds.

Schedule timeout task reseting timeout period if given timeout task is already pending .


@Override
	public void config(Config config) throws ConfigException, IOException {
		for (Config repositorySection : config.findChildren("repository")) {
			// view manager configuration section is named <views>
			// a <views> configuration section has one or many <repository> child sections
			// scan every repository files accordingly files pattern and add meta views to views meta pool

			// load repository view implementation class and perform insanity checks
			String className = repositorySection.getAttribute("class", DEF_IMPLEMENTATION);
			Class<?> implementation = Classes.forOptionalName(className);
			if (implementation == null) {
				throw new ConfigException("Unable to load view implementation |%s|.", className);
			}
			if (!Types.isKindOf(implementation, View.class)) {
				throw new ConfigException("View implementation |%s| is not of proper type.", className);
			}
			if (!Classes.isInstantiable(implementation)) {
				throw new ConfigException("View implementation |%s| is not instantiable. Ensure is not abstract or interface and have default constructor.", implementation);
			}
			@SuppressWarnings("unchecked")
			Class<? extends View> viewImplementation = (Class<? extends View>) implementation;

			// load repository path and files pattern and create I18N repository instance
			String repositoryPath = repositorySection.getAttribute("path");
			if (repositoryPath == null) {
				throw new ConfigException("Invalid views repository configuration. Missing <path> attribute.");
			}
			String filesPattern = repositorySection.getAttribute("files-pattern");
			if (filesPattern == null) {
				throw new ConfigException("Invalid views repository configuration. Missing <files-pattern> attribute.");
			}

			ConfigBuilder builder = new I18nRepository.ConfigBuilder(repositoryPath, filesPattern);
			I18nRepository repository = new I18nRepository(builder.build());
			if (viewsMetaPool == null) {
				// uses first repository to initialize i18n pool
				// limitation for this solution is that all repositories should be the kind: locale sensitive or not
				viewsMetaPool = repository.getPoolInstance();
			}
			Properties properties = repositorySection.getProperties();

			// traverses all files from I18N repository instance and register view meta instance
			// builder is used by view meta to load the document template
			for (I18nFile template : repository) {
				ViewMeta meta = new ViewMeta(template.getFile(), viewImplementation, properties);
				if (viewsMetaPool.put(meta.getName(), meta, template.getLocale())) {
					log.warn("Override view |%s|", meta);
				} else {
					log.debug("Register view |%s|", meta);
				}
			}
		}
	}

Create views meta pool from given managed view configuration object. Configuration object is described on class
description.

@param config view manager configuration object.
@throws ConfigException if configuration object is not valid.
@throws IOException if views meta pool cannot be created.

Create views meta pool from given managed view configuration object . Configuration object is described on class description .


@Override
	public final File next() {
		if (files == null || fileIndex >= files.length) {
			if (!cacheNext()) {
				throw new NoSuchElementException();
			}
		}
		return files[fileIndex++];
	}

@ Override public final File next ( ) { if ( files == null || fileIndex >= files . length ) { if ( ! cacheNext ( ) ) { throw new NoSuchElementException ( ) ; } } return files [ fileIndex ++ ] ; }

Returns the next matching file.

@return the next element in the iteration.
@throws NoSuchElementException iteration has no more elements


private static void configureApplication() {
        // Try to load the file.
        File file = new File("chameria.props");
        if (file.exists()) {
            Properties props = new Properties();
            InputStream is = null;
            try {
                is = new FileInputStream(file);
                props.load(is);

                String n = props.getProperty("application.name");
                if (n != null) {
                    QApplication.setApplicationName(n);
                } else {
                    QApplication.setApplicationName("akquinet ChameRIA");
                }

                n = props.getProperty("application.version");
                if (n != null) {
                    QApplication.setApplicationVersion(n);
                }

                n = props.getProperty("application.icon");
                if (n != null) {
                    QIcon icon = new QIcon(n);
                    QApplication.setWindowIcon(icon);
                }

            } catch (Exception e) {
                System.err.println("Cannot read the application configuration "
                        + e.getMessage());
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        // Ignored
                    }
                }
            }
        }

        QApplication.setOrganizationName("akquinet A.G.");
    }


private static void printWelcomeBanner() {
        StringBuffer banner = new StringBuffer();
        banner.append("\n");
        banner.append("\t============================\n");
        banner.append("\t|                          |\n");
        banner.append("\t|   Welcome to ChameRIA    |\n");
        banner.append("\t|                          |\n");
        banner.append("\t============================\n");
        banner.append("\n");
        System.out.println(banner);
    }

private
static
void
printWelcomeBanner
(
)
{
StringBuffer
banner
=
new
StringBuffer
(
)
;
banner
.
append
(
"\n"
)
;
banner
.
append
(
"\t============================\n"
)
;
banner
.
append
(
"\t|                          |\n"
)
;
banner
.
append
(
"\t|   Welcome to ChameRIA    |\n"
)
;
banner
.
append
(
"\t|                          |\n"
)
;
banner
.
append
(
"\t============================\n"
)
;
banner
.
append
(
"\n"
)
;
System
.
out
.
println
(
banner
)
;
}


private static void printStoppedBanner() {
        System.out.println("\n");
        System.out.println("\t=========================");
        System.out.println("\t|   ChameRIA  stopped   |");
        System.out.println("\t=========================");
        System.out.println("\n");
    }

private
static
void
printStoppedBanner
(
)
{
System
.
out
.
println
(
"\n"
)
;
System
.
out
.
println
(
"\t========================="
)
;
System
.
out
.
println
(
"\t|   ChameRIA  stopped   |"
)
;
System
.
out
.
println
(
"\t========================="
)
;
System
.
out
.
println
(
"\n"
)
;
}