signature:
public class AbstractEMFParser { /** * Returns files that end with java and all directories . Files and directories started with a " . " are excluded .
 * @ param dir
 * Directory to scan .
 * @ return List of files in the directory . */
private File [ ] getFiles ( final File dir ) { } }

implementation: final File [ ] files = dir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( final File file ) { final boolean pointFile = file . getName ( ) . startsWith ( "." ) ; final String extension = FilenameUtils . getExtension ( file . getName ( ) ) ; return ( ! pointFile && fileExtensions . contains ( extension ) ) || file . isDirectory ( ) ; } } ) ; return files ;


signature:
public class AbstractEMFParser { /** * Parse the directory and it ' s sub directory .
 * @ param dir
 * Directory to parse . */
private void parseDir ( final File dir ) { } }

implementation: LOG . debug ( "Parse: {}" , dir ) ; final File [ ] files = getFiles ( dir ) ; if ( ( files == null ) || ( files . length == 0 ) ) { LOG . debug ( "No files found in directory: {}" , dir ) ; } else { for ( final File file : files ) { if ( file . isFile ( ) ) { final Resource resource = resourceSet . getResource ( URI . createFileURI ( Utils4J . getCanonicalPath ( file ) ) , true ) ; final EList < Diagnostic > diagnostics = resource . getErrors ( ) ; if ( diagnostics . size ( ) == 0 ) { LOG . debug ( "Parsed {}" , file ) ; } else { error = true ; LOG . error ( "Parsed {} with errors: {}" , file , diagnostics ) ; } } else { parseDir ( file ) ; } } }


signature:
public class AbstractEMFParser { /** * Determines if all proxies in the model are resolved .
 * @ return { @ code true } if there are no more proxies in the model . */
public boolean isModelFullyResolved ( ) { } }

implementation: boolean resolved = true ; final Set < EObject > eObjects = findAllEObjects ( resourceSet ) ; final Iterator < EObject > it = eObjects . iterator ( ) ; while ( it . hasNext ( ) ) { final EObject eObj = it . next ( ) ; if ( eObj instanceof InternalEObject ) { final InternalEObject iObj = ( InternalEObject ) eObj ; for ( final EObject crossRef : iObj . eCrossReferences ( ) ) { if ( crossRef . eIsProxy ( ) ) { LOG . error ( "Unresolved: {}" , crossRef ) ; resolved = false ; } } } } return resolved ;


signature:
public class AbstractEMFParser { /** * Returns a list of all objects .
 * @ return List . */
private static Set < EObject > findAllEObjects ( final ResourceSet resourceSet ) { } }

implementation: final Set < EObject > list = new HashSet < EObject > ( ) ; for ( final Iterator < Notifier > i = resourceSet . getAllContents ( ) ; i . hasNext ( ) ; ) { final Notifier next = i . next ( ) ; if ( next instanceof EObject ) { list . add ( ( EObject ) next ) ; } } return list ;


signature:
public class AbstractEMFParser { /** * Sets the model directories to parse . If no list exists internally , it will be created if necessary .
 * @ param modelDirs
 * Array of model directories or NULL . */
protected final void setModelDirs ( final File ... modelDirs ) { } }

implementation: if ( modelDirs == null ) { this . modelDirs = null ; } else { this . modelDirs = new ArrayList < File > ( ) ; this . modelDirs . addAll ( Arrays . asList ( modelDirs ) ) ; }


signature:
public class AbstractEMFParser { /** * Sets the list of file extensions . If no list exists internally , it will be created if necessary .
 * @ param fileExtensions
 * Array of extensions for files to find ( " mymodel " , " java " , " class " , . . . ) */
protected final void setFileExtensions ( final String ... fileExtensions ) { } }

implementation: if ( fileExtensions == null ) { this . fileExtensions = null ; } else { this . fileExtensions = new ArrayList < String > ( ) ; this . fileExtensions . addAll ( Arrays . asList ( fileExtensions ) ) ; }


signature:
public class AbstractEMFParser { /** * Sets the model resources to parse . If no list exists internally , it will be created if necessary .
 * @ param modelResources
 * Array of model resources or NULL . */
protected final void setModelResources ( final URI ... modelResources ) { } }

implementation: if ( modelResources == null ) { this . modelResources = null ; } else { this . modelResources = new ArrayList < URI > ( ) ; this . modelResources . addAll ( Arrays . asList ( modelResources ) ) ; }


signature:
public class CSVRecordReader { /** * Reads the next row .
 * @ return { @ code true } if a record set could been read ,
 * { @ code false } on end of file .
 * @ throws IOException when the underlying Stream reports an error */
@ Override public final boolean nextRecord ( ) throws IOException { } }

implementation: final String line = reader . readLine ( ) ; if ( line == null ) { parts = null ; return false ; } final List < String > newParts = splitLine ( line ) ; parts = newParts . toArray ( new String [ newParts . size ( ) ] ) ; partIndex = 0 ; return true ;


signature:
public class RowFixture { /** * Sorts and compare two lists .
 * It is assumed that all items in { @ code expected } and { @ code computed }
 * are equal on the { @ code col - 1 } columns . */
private void multiLevelMatch ( List < FitRow > expected , List < Object > computed , int col ) { } }

implementation: boolean cantGoDeeper = col >= columnNames . length ; if ( cantGoDeeper ) { check ( expected , computed ) ; } else { boolean isComment = isComment ( col ) ; if ( isComment ) { multiLevelMatch ( expected , computed , col + 1 ) ; } else { groupAndMatch ( expected , computed , col ) ; } }


signature:
public class RowFixture { /** * Groups both lists by column { @ code col } . For every resulting group check if
 * there is a 1:1 or a 1:0 match . Otherwise , group further . */
private void groupAndMatch ( List < FitRow > expected , List < Object > computed , int col ) { } }

implementation: Map < Object , List < FitRow > > expectedMap = groupExpectedByColumn ( expected , col ) ; Map < Object , List < Object > > computedMap = groupComputedByColumn ( computed , col ) ; Set keys = union ( expectedMap . keySet ( ) , computedMap . keySet ( ) ) ; for ( Object key : keys ) { List < FitRow > expectedList = expectedMap . get ( key ) ; List < Object > computedList = computedMap . get ( key ) ; boolean isAmbiguous = hasMultipleEntries ( expectedList ) && hasMultipleEntries ( computedList ) ; if ( isAmbiguous ) { multiLevelMatch ( expectedList , computedList , col + 1 ) ; } else { check ( expectedList , computedList ) ; } }


signature:
public class RowFixture { /** * Compares two lists .
 * < ul >
 * < li > if { @ code expectedList } is empty , all { @ code computedList } items are surplus < / li >
 * < li > if { @ code computedList } is empty , all { @ code expectedList } items are missing < / li >
 * < li > otherwise , match the first rows and compare the rest recursively < / li >
 * < / ul >
 * @ param computedList Objects from { @ link # query ( ) } .
 * @ param expectedList Objects from HTML . */
protected void check ( List < FitRow > expectedList , List < Object > computedList ) { } }

implementation: if ( expectedList == null || expectedList . size ( ) == 0 ) { surplus . addAll ( computedList ) ; } else if ( computedList == null || computedList . size ( ) == 0 ) { missing . addAll ( expectedList ) ; } else { Object computedRow = computedList . remove ( 0 ) ; List < FitCell > expectedRow = expectedList . remove ( 0 ) . cells ( ) ; compareRow ( computedRow , expectedRow ) ; check ( expectedList , computedList ) ; }


signature:
public class RowFixture { /** * Compares two rows item by item using { @ link Fixture # check ( FitCell , ValueReceiver , String ) } .
 * Each cell will be marked as right , wrong , ignored or exception */
private void compareRow ( Object computedRow , List < FitCell > expectedCells ) { } }

implementation: for ( int i = 0 ; i < columnNames . length && expectedCells != null ; i ++ ) { try { ValueReceiver valueReceiver ; if ( isComment ( i ) ) { valueReceiver = null ; } else { valueReceiver = createReceiver ( computedRow , columnNames [ i ] ) ; } String columnParameter = FitUtils . saveGet ( i , columnParameters ) ; check ( expectedCells . get ( i ) , valueReceiver , columnParameter ) ; } catch ( NoSuchMethodException | NoSuchFieldException e ) { expectedCells . indexOf ( e ) ; } }


signature:
public class SubstVars { /** * This method performs property variable substitution on the specified
 * value . If the specified value contains the syntax
 * < tt > $ { & lt ; prop - name & gt ; } < / tt > , where < tt > & lt ; prop - name & gt ; < / tt > refers to
 * either a configuration property or a system property , then the
 * corresponding property value is substituted for the variable placeholder .
 * Multiple variable placeholders may exist in the specified value as well
 * as nested variable placeholders , which are substituted from inner most to
 * outer most . Configuration properties override system properties .
 * @ param val
 * The string on which to perform property substitution .
 * @ param currentKey
 * The key of the property being evaluated used to
 * detect cycles .
 * @ param cycleMap
 * Map of variable references used to detect nested cycles .
 * @ param configProps
 * Set of configuration properties .
 * @ return The value of the specified string after system property
 * substitution .
 * @ throws IllegalArgumentException
 * If there was a syntax error in the
 * property placeholder syntax or a recursive variable
 * reference . */
@ SuppressWarnings ( { } }

implementation:
"rawtypes" , "unchecked" } ) public static String substVars ( String val , String currentKey , Map cycleMap , Properties configProps ) throws IllegalArgumentException { // If there is currently no cycle map , then create
// one for detecting cycles for this invocation .
if ( cycleMap == null ) { cycleMap = new HashMap ( ) ; } // Put the current key in the cycle map .
cycleMap . put ( currentKey , currentKey ) ; // Assume we have a value that is something like :
// " leading $ { foo . $ { bar } } middle $ { baz } trailing "
// Find the first ending ' } ' variable delimiter , which
// will correspond to the first deepest nested variable
// placeholder .
int stopDelim = - 1 ; int startDelim = - 1 ; do { stopDelim = val . indexOf ( DELIM_STOP , stopDelim + 1 ) ; // If there is no stopping delimiter , then just return
// the value since there is no variable declared .
if ( stopDelim < 0 ) { return val ; } // Try to find the matching start delimiter by
// looping until we find a start delimiter that is
// greater than the stop delimiter we have found .
startDelim = val . indexOf ( DELIM_START ) ; // If there is no starting delimiter , then just return
// the value since there is no variable declared .
if ( startDelim < 0 ) { return val ; } while ( stopDelim >= 0 ) { int idx = val . indexOf ( DELIM_START , startDelim + DELIM_START . length ( ) ) ; if ( ( idx < 0 ) || ( idx > stopDelim ) ) { break ; } else if ( idx < stopDelim ) { startDelim = idx ; } } } while ( ( startDelim > stopDelim ) && ( stopDelim >= 0 ) ) ; // At this point , we have found a variable placeholder so
// we must perform a variable substitution on it .
// Using the start and stop delimiter indices , extract
// the first , deepest nested variable placeholder .
String variable = val . substring ( startDelim + DELIM_START . length ( ) , stopDelim ) ; // Verify that this is not a recursive variable reference .
if ( cycleMap . get ( variable ) != null ) { throw new IllegalArgumentException ( "recursive variable reference: " + variable ) ; } // Get the value of the deepest nested variable placeholder .
// Try to configuration properties first .
String substValue = ( configProps != null ) ? configProps . getProperty ( variable , null ) : null ; if ( substValue == null ) { // Ignore unknown property values .
substValue = System . getProperty ( variable , "" ) ; } // Remove the found variable from the cycle map , since
// it may appear more than once in the value and we don ' t
// want such situations to appear as a recursive reference .
cycleMap . remove ( variable ) ; // Append the leading characters , the substituted value of
// the variable , and the trailing characters to get the new
// value .
val = val . substring ( 0 , startDelim ) + substValue + val . substring ( stopDelim + DELIM_STOP . length ( ) , val . length ( ) ) ; // Now perform substitution again , since there could still
// be substitutions to make .
val = substVars ( val , currentKey , cycleMap , configProps ) ; // Return the value .
return val ;


signature:
public class ArrayTypeHandler { /** * Converts a { @ code String } into a { @ code Array } .
 * @ param s the { @ code String } to convert
 * @ return an { @ code Array } which contains { @ code s } */
@ Override public Object unsafeParse ( final String s ) throws ParseException { } }

implementation: final StringTokenizer t = new StringTokenizer ( s , "," ) ; final Object array = Array . newInstance ( componentAdapter . getType ( ) , t . countTokens ( ) ) ; for ( int i = 0 ; t . hasMoreTokens ( ) ; i ++ ) { Array . set ( array , i , componentAdapter . parse ( t . nextToken ( ) . trim ( ) ) ) ; } return array ;


signature:
public class ArrayTypeHandler { /** * Checks whether two Arrays { @ code a } and { @ code b } are
 * equal .
 * A type specific { @ code TypeAdapter } is used to compare the items .
 * @ param a first array
 * @ param b second array
 * @ return { @ code true } if all items are equal , { @ code false } otherwise */
@ SuppressWarnings ( "unchecked" ) @ Override public boolean unsafeEquals ( Object a , Object b ) { } }

implementation: final int length = Array . getLength ( a ) ; if ( length != Array . getLength ( b ) ) { return false ; } for ( int i = 0 ; i < length ; i ++ ) { if ( ! componentAdapter . unsafeEquals ( Array . get ( a , i ) , Array . get ( b , i ) ) ) { return false ; } } return true ;


signature:
public class LogEventAnalyzerFactory { /** * Creates a LogEventAnalyzer which is capable to analyze the events { @ code
 * events } using the condition defined in { @ code conditionCell } .
 * @ param validator the validator for the cell
 * @ param conditionCell cell which contains the condition
 * @ param events list of events to process @ return instance of LogEventAnalyzer
 * @ return A LogEventAnalyzer able to processing all parameters . */
public LogEventAnalyzer getLogEventAnalyzerFor ( Validator validator , FitCell conditionCell , LoggingEvent [ ] events ) { } }

implementation: return new LogEventAnalyzer ( validator , conditionCell , events ) ;


signature:
public class XspView { /** * Uses template engine to inject model and serialize view on HTTP response . If meta - view contains
 * { @ link # OPERATOR _ SERIALIZATION } property enable engine operators serialization .
 * @ param outputStream output stream of the HTTP response .
 * @ throws IOException if stream write operation fails . */
@ Override protected void serialize ( OutputStream outputStream ) throws IOException { } }

implementation:
// refrain to use HttpResponse # getWriter ( )
// this library always uses output stream since servlet response API does not allow mixing characters and bytes streams
Writer writer = new BufferedWriter ( new OutputStreamWriter ( outputStream , "UTF-8" ) ) ; TemplateEngine templateEngine = Classes . loadService ( TemplateEngine . class ) ; Template template = templateEngine . getTemplate ( meta . getTemplateFile ( ) ) ; boolean operatorSerialization = Boolean . parseBoolean ( meta . getProperty ( OPERATOR_SERIALIZATION ) ) ; if ( operatorSerialization ) { template . setProperty ( "js.template.serialize.operator" , true ) ; } // if model is null template serializes itself skipping injection operation
template . serialize ( model , writer ) ; // there is no need to flush response stream on error so no need for try / finally
writer . flush ( ) ;


signature:
public class StatementImpl { /** * Execute Results */
public < K , V > Map < K , V > executeMap ( ResultSetMapper < K > key , ResultSetMapper < V > value , Map < K , V > newMap ) throws java . sql . SQLException { } }

implementation: try ( ResultSetImpl rs = this . executeResult ( ) ) { while ( rs . next ( ) ) { K k = key . map ( rs ) ; V v = value . map ( rs ) ; newMap . put ( k , v ) ; } return newMap ; }


signature:
public class StatementImpl { /** * type IN ( @ types ) */
public void setStringArray ( String parameterName , String ... values ) throws java . sql . SQLException { } }

implementation: int arrayLen = this . getSql ( ) . getArrayLen ( parameterName ) ; AssertUtils . assertTrue ( values . length <= arrayLen ) ; for ( int i = 0 ; i < arrayLen ; i ++ ) { setString2 ( Sql . toParamName ( parameterName , i ) , ( i < values . length ) ? values [ i ] : null ) ; }


signature:
public class StatementImpl { /** * Set Nullable Parameters */
public void setBoolean2 ( String parameterName , Boolean value ) throws java . sql . SQLException { } }

implementation: if ( value == null ) { setNull ( parameterName , Types . BIT ) ; } else { setBoolean ( parameterName , value ) ; }


signature:
public class StatementImpl { /** * java . sql . Statement */
@ Override public long executeLargeUpdate ( java . lang . String sql , int [ ] columnIndexes ) throws java . sql . SQLException { } }

implementation: return this . stat . executeLargeUpdate ( sql , columnIndexes ) ;


signature:
public class ActivationUtils { /** * Checks if the arguments contains the argument < code > arg < / code > .
 * @ param args the arguments
 * @ param arg the argument to find
 * @ return < code > true < / code > if the */
public static boolean containsArgument ( String [ ] args , String arg ) { } }

implementation: if ( args == null || arg == null || arg . length ( ) == 0 || args . length == 0 ) { return false ; } else { for ( String a : args ) { if ( a . equalsIgnoreCase ( arg ) ) { return true ; } else if ( a . startsWith ( arg + "=" ) ) { return true ; } } return false ; }


signature:
public class ActivationUtils { /** * Gets the argument value .
 * < ul >
 * < li > for ' arg = value ' it returns ' value ' < / li >
 * < li > for ' arg value ' it returns ' value ' < / li >
 * @ param args the arguments
 * @ param arg the argument to find
 * @ return the argument value or < code > null < / code > if not found . */
public static String getArgumentValue ( String args [ ] , String arg ) { } }

implementation:
if ( args == null || arg == null || arg . length ( ) == 0 || args . length == 0 ) { return null ; } else { for ( int i = 0 ; i < args . length ; i ++ ) { String a = args [ i ] ; if ( a . equalsIgnoreCase ( arg ) ) { // Case ' arg value ' : Look for arg + 1;
if ( args . length > i + 1 ) { return args [ i + 1 ] ; } } else if ( a . startsWith ( arg + "=" ) ) { // Case ' arg = value ' : Parse the value
int index = a . indexOf ( '=' ) + 1 ; return a . substring ( index ) ; } } return null ; }


signature:
public class InstanceType { /** * Create an instance type from its string value . */
@ SuppressWarnings ( "unchecked" ) @ Override public < T > T asObject ( String string , Class < T > valueType ) throws IllegalArgumentException , ConverterException { } }

implementation: return ( T ) new InstanceType ( string ) ;


signature:
public class VelocityGenerator { /** * 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 */
protected final void merge ( final VelocityContext context , final String artifactName , final String templateName , final String filename ) throws GenerateException { } }

implementation:
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 ) ; } }


signature:
public class XmlArgumentsReader { /** * Handle XML input stream from HTTP request . This method expects a single formal parameter , current implementation
 * supporting { @ link Document } and { @ link InputStream } .
 * @ param httpRequest HTTP request ,
 * @ param formalParameters formal parameter types .
 * @ return arguments array .
 * @ throws IOException if reading from HTTP request input stream fails .
 * @ throws IllegalArgumentException if formal parameters does not contain exactly one type .
 * @ throws IllegalArgumentException if formal parameter type is parameterized .
 * @ throws IllegalArgumentException if formal parameter type is not supported by this method . */
@ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { } }

implementation: if ( formalParameters . length != 1 ) { throw new IllegalArgumentException ( "Bad parameters count. Should be exactly one but is |%d|." , formalParameters . length ) ; } if ( formalParameters [ 0 ] instanceof ParameterizedType ) { throw new IllegalArgumentException ( "Parameterized type |%s| is not supported." , formalParameters [ 0 ] ) ; } return new Object [ ] { read ( httpRequest . getInputStream ( ) , formalParameters [ 0 ] ) } ;


signature:
public class XmlArgumentsReader { /** * Process XML input stream accordingly requested type . Current implementation supports two type : XML { @ link Document } and
 * XML input stream .
 * @ param inputStream XML input stream ,
 * @ param type expected Java type .
 * @ return XML stream processing result .
 * @ throws IOException if XML stream reading fails .
 * @ throws IllegalArgumentException if requested Java type is not supported . */
@ Override public Object read ( InputStream inputStream , Type type ) throws IOException { } }

implementation: if ( Types . isKindOf ( type , Document . class ) ) { return documentBuilder . loadXML ( inputStream ) ; } else if ( Types . isKindOf ( type , InputStream . class ) ) { threadLocal . set ( inputStream ) ; return inputStream ; } else { throw new IllegalArgumentException ( "Unsupported formal parameter type |%s| for XML content type." , type ) ; }


signature:
public class ParameterizedTemplateParserConfig { /** * Returns the model directory .
 * @ return Model directory or NULL . */
public final File getModelDir ( ) { } }

implementation: if ( ( modelDir == null ) && ( modelPath != null ) ) { modelDir = Utils4J . getCanonicalFile ( new File ( modelPath ) ) ; } return modelDir ;


signature:
public class ParameterizedTemplateParserConfig { /** * Returns the template directory .
 * @ return Template directory or NULL . */
public final File getTemplateDir ( ) { } }

implementation: 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 ;


signature:
public class JoseUtils { /** * number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date / time */
public static Long toNumericDate ( Date value ) { } }

implementation: if ( value == null ) { return null ; } return DateUtils . clearMs ( value ) . getTime ( ) / 1000 ;


signature:
public class XmlValueWriter { /** * 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 . */
@ Override public void write ( HttpServletResponse httpResponse , Object value ) throws IOException { } }

implementation: final Document document = ( Document ) value ; document . serialize ( new OutputStreamWriter ( httpResponse . getOutputStream ( ) , "UTF-8" ) ) ;


signature:
public class WebViewFactory { /** * Configuration Property : set the initial URL .
 * This property is < b > mandatory < / b > .
 * If the browser is already created , this web view loads
 * this new url .
 * @ param url the url */
@ Property ( name = "url" ) public synchronized void setURL ( final String url ) { } }

implementation: this . m_url = url ; if ( m_browser != null ) { QApplication . invokeLater ( new Runnable ( ) { public void run ( ) { m_browser . open ( url ) ; } } ) ; }


signature:
public class WebViewFactory { /** * Starts the browser and loads the
 * set url in the web view . */
@ Validate public void start ( ) { } }

implementation: 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." ) ; } } ) ;


signature:
public class WebViewFactory { /** * Configures the application :
 * < ul >
 * < li > sets the application name ( default : ' akquinet ChameRIA ' ) < / li >
 * < li > sets the application version ( default : current web view factory version ) < / li >
 * < li > sets the application icon ( default : no icon ) < / li >
 * < / ul > */
private void configureApplication ( ) { } }

implementation:
if ( m_appName != null ) { QApplication . setApplicationName ( m_appName ) ; } else { QApplication . setApplicationName ( "akquinet ChameRIA" ) ; } if ( m_appVersion != null ) { QApplication . setApplicationVersion ( m_appVersion ) ; } else { QApplication . setApplicationVersion ( m_context . getBundle ( ) . getVersion ( ) . toString ( ) ) ; } if ( m_icon != null ) { QFile file = new QFile ( m_icon ) ; QIcon icon = new QIcon ( file . fileName ( ) ) ; QApplication . setWindowIcon ( icon ) ; } QApplication . setOrganizationName ( "akquinet A.G." ) ; // Configure the proxy
if ( m_proxyType != null ) { m_logger . warn ( "Set application proxy : " + m_proxyType ) ; if ( m_proxyHostName == null || m_proxyPort == 0 ) { m_logger . error ( "Cannot configure proxy : hostname or port not set : " + m_proxyHostName + ":" + m_proxyPort ) ; } else { QNetworkProxy proxy = new QNetworkProxy ( m_proxyType , m_proxyHostName , m_proxyPort ) ; QNetworkProxy . setApplicationProxy ( proxy ) ; m_logger . warn ( "Application proxy set " + m_proxyType + " on " + m_proxyHostName + ":" + m_proxyPort ) ; } }


signature:
public class WebViewFactory { /** * Configures the browser window .
 * @ param web the browser window */
private void configureWindow ( WebWindow web ) { } }

implementation:
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 ) ; }


signature:
public class WebViewFactory { /** * Print callback .
 * Checks if the print feature is enabled . If so , launch the system
 * print job .
 * @ param view the view to print */
public void print ( QWebView view ) { } }

implementation:
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" ) ; }


signature:
public class WebViewFactory { /** * Save callback ( for unsupported content ) .
 * Checks if the ' save ' feature is enabled . If so , launch the system
 * save dialog .
 * @ param reply the url to save */
public void save ( QNetworkReply reply ) { } }

implementation: if ( m_download ) { String fn = QFileDialog . getSaveFileName ( ) ; if ( fn != null && fn . length ( ) > 0 ) { m_logger . info ( "File name : " + fn ) ; try { URL u = new URL ( reply . url ( ) . toString ( ) ) ; FileOutputStream out = new FileOutputStream ( new File ( fn ) ) ; InputStream in = u . openStream ( ) ; write ( in , out ) ; } catch ( IOException e ) { m_logger . error ( "Cannot download file " + e . getMessage ( ) , e ) ; } } else { m_logger . warn ( "No File Name - Download request cancelled" ) ; } } else { m_logger . warn ( "Download disabled" ) ; }


signature:
public class WebViewFactory { /** * 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 */
public static void write ( InputStream in , OutputStream out ) throws IOException { } }

implementation: byte [ ] b = new byte [ 4096 ] ; for ( int n ; ( n = in . read ( b ) ) != - 1 ; ) { out . write ( b , 0 , n ) ; } in . close ( ) ; out . close ( ) ;


signature:
public class WebViewFactory { /** * Open callback ( < code > window . open < / code > ) .
 * Checks if the ' open new window ' feature is enabled . If so , creates the
 * web view */
public QWebView openWindow ( ) { } }

implementation:
if ( m_window_open ) { // We share the same factory
QWebView newwindow = new ChameriaWebView ( this ) ; return newwindow ; } else { m_logger . warn ( "Open new window disabled" ) ; return null ; }


signature:
public class ScopeProxyHandler { /** * 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 . */
@ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { } }

implementation: T instance = appFactory . getInstance ( interfaceClass ) ; return method . invoke ( instance , args ) ;


signature:
public class RequestContext { /** * 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 . */
public void attach ( HttpServletRequest httpRequest , HttpServletResponse httpResponse ) { } }

implementation:
// 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 ;


signature:
public class RequestContext { /** * Detach request context instance from HTTP servlet request . Invoking getters on this instance after detaching is
 * considered a bug . */
public void detach ( ) { } }

implementation: attached = false ; locale = null ; securityDomain = null ; cookies = null ; requestPath = null ; requestURL = null ;


signature:
public class RequestContext { /** * Get request cookies .
 * @ return request cookies .
 * @ throws BugError if attempt to use this getter on instance not attached to a HTTP servlet request . */
public Cookies getCookies ( ) { } }

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


signature:
public class RequestContext { /** * Get HTTP session this request context is part of or null if session is not or could not be created . If
 * < code > create < / code > flag is not provided this method return current HTTP session as it is , that is , return it if already
 * created or null if not .
 * If < code > create < / code > flag is present and is true this method returns current HTTP session , if there is one associated
 * with current request , or create a new one . This method never returns null if requested to create session but can throw
 * illegal state exception if attempt to create session after response commit .
 * @ param create optional create flag .
 * @ return current HTTP session possible null .
 * @ throws IllegalStateException if attempt to create new HTTP session after response was committed .
 * @ throws BugError if attempt to use this getter on instance not attached to a HTTP servlet request . */
public HttpSession getSession ( boolean ... create ) { } }

implementation:
assertAttached ( ) ; if ( create . length == 0 ) { return httpRequest . getSession ( ) ; } // if create flag is true next call can throw IllegalStateException if HTTP response is committed
return httpRequest . getSession ( create [ 0 ] ) ;


signature:
public class RequestContext { /** * Dump this request context state to error logger . If this instance is not attached this method is NOP . */
public void dump ( ) { } }

implementation: 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 ( ) ) ;


signature:
public class SetupFixture { /** * Registers the { @ link TypeHandler } which is provided by
 * { @ code className } . After processing this row , the TypeAdapter
 * will be automatically used when the destination type matches
 * { @ link TypeHandler # getType ( ) } .
 * @ param className fully qualified name of a class
 * @ throws Exception propagated to fit , in case of unknown classes ,
 * permission errors , etc . */
@ SuppressWarnings ( "unchecked" ) public void load ( final String className ) throws Exception { } }

implementation: Class < ? extends TypeHandler < ? > > clazz = ( Class < ? extends TypeHandler < ? > > ) Class . forName ( className ) ; TypeHandlerFactory helper = DependencyManager . getOrCreate ( TypeHandlerFactory . class ) ; helper . register ( clazz ) ;


signature:
public class Observer { /** * Collect invocation meters from application managed classes .
 * @ return application invocation meters . */
private static List < InvocationMeter > getMeters ( ) { } }

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


signature:
public class EventStream { /** * Configure events stream instance from configuration object .
 * @ param config event stream configuration object . */
protected void config ( EventStreamConfig config ) { } }

implementation: if ( config . hasSecretKey ( ) ) { secretKey = config . getSecretKey ( ) ; } if ( config . hasKeepAlivePeriod ( ) ) { keepAlivePeriod = config . getKeepAlivePeriod ( ) ; } parameters = config . getParameters ( ) ;


signature:
public class EventStream { /** * Push event to this events stream client . This method just stores the event on { @ link # eventsQueue events queue } being
 * executed into invoker thread . This events stream thread is blocked on the events queue ; after this method execution it
 * will unblock and process the event , see { @ link # loop ( ) } method .
 * Queue offer operation is guarded by { @ link # EVENTS _ QUEUE _ PUSH _ TIMEOUT } . This timeout can occur only in a very improbable
 * condition of events flood combined with system resources starvation . For this reason there is no attempt to recover ;
 * event is simple lost with warning on application logger .
 * @ param event event instance to push on event stream .
 * @ throws BugError if trying to use this method after stream close . */
public void push ( Event event ) { } }

implementation:
if ( ! active . get ( ) ) { throw new BugError ( "Event stream |%s| is closed." , this ) ; } // BlockingQueue is thread safe so we do not need to synchronize this method
try { if ( ! eventsQueue . offer ( event , EVENTS_QUEUE_PUSH_TIMEOUT , TimeUnit . MILLISECONDS ) ) { log . warn ( "Timeout trying to push event on events queue. Event |%s| not processed." , event ) ; } } catch ( InterruptedException unused ) { log . warn ( "Thread interruption on event stream |%s| while trying to push event to queue. Event |%s| not processed." , this , event ) ; Thread . currentThread ( ) . interrupt ( ) ; }


signature:
public class EventStream { /** * Close this event stream loop and waits for associated { @ link EventStreamServlet } exit . */
@ Override public void close ( ) { } }

implementation: if ( ! active . get ( ) ) { return ; } log . debug ( "Closing event stream |%s| ..." , this ) ; push ( new ShutdownEvent ( ) ) ; active . set ( false ) ; log . debug ( "Event stream |%s| was closed." , this ) ;


signature:
public class EventStream { /** * Set the host address for client connected to this event stream .
 * @ param remoteHost client remote host address . */
protected void setRemoteHost ( String remoteHost ) { } }

implementation: if ( string == null ) { string = Strings . concat ( '#' , STREAM_ID ++ , ':' , remoteHost ) ; }


signature:
public class EventStream { /** * Event stream main loop repeated for every event . Waits for an event and push it to the client via { @ link # writer } , writer
 * initialized by { @ link EventStreamServlet } on this event stream creation . Note that this logic is executed into HTTP
 * request thread ; it blocks the thread till an event become available . This method always returns true allowing event
 * stream to continue . It returns false only when got { @ link ShutdownEvent } , pushed on queue by { @ link # close ( ) } method or
 * there is an error on print writer . Checking for print writer errors is especially useful to detect that remote client
 * closes its socket and to gracefully close this stream and release parent servlet instance .
 * Also this method takes care to periodically send keep alive events , see { @ link # keepAlivePeriod } . Keep alive is used to
 * ensure server side and client logic that peer is still running and to avoid connection drop due to routers idle
 * connection timeout .
 * @ return true if event stream should continue running . */
protected boolean loop ( ) { } }

implementation:
Event event = null ; try { event = eventsQueue . poll ( keepAlivePeriod , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException unused ) { if ( ! active . get ( ) ) { log . debug ( "Events stream |%s| thread is interrupted. Break events stream loop." , this ) ; return false ; } // in a perfect world , now would be the right moment to stop the events stream , returning false . . .
// but i ' m not sure interruption occurs only when current thread is interrupted
// for now i play safe , allowing events stream to continue and use shutdown event to break it
log . warn ( "Events stream |%s| thread is interrupted. Continue events stream loop." , this ) ; return true ; } if ( event == null ) { // we are here due to keep - alive period expiration
// returns true to signal event stream should continue
sendKeepAlive ( ) ; log . debug ( "Keep-alive was sent to event stream |%s|." , this ) ; return ! writer . checkError ( ) ; } // close method puts this event into queue ; returns false to break this events stream loop
if ( event instanceof ShutdownEvent ) { log . debug ( "Got shutdown event. Break event stream loop." ) ; return false ; } sendEvent ( event ) ; onSent ( event ) ; log . debug ( "Event |%s| was sent to event stream |%s|." , event , this ) ; return ! writer . checkError ( ) ;


signature:
public class EventStream { /** * 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 . */
protected < T > T getParameter ( String name , Class < T > type ) { } }

implementation: 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 ) ;


signature:
public class EventStream { /** * Send event instance to this event stream consumer . Compile a W3C Server - Sent event from < code > event < / code > instance
 * argument and write it to this { @ link # writer } . This event stream implementation does not use all W3C server - sent event
 * fields : only < code > event < / code > and < code > data < / code > , as folows :
 * < ul >
 * < li > event field stores event argument canonical class name ,
 * < li > data field value is event argument instance serialized JSON .
 * < / ul >
 * Just for those curious here is an sample of a serialized hypothetical event , as it is on wire :
 * < pre >
 * event : bb . hub . event . NotificationCRLF
 * data : { " id " : 213 , " title " : " Baby Server Admin " , " text " : " Baby server was stopped . " , " timestamp " : " 2014-04-10T19:07:05Z " , " priority " : " DEFAULT " } CRLF
 * CRLF
 * < / pre >
 * @ param event event instance . */
protected void sendEvent ( Event event ) { } }

implementation:
write ( "data:" ) ; if ( secretKey == null ) { json . serialize ( writer , event ) ; } else { try { Cipher cipher = Cipher . getInstance ( secretKey . getAlgorithm ( ) ) ; cipher . init ( Cipher . ENCRYPT_MODE , secretKey ) ; // this overload of doFinal from Cipher class is able to perform single step encrypting
// excerpt from API :
// Encrypts or decrypts data in a single - part operation , or finishes a multiple - part operation .
byte [ ] encryptedMessage = cipher . doFinal ( json . serialize ( event ) ) ; // encode encrypted event message with Base64 since content type should be text
write ( Base64 . encode ( encryptedMessage ) ) ; } catch ( InvalidKeyException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e ) { // we step here only for bugs on encryption provider :
// secret key size is incorrect or key is not properly initialized
// single step encryption using directly Cipher # doFinal is supposed to process all input at once
// missing JVM default padding mechanism
// bad padding occurring on encryption
throw new BugError ( e ) ; } catch ( NoSuchAlgorithmException e ) { throw new BugError ( "Missing support for |%s| cryptographic algorithm." , secretKey . getAlgorithm ( ) ) ; } } // end data field
crlf ( ) ; // single end of line is the mark for event end
crlf ( ) ; flush ( ) ;


signature:
public class FileSystemDirectoryHelper { /** * 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 . */
public String removePrefix ( final String path , final String prefix ) { } }

implementation: String pathWithoutPrefix = path ; if ( pathWithoutPrefix . startsWith ( prefix ) ) { pathWithoutPrefix = pathWithoutPrefix . substring ( prefix . length ( ) ) ; while ( pathWithoutPrefix . startsWith ( "/" ) || pathWithoutPrefix . startsWith ( "\\" ) ) { pathWithoutPrefix = pathWithoutPrefix . substring ( 1 ) ; } } return pathWithoutPrefix ;


signature:
public class FileSystemDirectoryHelper { /** * Checks whether { @ code subDir } is a sub directory of { @ code parentDir } .
 * Note : the comparison is case sensitive .
 * @ param subDir potential sub directory
 * @ param parentDir parent directory
 * @ return { @ code true } if { @ code subDir } is a subDirectory of
 * { @ code parentDir } , false otherwise .
 * @ throws java . io . IOException Thrown when paths cannot be normalized . */
public boolean isSubDir ( final File subDir , final File parentDir ) throws IOException { } }

implementation: int parentDirLength = parentDir . getCanonicalFile ( ) . getAbsolutePath ( ) . length ( ) ; File currentDir = subDir . getCanonicalFile ( ) . getAbsoluteFile ( ) ; while ( currentDir . getAbsolutePath ( ) . length ( ) > parentDirLength ) { currentDir = currentDir . getParentFile ( ) ; } return currentDir . equals ( parentDir . getAbsoluteFile ( ) ) ;


signature:
public class FileSystemDirectoryHelper { /** * Returns all directory paths between { @ code fromDir } and { @ code toDir } .
 * @ param fromDir directory to start from
 * @ param toDir last directory path
 * @ return an array of all generated paths
 * @ throws java . io . IOException Thrown when paths cannot be normalized . */
public File [ ] getParentDirs ( final File fromDir , final File toDir ) throws IOException { } }

implementation: List < File > result = new LinkedList < > ( ) ; final File fromDirCanonical = fromDir . getCanonicalFile ( ) ; for ( File current = toDir . getCanonicalFile ( ) . getAbsoluteFile ( ) ; ! current . equals ( fromDirCanonical ) ; current = current . getParentFile ( ) ) { result . add ( 0 , current ) ; } return result . toArray ( new File [ result . size ( ) ] ) ;


signature:
public class FileSystemDirectoryHelper { /** * 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 */
public File getCommonDir ( final File dir1 , final File dir2 ) throws IOException { } }

implementation: 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 ;


signature:
public class FileSystemDirectoryHelper { /** * 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 } */
public String abs2rel ( final String basePath , final String absPath ) { } }

implementation:
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 ( ) ;


signature:
public class FileSystemDirectoryHelper { /** * 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 */
public File rel2abs ( final String basePath , final String relPath ) { } }

implementation: 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 ( ) ) ;


signature:
public class FileSystemDirectoryHelper { /** * Counts the number of directories in a given path .
 * @ param path the path to analyze
 * @ return number of directories */
public int dirDepth ( final File path ) { } }

implementation: final String stringPath = path . getPath ( ) ; return stringPath . length ( ) - stringPath . replaceAll ( "[/\\\\]" , "" ) . length ( ) ;


signature:
public class AppServlet { /** * Servlet life cycle callback executed at this servlet instance initialization . Mainly takes care to initialize parent
 * container reference . If there is no servlet context attribute with the name { @ link TinyContainer # ATTR _ INSTANCE } this
 * initialization fails with servlet permanently unavailable .
 * Parent container instance has application life span and its reference is valid for entire life span of this servlet
 * instance .
 * @ param config servlet configuration object .
 * @ throws UnavailableException if tiny container is not properly initialized . */
@ Override public void init ( ServletConfig config ) throws UnavailableException { } }

implementation: container = ( ContainerSPI ) config . getServletContext ( ) . getAttribute ( TinyContainer . ATTR_INSTANCE ) ; if ( container == null ) { log . fatal ( "Tiny container instance not properly created, probably misconfigured. Servlet |%s| permanently unvailable." , config . getServletName ( ) ) ; throw new UnavailableException ( "Tiny container instance not properly created, probably misconfigured." ) ; } servletName = Strings . concat ( config . getServletContext ( ) . getServletContextName ( ) , '#' , config . getServletName ( ) ) ; log . trace ( "Initialize servlet |%s|." , servletName ) ;


signature:
public class AppServlet { /** * Prepare execution context and delegates the actual HTTP request processing to abstract handler . Initialize request
 * context bound to current thread and delegates { @ link # handleRequest ( RequestContext ) } . After request handler execution
 * takes care to cleanup request context .
 * This method also initialize logger context , see { @ link # logContext } with remote address of current request so that
 * logging utility can include contextual diagnostic data into log messages . Just before exiting , this service request
 * cleanups the logger context .
 * @ throws IOException if reading from request or writing to response fail .
 * @ throws ServletException for fails on executing servlet container services . */
@ Override protected void service ( HttpServletRequest httpRequest , HttpServletResponse httpResponse ) throws IOException , ServletException { } }

implementation:
// push context path and remote address of the requested processed by this thread to logger diagnostic context
logContext . put ( LOG_CONTEXT_APP , httpRequest . getContextPath ( ) . isEmpty ( ) ? TinyContainer . ROOT_CONTEXT : httpRequest . getContextPath ( ) . substring ( 1 ) ) ; logContext . put ( LOG_CONTEXT_IP , httpRequest . getRemoteHost ( ) ) ; logContext . put ( LOG_CONTEXT_ID , Integer . toString ( requestID . getAndIncrement ( ) , Character . MAX_RADIX ) ) ; if ( isEmptyUriRequest ( httpRequest ) ) { log . debug ( "Empty URI request for |%s|. Please check for <img> with empty 'src' or <link>, <script> with empty 'href' in HTML source or script resulting in such condition." , httpRequest . getRequestURI ( ) ) ; return ; } String requestURI = httpRequest . getRequestURI ( ) ; long start = System . currentTimeMillis ( ) ; Factory . bind ( container ) ; // request context has THREAD scope and this request thread may be reused by servlet container
// takes care to properly initialize request context for every HTTP request
RequestContext context = container . getInstance ( RequestContext . class ) ; context . attach ( httpRequest , httpResponse ) ; log . trace ( "Processing request |%s|." , requestURI ) ; try { handleRequest ( context ) ; } catch ( IOException | ServletException | Error | RuntimeException t ) { // last line of defense ; dump request context and throwable then dispatch exception to servlet container
// servlet container will generate response page using internal templates or < error - page > , if configured
dumpError ( context , t ) ; throw t ; } finally { log . trace ( "%s %s processed in %d msec." , httpRequest . getMethod ( ) , context . getRequestURL ( ) , System . currentTimeMillis ( ) - start ) ; // cleanup remote address from logger context and detach request context instance from this request
logContext . clear ( ) ; context . detach ( ) ; }


signature:
public class AppServlet { /** * Detect self - referenced request URI . It seems there are browsers considering empty string as valid URL pointing to current
 * loaded page . If we have an < code > img < / code > element with empty < code > src < / code > attribute browser will try to load that
 * image from current URL , that is , the content of current page . This means is possible to invoke a controller many times
 * for a single page request .
 * To avoid such condition check if this request comes from the same page , i . e . referrer is current request . Note that this
 * is also true for < code > link < / code > and < code > script < / code > with empty < code > href < / code > . Finally worthy to mention is
 * that this check is not performed on request accepting < code > text / html < / code > .
 * @ param httpRequest HTTP request .
 * @ return true only this request is a < code > GET < / code > and referrer is request itself . */
private static boolean isEmptyUriRequest ( HttpServletRequest httpRequest ) { } }

implementation: if ( ! "GET" . equals ( httpRequest . getMethod ( ) ) ) { return false ; } String acceptValue = httpRequest . getHeader ( HttpHeader . ACCEPT ) ; if ( acceptValue != null && acceptValue . contains ( ContentType . TEXT_HTML . getMIME ( ) ) ) { return false ; } String referer = httpRequest . getHeader ( HttpHeader . REFERER ) ; if ( referer == null ) { return false ; } StringBuilder uri = new StringBuilder ( httpRequest . getRequestURI ( ) ) ; String query = httpRequest . getQueryString ( ) ; if ( query != null ) { if ( query . charAt ( 0 ) != '?' ) { uri . append ( '?' ) ; } uri . append ( query ) ; } return referer . toLowerCase ( ) . endsWith ( uri . toString ( ) . toLowerCase ( ) ) ;


signature:
public class AppServlet { /** * Send unauthorized access response . This method send back a response with status code
 * { @ link HttpServletResponse # SC _ UNAUTHORIZED } and response header { @ link HttpHeader # WWW _ AUTHENTICATE } set to basic
 * authentication method and { @ link ContainerSPI # getLoginRealm ( ) } authentication realm .
 * If request is from an agent using XHR this method behaves a little different . XHR specification mandates that
 * unauthorized access to be handled transparently by client agent that usually displays client agent login form , not very
 * well integrated with application . Below is a snippet from this framework script library .
 * For not authorized XHR requests this method sends { @ link HttpServletResponse # SC _ OK } and custom response header
 * { @ link HttpHeader # X _ HEADER _ LOCATION } set to application login page , see { @ link ContainerSPI # getLoginPage ( ) } . Client
 * script can handle this response and redirect to given login page .
 * < pre >
 * var redirect = this . _ request . getResponseHeader ( & quot ; X - JSLIB - Location & quot ; ) ;
 * if ( redirect ) {
 * WinMain . assign ( redirect ) ;
 * < / pre >
 * Anyway , if application is not configured with login page , for rejected XHR requests this method still uses standard
 * { @ link HttpServletResponse # SC _ UNAUTHORIZED } .
 * @ param context current request context . */
protected static void sendUnauthorized ( RequestContext context ) { } }

implementation:
final ContainerSPI container = context . getContainer ( ) ; final HttpServletResponse httpResponse = context . getResponse ( ) ; if ( httpResponse . isCommitted ( ) ) { log . fatal ( "Abort HTTP transaction. Attempt to send reponse after response already commited." ) ; return ; } log . error ( "Reject unauthorized request for private resource or service: |%s|." , context . getRequestURI ( ) ) ; String loginPage = container . getLoginPage ( ) ; if ( HttpHeader . isXHR ( context . getRequest ( ) ) && loginPage != null ) { // XMLHttpRequest specs mandates that redirection codes to be performed transparently by user agent
// this means redirect from server does not reach script counterpart
// as workaround uses 200 OK and X - JSLIB - Location extension header
log . trace ( "Send X-JSLIB-Location |%s| for rejected XHR request: |%s|" , container . getLoginPage ( ) , context . getRequestURI ( ) ) ; httpResponse . setStatus ( HttpServletResponse . SC_OK ) ; httpResponse . setHeader ( HttpHeader . X_HEADER_LOCATION , container . getLoginPage ( ) ) ; return ; } log . trace ( "Send WWW-Authenticate |Basic realm=%s| for rejected request: |%s|" , container . getLoginRealm ( ) , context . getRequestURI ( ) ) ; httpResponse . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; httpResponse . setHeader ( HttpHeader . WWW_AUTHENTICATE , String . format ( "Basic realm=%s" , container . getLoginRealm ( ) ) ) ;


signature:
public class AppServlet { /** * Send response for bad request with request URI as message . This utility method is used when a request URI is not well
 * formed , as expected by concrete servlet implementation . It dumps request context and delegates servlet container ,
 * { @ link HttpServletResponse # sendError ( int , String ) } to send { @ link HttpServletResponse # SC _ BAD _ REQUEST } .
 * @ param context request context .
 * @ throws IOException if writing to HTTP response fails . */
protected static void sendBadRequest ( RequestContext context ) throws IOException { } }

implementation: log . error ( "Bad request format for resource or service: |%s|." , context . getRequestURI ( ) ) ; context . dump ( ) ; context . getResponse ( ) . sendError ( HttpServletResponse . SC_BAD_REQUEST , context . getRequestURI ( ) ) ;


signature:
public class AppServlet { /** * Send response for resource or service not found , containing the exception that describes missing entity . This method
 * sends back exception object wrapped in { @ link RemoteException } . Response is encoded JSON and status code is
 * { @ link HttpServletResponse # SC _ NOT _ FOUND } .
 * @ param context current request context ,
 * @ param exception exception describing missing entity .
 * @ throws IOException if writing to response stream fails . */
protected static void sendNotFound ( RequestContext context , Exception exception ) throws IOException { } }

implementation: log . error ( "Request for missing resource or service: |%s|." , context . getRequestURI ( ) ) ; sendJsonObject ( context , new RemoteException ( exception ) , HttpServletResponse . SC_NOT_FOUND ) ;


signature:
public class AppServlet { /** * Send server error response with given exception serialized JSON . This utility method dumps stack trace and request
 * context to application logger and send back throwable object . Response is encoded JSON and status code is
 * { @ link HttpServletResponse # SC _ INTERNAL _ SERVER _ ERROR } . If given exception argument is { @ link InvocationException } or
 * { @ link InvocationTargetException } extract the cause .
 * There is a special case for { @ link BusinessException } . This exception signals broken business constrain and is send back
 * also as JSON object but with status code { @ link HttpServletResponse # SC _ BAD _ REQUEST } . Also does not dump exception stack
 * trace or request context .
 * @ param context current request context ,
 * @ param throwable exception describing server error .
 * @ throws IOException if writing to response stream fails . */
protected static void sendError ( RequestContext context , Throwable throwable ) throws IOException { } }

implementation:
if ( throwable instanceof InvocationException && throwable . getCause ( ) != null ) { throwable = throwable . getCause ( ) ; } if ( throwable instanceof InvocationTargetException ) { throwable = ( ( InvocationTargetException ) throwable ) . getTargetException ( ) ; } if ( throwable instanceof BusinessException ) { // business constrains exception is generated by user space code and sent to client using HTTP response
// status 400 - HttpServletResponse . SC _ BAD _ REQUEST , as JSON serialized object
log . debug ( "Send business constrain exception |%d|." , ( ( BusinessException ) throwable ) . getErrorCode ( ) ) ; sendJsonObject ( context , throwable , HttpServletResponse . SC_BAD_REQUEST ) ; } else { dumpError ( context , throwable ) ; sendJsonObject ( context , new RemoteException ( throwable ) , HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; }


signature:
public class AppServlet { /** * Dump throwable stack trace and request context to application logger .
 * @ param context request context ,
 * @ param throwable throwable to dump stack trace for . */
protected static void dumpError ( RequestContext context , Throwable throwable ) { } }

implementation: log . dump ( "Error on HTTP request:" , throwable ) ; context . dump ( ) ;


signature:
public class AppServlet { /** * 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 . */
protected static void sendJsonObject ( RequestContext context , Object object , int statusCode ) throws IOException { } }

implementation: 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 ( ) ;


signature:
public class ParameterizedTemplateModels { /** * Adds another template to the list . If the list does not exist , it will be created .
 * @ param paramTemplate
 * Template to add - Cannot be NULL . */
public final void addParamTemplate ( final ParameterizedTemplateModel paramTemplate ) { } }

implementation: if ( paramTemplates == null ) { paramTemplates = new ArrayList < ParameterizedTemplateModel > ( ) ; } paramTemplates . add ( paramTemplate ) ;


signature:
public class ParameterizedTemplateModels { /** * 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 . */
public final void addParamTemplates ( final List < ParameterizedTemplateModel > list ) { } }

implementation: if ( list != null ) { for ( final ParameterizedTemplateModel template : list ) { addParamTemplate ( template ) ; } }


signature:
public class ParameterizedTemplateModels { /** * Initalizes the object .
 * @ param context
 * Current context .
 * @ param vars
 * Variables to use . */
public final void init ( final SrcGen4JContext context , final Map < String , String > vars ) { } }

implementation: if ( paramTemplates != null ) { for ( final ParameterizedTemplateModel paramTemplate : paramTemplates ) { paramTemplate . init ( context , vars ) ; } }


signature:
public class ParameterizedTemplateModels { /** * 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 . */
public final List < ParameterizedTemplateModel > findReferencesTo ( final File templateDir , final File templateFile ) { } }

implementation: 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 ;


signature:
public class StringBuilderTypeHandler { /** * Checks whether two StringBuilder { @ code a } and { @ code b } are
 * equal .
 * This method removes whitespaces around both strings first .
 * @ param a first StringBuilder
 * @ param b second StringBuilder
 * @ return true if they are equal or both are null , false otherwise */
@ Override public final boolean unsafeEquals ( final StringBuilder a , Object b ) { } }

implementation: return a . toString ( ) . trim ( ) . equals ( b . toString ( ) . trim ( ) ) ;


signature:
public class StreamValueWriter { /** * Write bytes to output stream of HTTP response . This method invokes { @ link StreamHandler # invokeHandler ( OutputStream ) } with
 * HTTP response output stream . Stream handler instance is created by application and allows application logic access to
 * HTTP response stream .
 * @ param httpResponse HTTP response ,
 * @ param value object value is a stream handler instance created by application code .
 * @ throws IOException if writing to HTTP response output stream fails . */
@ Override public void write ( HttpServletResponse httpResponse , Object value ) throws IOException { } }

implementation: ( ( StreamHandler < ? > ) value ) . invokeHandler ( httpResponse . getOutputStream ( ) ) ;


signature:
public class ElementView { /** * Controls whether a save button is shown and fields are editable .
 * @ param val Turns the feature on or off . */
public void setSaveEnabled ( boolean val ) { } }

implementation: saveButton . setVisible ( val ) ; setReadOnly ( ! val ) ; entityForm . setReadOnly ( ! val ) ;


signature:
public class ElementView { /** * Deletes the element . */
protected void delete ( ) { } }

implementation:
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 ) ) ; } } } ) ;


signature:
public class ElementView { /** * 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 . */
protected void onDelete ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { } }

implementation: endpoint . delete ( ) ; eventBus . post ( new ElementDeletedEvent < > ( endpoint ) ) ;


signature:
public class TargetFile { /** * Replaces variables ( if defined ) in the path , name and arguments .
 * @ param vars
 * Variables to use . */
public final void init ( final Map < String , String > vars ) { } }

implementation: path = Utils4J . replaceVars ( path , vars ) ; name = Utils4J . replaceVars ( name , vars ) ; if ( arguments != null ) { for ( final Argument argument : arguments ) { argument . init ( vars ) ; } }


signature:
public class FileInformation { /** * Opens the file and returns a { @ code BufferedReader } object using
 * the given encoding .
 * @ param encoding the encoding to use
 * @ return the open file as { @ code BufferdReader }
 * @ throws IOException thrown if the file could not be read */
public BufferedReader openBufferedReader ( final String encoding ) throws IOException { } }

implementation: final InputStream fis = openInputStream ( ) ; final InputStreamReader isr = new InputStreamReader ( fis , encoding ) ; return new BufferedReader ( isr ) ;


signature:
public class LocalInstanceFactory { /** * 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 < code > args < / code > argument is not of types and number required by constructor .
 * @ throws InvocationException if constructor execution fails . */
@ SuppressWarnings ( "unchecked" ) @ Override public < T > T newInstance ( ManagedClassSPI managedClass , Object ... args ) { } }

implementation:
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 ;


signature:
public class PTGenHelper { /** * Creates and initializes a SrcGen4J configuration from a configuration file that contains ONLY generators / parsers of type
 * { @ link ParameterizedTemplateParser } and { @ link ParameterizedTemplateGenerator } .
 * @ param context
 * Current context - Cannot be NULL .
 * @ param configFile
 * XML configuration file to read - Cannot be NULL .
 * @ return New configuration instance .
 * @ throws UnmarshalObjectException
 * Error reading the configuration . */
public static SrcGen4JConfig createAndInit ( final SrcGen4JContext context , final File configFile ) throws UnmarshalObjectException { } }

implementation: try { final JaxbHelper helper = new JaxbHelper ( ) ; final SrcGen4JConfig config = helper . create ( configFile , JAXBContext . newInstance ( SrcGen4JConfig . class , VelocityGeneratorConfig . class , ParameterizedTemplateParserConfig . class , ParameterizedTemplateGeneratorConfig . class ) ) ; config . init ( context , Utils4J . getCanonicalFile ( configFile . getParentFile ( ) ) ) ; return config ; } catch ( final JAXBException ex ) { throw new UnmarshalObjectException ( "Error reading the configuration: " + configFile , ex ) ; }


signature:
public class PKIUtils { /** * PEM : Privacy - enhanced Electronic Mail */
public static String toPemEncoded ( byte [ ] der , String label ) { } }

implementation: StringWriter pem = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( pem ) ; pw . append ( "-----BEGIN " ) . append ( label ) . println ( "-----" ) ; pw . write ( new String ( Base64Delegate . getDefault ( ) . mimeEncode ( der ) , CharsetUtils . US_ASCII ) ) ; pw . println ( ) ; pw . append ( "-----END " ) . append ( label ) . println ( "-----" ) ; pw . close ( ) ; return pem . toString ( ) ;


signature:
public class HeaderUtils { /** * Returns all Link headers listed in an { @ link HttpResponse } .
 * @ param response The response to check for Link headers .
 * @ return The Link headers found . */
public static Iterable < LinkHeader > getLinkHeaders ( HttpResponse response ) { } }

implementation: return stream ( response . getHeaders ( "Link" ) ) . flatMap ( x -> stream ( x . getElements ( ) ) . map ( LinkHeader :: new ) ) . collect ( toList ( ) ) ;


signature:
public class FormUrlArgumentsReader { /** * Reads invocation arguments from HTTP request URL parameters accordingly formal parameters list . This arguments reader
 * implementation delegates { @ link QueryParametersParser } for URL parameters parsing .
 * @ param httpRequest HTTP request ,
 * @ param formalParameters formal parameters .
 * @ return arguments array .
 * @ throws IOException if reading from request input stream fails .
 * @ throws IllegalArgumentException if arguments from URL query parameters cannot be parsed . */
@ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { } }

implementation: try { QueryParametersParser queryParameters = new QueryParametersParser ( httpRequest . getInputStream ( ) ) ; return queryParameters . getArguments ( formalParameters ) ; } catch ( SyntaxException e ) { throw new IllegalArgumentException ( e ) ; }


signature:
public class FitResultTable { /** * Saves the result < code > result < / code > of the file { @ code file } .
 * @ param file filename to identify the result
 * @ param result results */
@ Override public void put ( final File file , final Counts result ) { } }

implementation: FileCount fileCount = new FileCount ( file , result ) ; if ( results . contains ( fileCount ) ) { results . remove ( fileCount ) ; } results . add ( fileCount ) ;


signature:
public class FitResultTable { /** * Returns the { @ code Counts } of a filename .
 * @ param file filename to look up
 * @ return { @ code Counts } object which represents the file result */
public Counts get ( final File file ) { } }

implementation: int index = results . indexOf ( new FileCount ( file , null ) ) ; if ( index == - 1 ) { return null ; } else { return results . get ( index ) . getCounts ( ) ; }


signature:
public class FitResultTable { /** * Returns all saved filenames .
 * @ return filenames of all results . */
public File [ ] getFiles ( ) { } }

implementation: 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 ( ) ] ) ;


signature:
public class FitResultTable { /** * Returns the sum of all results .
 * @ return sum of all results */
public Counts getSummary ( ) { } }

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


signature:
public class FitResultTable { /** * Returns a single HTML Table row representing the results of the file
 * { @ code file } .
 * @ param file filename to look up
 * @ return HTML String with a a single Table row */
public String getRow ( final File file ) { } }

implementation:
StringBuilder builder = new StringBuilder ( ) ; Counts counts = get ( file ) ; builder . append ( "
" ) ; int depth = dirHelper . dirDepth ( file ) ; indent ( depth , builder ) ; builder . append ( "" ) ; builder . append ( file . getName ( ) ) ; builder . append ( "" ) ; builder . append ( "	" ) ; if ( counts == null ) { builder . append ( "(none)" ) ; } else { builder . append ( counts . toString ( ) ) ; } builder . append ( "
" ) ; return builder . toString ( ) ;


signature:
public class FitResultTable { /** * Returns a summary row for a whole test run .
 * @ param directory headline of the table
 * @ return a single HTML row */
public String getSummaryRow ( final File directory ) { } }

implementation:
StringBuilder builder = new StringBuilder ( ) ; Counts counts = getSummary ( ) ; builder . append ( "
" ) ; builder . append ( directory . getName ( ) ) ; builder . append ( "	" ) ; builder . append ( counts . toString ( ) ) ; builder . append ( "
" ) ; return builder . toString ( ) ;


signature:
public class FitResultTable { /** * Prints out a table to { @ code stream } which contains all saved
 * results including all summary rows .
 * @ param directory headline of the table
 * @ param stream stream to write results to
 * @ throws IOException thrown by { @ code stream } in case of problems */
@ Override public void print ( final File directory , final OutputStream stream ) throws IOException { } }

implementation:
OutputStreamWriter osw = new OutputStreamWriter ( stream ) ; BufferedWriter bw = new BufferedWriter ( osw ) ; bw . write ( "
" ) ; bw . write ( getSummaryRow ( directory ) ) ; bw . write ( "

" ) ; File [ ] files = getFiles ( ) ; if ( files . length == 0 ) { bw . write ( "
no files found
" ) ; } else { File currentDir = directory ; for ( File file : files ) { File newDir = file . getAbsoluteFile ( ) . getParentFile ( ) ; if ( ! newDir . equals ( currentDir ) && ! dirHelper . isSubDir ( currentDir , newDir ) ) { for ( File tmpDir : dirHelper . getParentDirs ( dirHelper . getCommonDir ( currentDir , file ) , newDir ) ) { bw . write ( getSubSummaryRow ( tmpDir ) ) ; } } currentDir = newDir ; bw . write ( getRow ( file ) ) ; } } bw . write ( "
" ) ; bw . flush ( ) ; osw . flush ( ) ;


signature:
public class FitResultTable { /** * 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 */
public String getSubSummaryRow ( final File path ) throws IOException { } }

implementation:
Counts sum = subDirSum ( path ) ; return String . format ( "
%s	%s
" , color ( sum ) , FitUtils . htmlSafeFile ( dirHelper . abs2rel ( new File ( "" ) . getAbsolutePath ( ) , path . getAbsolutePath ( ) ) ) , sum . toString ( ) ) ;


signature:
public class JsonValueWriter { /** * Serialize return value to HTTP response using JSON encoding . This method delegates
 * { @ link Json # stringify ( java . io . Writer , Object ) } for value serialization .
 * @ param httpResponse HTTP response ,
 * @ param value return value .
 * @ throws IOException if writing to HTTP response output stream fails . */
@ Override public void write ( HttpServletResponse httpResponse , Object value ) throws IOException { } }

implementation: json . stringify ( new OutputStreamWriter ( httpResponse . getOutputStream ( ) , "UTF-8" ) , value ) ;


signature:
public class Factory { /** * Delegates { @ link AppFactory # getInstance ( Class , Object . . . ) } .
 * @ param interfaceClass requested interface class ,
 * @ param args optional constructor arguments .
 * @ param < T > managed class implementation .
 * @ return managed instance , created on the fly or reused from caches , but never null .
 * @ throws BugError if application factory is not bound to current thread .
 * @ see AppFactory # getInstance ( Class , Object . . . ) */
public static < T > T getInstance ( Class < T > interfaceClass , Object ... args ) { } }

implementation: return getAppFactory ( ) . getInstance ( interfaceClass , args ) ;


signature:
public class Factory { /** * Delegates { @ link AppFactory # getInstance ( String , Class , Object . . . ) } .
 * @ param instanceName instance name ,
 * @ param interfaceClass requested interface class ,
 * @ param args optional constructor arguments .
 * @ param < T > managed class implementation .
 * @ return managed instance , created on the fly or reused from caches , but never null .
 * @ throws BugError if application factory is not bound to current thread .
 * @ see AppFactory # getInstance ( String , Class , Object . . . ) */
public static < T > T getInstance ( String instanceName , Class < T > interfaceClass , Object ... args ) { } }

implementation: return getAppFactory ( ) . getInstance ( instanceName , interfaceClass , args ) ;


signature:
public class Factory { /** * Delegates { @ link AppFactory # getOptionalInstance ( Class , Object . . . ) } .
 * @ param interfaceClass requested interface class ,
 * @ param args optional implementation constructor arguments .
 * @ return managed instance or null if no implementation found .
 * @ param < T > managed class implementation .
 * @ throws BugError if application factory is not bound to current thread .
 * @ see AppFactory # getOptionalInstance ( Class , Object . . . ) */
public static < T > T getOptionalInstance ( Class < T > interfaceClass , Object ... args ) { } }

implementation: return getAppFactory ( ) . getOptionalInstance ( interfaceClass , args ) ;


signature:
public class Factory { /** * Delegates { @ link AppFactory # getRemoteInstance ( String , Class ) } .
 * @ param implementationURL the URL of remote implementation ,
 * @ param interfaceClass interface implemented by remote class .
 * @ param < T > managed class implementation .
 * @ return remote class proxy instance .
 * @ throws UnsupportedProtocolException if URL protocol is not supported .
 * @ throws BugError if application factory is not bound to current thread .
 * @ see AppFactory # getRemoteInstance ( String , Class ) */
public static < T > T getRemoteInstance ( String implementationURL , Class < ? super T > interfaceClass ) { } }

implementation: return getAppFactory ( ) . getRemoteInstance ( implementationURL , interfaceClass ) ;


signature:
public class Factory { /** * Helper method to retrieve application factory bound to current thread . Retrieve application factory from current thread
 * local storage . In order to be successfully this method must be preceded by { @ link # bind ( AppFactory ) } called from current
 * thread ; otherwise bug error is thrown .
 * @ return application factory bound to current thread .
 * @ throws BugError if current thread has no application factory bound . */
public static AppFactory getAppFactory ( ) { } }

implementation: AppFactory appFactory = tls . get ( ) ; if ( appFactory == null ) { throw new BugError ( "No application factory bound to current thread |%s|. See #bind(AppFactory)." , Thread . currentThread ( ) ) ; } return appFactory ;


signature:
public class GridUtils { /** * Adds a row of filter text boxes to a Vaadin { @ link Grid } .
 * @ param grid The grid to add the filter row to . */
public static void addFilterRow ( Grid grid ) { } }

implementation: if ( grid . getHeaderRowCount ( ) < 2 ) { grid . appendHeaderRow ( ) ; } Grid . HeaderRow headerRow = grid . getHeaderRow ( 1 ) ; Container . Indexed container = grid . getContainerDataSource ( ) ; container . getContainerPropertyIds ( ) . forEach ( pid -> { TextField filterField = new TextField ( ) ; filterField . setInputPrompt ( "Filter" ) ; filterField . addStyleName ( ValoTheme . TEXTFIELD_SMALL ) ; filterField . setWidth ( 100 , Sizeable . Unit . PERCENTAGE ) ; filterField . addTextChangeListener ( event -> { ( ( Container . SimpleFilterable ) container ) . removeContainerFilters ( pid ) ; if ( ! event . getText ( ) . isEmpty ( ) ) { ( ( Container . Filterable ) container ) . addContainerFilter ( new SimpleStringFilter ( pid , event . getText ( ) , true , false ) ) ; } } ) ; headerRow . getCell ( pid ) . setComponent ( filterField ) ; } ) ;


signature:
public class ServiceInstanceFactory { /** * 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 < code > args < / code > argument is not empty .
 * @ throws NoProviderException if no service provider found on run - time for requested interface . */
@ SuppressWarnings ( "unchecked" ) @ Override public < I > I newInstance ( ManagedClassSPI managedClass , Object ... args ) { } }

implementation: 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 ] ) ;


signature:
public class XtextParserConfig { /** * Returns the setup class .
 * @ return Setup class of type { @ link # setupClassName } . */
public final Class < ? > getSetupClass ( ) { } }

implementation: 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 ;


signature:
public class XtextParserConfig { /** * Returns a list of model directories to parse .
 * @ return Directory list or NULL . */
public final List < File > getModelDirs ( ) { } }

implementation: if ( ( modelDirs == null ) && ( modelPath != null ) ) { modelDirs = paths ( ) . stream ( ) . filter ( XtextParserConfig :: isFile ) . map ( XtextParserConfig :: asFile ) . collect ( Collectors . toList ( ) ) ; } return modelDirs ;


signature:
public class XtextParserConfig { /** * Returns a list of model resources to parse .
 * @ return List of resources or NULL . */
public final List < URI > getModelResources ( ) { } }

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


signature:
public class SetupFixture { /** * Reads a row which contains two cells and registers an alias .
 * The first cell must contain the alias , the second one must contains the
 * fully qualified class name . Using another alias as class name is not
 * permitted .
 * Cross references are resolved .
 * @ param row row to parse */
@ Override protected void doRow ( FitRow row ) { } }

implementation: if ( row . size ( ) < 2 ) { row . cells ( ) . get ( 0 ) . ignore ( ) ; return ; } alias = validator . preProcess ( row . cells ( ) . get ( 0 ) ) ; className = validator . preProcess ( row . cells ( ) . get ( 1 ) ) ; AliasHelper aliasHelper = DependencyManager . getOrCreate ( AliasHelper . class ) ; aliasHelper . register ( alias , className ) ;


signature:
public class EntityPicker { /** * Sets a set of candidates for selection .
 * @ param candidates The candidates for selection . */
public void setCandidates ( Collection < T > candidates ) { } }

implementation: twinColSelect . setContainerDataSource ( container = new BeanItemContainer < > ( entityType , candidates ) ) ;


signature:
public class RunFixture { /** * Runs the file { @ code fileName } using the current runner and replaces
 * the current row with the results .
 * @ param fileName file to process
 * @ throws Exception propagated to fit */
public void file ( final String fileName ) throws Exception { } }

implementation:
String in = thisDir . getAbsolutePath ( ) ; File out = outDir . getAbsoluteFile ( ) ; // noinspection ResultOfMethodCallIgnored
out . mkdirs ( ) ; File inputFile = dirHelper . rel2abs ( in , fileName ) ; File outputFile = dirHelper . subdir ( out , inputFile . getName ( ) ) ; Counts result = runner . run ( inputFile , outputFile ) ; appendResults ( row , inputFile . getName ( ) , result ) ; row . getTable ( ) . getCounts ( ) . tally ( result ) ;


signature:
public class RunFixture { /** * TODO : not tested ? */
public void directory ( final String dir ) throws Exception { } }

implementation: File srcDir = dirHelper . rel2abs ( thisDir . getAbsolutePath ( ) , dir ) ; List < FileInformation > files = new DirectoryFilter ( srcDir , dirHelper ) . getSelectedFiles ( ) ; RunConfiguration runConfiguration = new RunConfiguration ( ) ; runConfiguration . setEncoding ( runner . getEncoding ( ) ) ; runConfiguration . setBaseDir ( srcDir ) ; runConfiguration . setDestination ( outDir . getPath ( ) ) ; runConfiguration . setSource ( files . toArray ( new FileInformation [ files . size ( ) ] ) ) ; System . out . println ( "Run: " + files + " in " + srcDir + " to " + outDir ) ; final FitRunner fitRunner = new FitRunner ( dirHelper , runConfiguration ) ; FitParseResult results = new FitParseResult ( ) ; fitRunner . run ( results ) ; results . insertAndReplace ( row ) ; row . getTable ( ) . getCounts ( ) . tally ( results . getCounts ( ) ) ;


signature:
public class TinyConfigBuilder { /** * 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 static void loadXML ( InputStream inputStream , Loader loader ) throws ConfigException { } }

implementation: 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 ) ; }


signature:
public class AbstractEndpointView { /** * Handler for errors reported by REST endpoints .
 * @ param ex The exception reported by the REST endpoint . */
protected void onError ( Exception ex ) { } }

implementation: Notification . show ( "Error" , ex . getLocalizedMessage ( ) , Notification . Type . ERROR_MESSAGE ) ;


signature:
public class AutoEntityForm { /** * Builds a form layout with fields for all properties exposed by the
 * entity .
 * @ param entityType The type of entity to build a form for .
 * @ return The form layout . */
protected Component buildAndBind ( Class < TEntity > entityType ) { } }

implementation: FormLayout layout = new FormLayout ( ) ; getPropertiesWithoutAnnotation ( entityType , EditorHidden . class ) . forEach ( ( property ) -> { if ( property . getWriteMethod ( ) == null ) { return ; } Component component = buildAndBind ( property ) ; component . setWidth ( 100 , Unit . PERCENTAGE ) ; if ( component . getCaption ( ) == null ) { component . setCaption ( propertyIdToHumanFriendly ( property . getName ( ) ) ) ; } if ( component instanceof DateField ) { ( ( DateField ) component ) . setResolution ( Resolution . SECOND ) ; } layout . addComponent ( component ) ; getAnnotation ( entityType , property , Description . class ) . ifPresent ( x -> layout . addComponent ( buildDescriptionComponent ( property , x . value ( ) ) ) ) ;


signature:
public class QueryParametersParser { /** * Parse URL query parameters provided by source reader . Detect query parameters name and and value and update a list of
 * parsed parameters . Takes care to decode escaped characters from both parameter names and values .
 * This parser expect UTF - 8 for text encoding and throws unsupported encoding for different codes .
 * @ param reader source reader .
 * @ return list of parsed parameters .
 * @ throws IOException if read operation fails .
 * @ throws UnsupportedEncodingException if URL encoded parameters encoding is not UTF - 8.
 * @ throws SyntaxException if URL query parameters are not properly encoded . */
private static List < Parameter > parse ( Reader reader ) throws IOException { } }

implementation:
List < Parameter > parameters = new ArrayList < Parameter > ( ) ; Parameter parameter = new Parameter ( ) ; State state = State . NAME ; for ( ; ; ) { int b = reader . read ( ) ; if ( b == - 1 ) { // conclude last parameter value
if ( parameter . isEmpty ( ) ) { break ; } if ( parameters . isEmpty ( ) && parameter . isRawValue ( ) ) { parameter . commitRawValue ( ) ; } else { parameter . commitValue ( ) ; } parameters . add ( parameter ) ; break ; } char c = ( char ) b ; switch ( state ) { case NAME : switch ( c ) { case '=' : state = State . VALUE ; parameter . commitName ( ) ; break ; case '&' : if ( parameter . getBuilder ( ) . isEmpty ( ) ) { throw new SyntaxException ( "Invalid query string. Empty parameter name." ) ; } else { throw new SyntaxException ( "Invalid query string parameter |%s|. Missing name/value separator." , parameter . getBuilder ( ) ) ; } default : parameter . append ( c ) ; } break ; case VALUE : switch ( c ) { case '&' : state = State . NAME ; parameter . commitValue ( ) ; parameters . add ( parameter ) ; parameter = new Parameter ( ) ; break ; case '=' : throw new SyntaxException ( "Invalid query string parameter |%s|. Unescaped '=' character." , parameter . getBuilder ( ) ) ; default : parameter . append ( c ) ; } } } return parameters ;