signature:
public class ConditionFactory { /** * Await until a Atomic variable has a value matching the specified
 * { @ link org . hamcrest . Matcher } . E . g .
 * < p > & nbsp ; < / p >
 * < pre >
 * await ( ) . untilAtomic ( myAtomic , is ( greaterThan ( 2 ) ) ) ;
 * < / pre >
 * @ param atomic the atomic variable
 * @ param matcher the matcher The hamcrest matcher that checks whether the
 * condition is fulfilled .
 * @ return a { @ link java . lang . Integer } object .
 * @ throws org . awaitility . core . ConditionTimeoutException If condition was not fulfilled within the given time period . */
public Integer untilAtomic ( final AtomicInteger atomic , final Matcher < ? super Integer > matcher ) { } }

implementation: return until ( new CallableHamcrestCondition < Integer > ( new Callable < Integer > ( ) { public Integer call ( ) { return atomic . get ( ) ; } } , matcher , generateConditionSettings ( ) ) ) ;


signature:
public class ConditionFactory { /** * Await until a Atomic variable has a value matching the specified
 * { @ link org . hamcrest . Matcher } . E . g .
 * < p > & nbsp ; < / p >
 * < pre >
 * await ( ) . untilAtomic ( myAtomic , is ( greaterThan ( 2 ) ) ) ;
 * < / pre >
 * @ param atomic the atomic variable
 * @ param matcher the matcher The hamcrest matcher that checks whether the
 * condition is fulfilled .
 * @ return a { @ link java . lang . Long } object .
 * @ throws org . awaitility . core . ConditionTimeoutException If condition was not fulfilled within the given time period . */
public Long untilAtomic ( final AtomicLong atomic , final Matcher < ? super Long > matcher ) { } }

implementation: return until ( new CallableHamcrestCondition < Long > ( new Callable < Long > ( ) { public Long call ( ) { return atomic . get ( ) ; } } , matcher , generateConditionSettings ( ) ) ) ;


signature:
public class ConditionFactory { /** * Await until a Atomic variable has a value matching the specified
 * { @ link org . hamcrest . Matcher } . E . g .
 * < p > & nbsp ; < / p >
 * < pre >
 * await ( ) . untilAtomic ( myAtomic , is ( greaterThan ( 2 ) ) ) ;
 * < / pre >
 * @ param atomic the atomic variable
 * @ param matcher the matcher The hamcrest matcher that checks whether the
 * condition is fulfilled .
 * @ throws org . awaitility . core . ConditionTimeoutException If condition was not fulfilled within the given time period . */
public void untilAtomic ( final AtomicBoolean atomic , final Matcher < ? super Boolean > matcher ) { } }

implementation: until ( new CallableHamcrestCondition < Boolean > ( new Callable < Boolean > ( ) { public Boolean call ( ) { return atomic . get ( ) ; } } , matcher , generateConditionSettings ( ) ) ) ;


signature:
public class ConditionFactory { /** * Await until a Atomic boolean becomes true .
 * @ param atomic the atomic variable
 * @ throws org . awaitility . core . ConditionTimeoutException If condition was not fulfilled within the given time period . */
public void untilTrue ( final AtomicBoolean atomic ) { } }

implementation: untilAtomic ( atomic , anyOf ( is ( Boolean . TRUE ) , is ( true ) ) ) ;


signature:
public class ConditionFactory { /** * Await until a Atomic boolean becomes false .
 * @ param atomic the atomic variable
 * @ throws org . awaitility . core . ConditionTimeoutException If condition was not fulfilled within the given time period . */
public void untilFalse ( final AtomicBoolean atomic ) { } }

implementation: untilAtomic ( atomic , anyOf ( is ( Boolean . FALSE ) , is ( false ) ) ) ;


signature:
public class ConditionFactory { /** * Await until a Atomic variable has a value matching the specified
 * { @ link org . hamcrest . Matcher } . E . g .
 * < p > & nbsp ; < / p >
 * < pre >
 * await ( ) . untilAtomic ( myAtomic , is ( greaterThan ( 2 ) ) ) ;
 * < / pre >
 * @ param atomic the atomic variable
 * @ param matcher the matcher The hamcrest matcher that checks whether the
 * condition is fulfilled .
 * @ param < V > a V object .
 * @ return a V object .
 * @ throws org . awaitility . core . ConditionTimeoutException If condition was not fulfilled within the given time period . */
public < V > V untilAtomic ( final AtomicReference < V > atomic , final Matcher < ? super V > matcher ) { } }

implementation: return until ( new CallableHamcrestCondition < V > ( new Callable < V > ( ) { public V call ( ) { return atomic . get ( ) ; } } , matcher , generateConditionSettings ( ) ) ) ;


signature:
public class ConditionFactory { /** * Ensures backward compatibility ( especially that poll delay is the same as poll interval for fixed poll interval ) .
 * It also make sure that poll delay is { @ link Duration # ZERO } for all other poll intervals if poll delay was not explicitly
 * defined . If poll delay was explicitly defined the it will just be returned .
 * @ param pollDelay The poll delay
 * @ param pollInterval The chosen ( or default ) poll interval
 * @ return The poll delay to use */
private Duration definePollDelay ( Duration pollDelay , PollInterval pollInterval ) { } }

implementation:
final Duration pollDelayToUse ; // If a poll delay is null then a poll delay has not been explicitly defined by the user
if ( pollDelay == null ) { if ( pollInterval != null && pollInterval instanceof FixedPollInterval ) { pollDelayToUse = pollInterval . next ( 1 , Duration . ZERO ) ; // Will return same poll delay as poll interval
} else { pollDelayToUse = Duration . ZERO ; // Default poll delay for non - fixed poll intervals
} } else { // Poll delay was explicitly defined , use it !
pollDelayToUse = pollDelay ; } return pollDelayToUse ;


signature:
public class Awaitility { /** * Instruct Awaitility to ignore caught exception of the given type during condition evaluation .
 * Exceptions will be treated as evaluating to < code > false < / code > . Your test will not fail
 * upon an exception matching the supplied exception type , unless it times out . */
public static void ignoreExceptionByDefault ( final Class < ? extends Throwable > exceptionType ) { } }

implementation: defaultExceptionIgnorer = new PredicateExceptionIgnorer ( new Predicate < Throwable > ( ) { public boolean matches ( Throwable e ) { return e . getClass ( ) . equals ( exceptionType ) ; } } ) ;


signature:
public class Awaitility { /** * Instructs Awaitility to execute the polling of the condition from the same as the test .
 * This is an advanced feature and you should be careful when combining this with conditions that
 * wait forever ( or a long time ) since Awaitility cannot interrupt the thread when using the same
 * thread as the test . For safety you should always combine tests using this feature with a test framework specific timeout ,
 * for example in JUnit :
 * < pre >
 * @ Test ( timeout = 2000L )
 * public void myTest ( ) {
 * Awaitility . pollInSameThread ( ) ;
 * await ( ) . forever ( ) . until ( . . . ) ;
 * < / pre >
 * @ since 3.0.0 */
public static void pollInSameThread ( ) { } }

implementation: defaultExecutorLifecycle = ExecutorLifecycle . withNormalCleanupBehavior ( new Supplier < ExecutorService > ( ) { @ Override public ExecutorService get ( ) { return InternalExecutorServiceFactory . sameThreadExecutorService ( ) ; } } ) ;


signature:
public class Awaitility { /** * Specify a thread supplier whose thread will be used to evaluate the poll condition in Awaitility .
 * The supplier will be called only once and the thread it returns will be reused during all condition evaluations .
 * This is an advanced feature and it should only be used sparingly .
 * @ param threadSupplier A supplier of the thread that Awaitility will use when polling
 * @ since 3.0.0 */
public static void pollThread ( final Function < Runnable , Thread > threadSupplier ) { } }

implementation: defaultExecutorLifecycle = ExecutorLifecycle . withNormalCleanupBehavior ( new Supplier < ExecutorService > ( ) { @ Override public ExecutorService get ( ) { return InternalExecutorServiceFactory . create ( threadSupplier ) ; } } ) ;


signature:
public class Awaitility { /** * Reset the timeout , poll interval , poll delay , uncaught exception handling
 * to their default values :
 * < p > & nbsp ; < / p >
 * < ul >
 * < li > timeout - 10 seconds < / li >
 * < li > poll interval - 100 milliseconds < / li >
 * < li > poll delay - 100 milliseconds < / li >
 * < li > Catch all uncaught exceptions - true < / li >
 * < li > Do not ignore caught exceptions < / li >
 * < li > Don ' t handle condition evaluation results < / li >
 * < / ul > */
public static void reset ( ) { } }

implementation: defaultPollInterval = DEFAULT_POLL_INTERVAL ; defaultPollDelay = DEFAULT_POLL_DELAY ; defaultWaitConstraint = AtMostWaitConstraint . TEN_SECONDS ; defaultCatchUncaughtExceptions = true ; defaultConditionEvaluationListener = null ; defaultExecutorLifecycle = null ; defaultExceptionIgnorer = new PredicateExceptionIgnorer ( new Predicate < Throwable > ( ) { public boolean matches ( Throwable e ) { return false ; } } ) ; Thread . setDefaultUncaughtExceptionHandler ( null ) ;


signature:
public class Awaitility { /** * Start building a named await statement . This is useful is cases when you
 * have several awaits in your test and you need to tell them apart . If a
 * named await timeout ' s the < code > alias < / code > will be displayed indicating
 * which await statement that failed .
 * @ param alias the alias that will be shown if the await timeouts .
 * @ return the condition factory */
public static ConditionFactory await ( String alias ) { } }

implementation: return new ConditionFactory ( alias , defaultWaitConstraint , defaultPollInterval , defaultPollDelay , defaultCatchUncaughtExceptions , defaultExceptionIgnorer , defaultConditionEvaluationListener , defaultExecutorLifecycle ) ;


signature:
public class Awaitility { /** * Catching uncaught exceptions in other threads . This will make the await
 * statement fail even if exceptions occur in other threads . This is the
 * default behavior .
 * @ return the condition factory */
public static ConditionFactory catchUncaughtExceptions ( ) { } }

implementation: return new ConditionFactory ( null , defaultWaitConstraint , defaultPollInterval , defaultPollDelay , defaultCatchUncaughtExceptions , defaultExceptionIgnorer , defaultConditionEvaluationListener , defaultExecutorLifecycle ) ;


signature:
public class Awaitility { /** * Don ' t catch uncaught exceptions in other threads . This will < i > not < / i >
 * make the await statement fail if exceptions occur in other threads .
 * @ return the condition factory */
public static ConditionFactory dontCatchUncaughtExceptions ( ) { } }

implementation: return new ConditionFactory ( null , defaultWaitConstraint , defaultPollInterval , defaultPollDelay , false , defaultExceptionIgnorer , defaultConditionEvaluationListener , defaultExecutorLifecycle ) ;


signature:
public class Awaitility { /** * An alternative to using { @ link # await ( ) } if you want to specify a timeout
 * directly .
 * @ param timeout the timeout
 * @ return the condition factory */
public static ConditionFactory waitAtMost ( Duration timeout ) { } }

implementation: return new ConditionFactory ( null , defaultWaitConstraint . withMaxWaitTime ( timeout ) , defaultPollInterval , defaultPollDelay , defaultCatchUncaughtExceptions , defaultExceptionIgnorer , defaultConditionEvaluationListener , defaultExecutorLifecycle ) ;


signature:
public class Awaitility { /** * An alternative to using { @ link # await ( ) } if you want to specify a timeout
 * directly .
 * @ param value the value
 * @ param unit the unit
 * @ return the condition factory */
public static ConditionFactory waitAtMost ( long value , TimeUnit unit ) { } }

implementation: return new ConditionFactory ( null , defaultWaitConstraint . withMaxWaitTime ( new Duration ( value , unit ) ) , defaultPollInterval , defaultPollDelay , defaultCatchUncaughtExceptions , defaultExceptionIgnorer , defaultConditionEvaluationListener , defaultExecutorLifecycle ) ;


signature:
public class Awaitility { /** * Sets the default timeout all await statements will use .
 * @ param timeout the timeout
 * @ param unit the unit */
public static void setDefaultTimeout ( long timeout , TimeUnit unit ) { } }

implementation: defaultWaitConstraint = defaultWaitConstraint . withMaxWaitTime ( new Duration ( timeout , unit ) ) ;


signature:
public class Awaitility { /** * Sets the default timeout that all await statements will use .
 * @ param defaultTimeout the new default timeout */
public static void setDefaultTimeout ( Duration defaultTimeout ) { } }

implementation: if ( defaultTimeout == null ) { throw new IllegalArgumentException ( "You must specify a default timeout (was null)." ) ; } defaultWaitConstraint = defaultWaitConstraint . withMaxWaitTime ( defaultTimeout ) ;


signature:
public class MigrationInitializer { /** * We start it at order 9 which is below order 10 ( where JPA is started ) */
@ Start ( order = 9 ) public void start ( ) { } }

implementation:
// Run migration only when activated in configuration . conf :
Boolean runMigrations = ninjaProperties . getBoolean ( NinjaConstant . NINJA_MIGRATION_RUN ) ; if ( runMigrations != null && runMigrations ) { // provider used for late binding
migrationEngineProvider . get ( ) . migrate ( ) ; }


signature:
public class ArgumentTokenizer { /** * Tokenizes the given String into String tokens .
 * @ param arguments A String containing one or more command - line style arguments to be tokenized .
 * @ param stringify whether or not to include escape special characters
 * @ return A list of parsed and properly escaped arguments . */
public static List < String > tokenize ( String arguments , boolean stringify ) { } }

implementation:
LinkedList < String > argList = new LinkedList < > ( ) ; StringBuilder currArg = new StringBuilder ( ) ; boolean escaped = false ; int state = NO_TOKEN_STATE ; // start in the NO _ TOKEN _ STATE
int len = arguments . length ( ) ; // Loop over each character in the string
for ( int i = 0 ; i < len ; i ++ ) { char c = arguments . charAt ( i ) ; if ( escaped ) { // Escaped state : just append the next character to the current arg .
escaped = false ; currArg . append ( c ) ; } else { switch ( state ) { case SINGLE_QUOTE_STATE : if ( c == '\'' ) { // Seen the close quote ; continue this arg until whitespace is seen
state = NORMAL_TOKEN_STATE ; } else { currArg . append ( c ) ; } break ; case DOUBLE_QUOTE_STATE : if ( c == '"' ) { // Seen the close quote ; continue this arg until whitespace is seen
state = NORMAL_TOKEN_STATE ; } else if ( c == '\\' ) { // Look ahead , and only escape quotes or backslashes
i ++ ; char next = arguments . charAt ( i ) ; if ( next == '"' || next == '\\' ) { currArg . append ( next ) ; } else { currArg . append ( c ) ; currArg . append ( next ) ; } } else { currArg . append ( c ) ; } break ; // case NORMAL _ TOKEN _ STATE :
// if ( Character . isWhitespace ( c ) ) {
// / / Whitespace ends the token ; start a new one
// argList . add ( currArg . toString ( ) ) ;
// currArg = new StringBuffer ( ) ;
// state = NO _ TOKEN _ STATE ;
// else if ( c = = ' \ \ ' ) {
// / / Backslash in a normal token : escape the next character
// escaped = true ;
// else if ( c = = ' \ ' ' ) {
// state = SINGLE _ QUOTE _ STATE ;
// else if ( c = = ' " ' ) {
// state = DOUBLE _ QUOTE _ STATE ;
// else {
// currArg . append ( c ) ;
// break ;
case NO_TOKEN_STATE : case NORMAL_TOKEN_STATE : switch ( c ) { case '\\' : escaped = true ; state = NORMAL_TOKEN_STATE ; break ; case '\'' : state = SINGLE_QUOTE_STATE ; break ; case '"' : state = DOUBLE_QUOTE_STATE ; break ; default : if ( ! Character . isWhitespace ( c ) ) { currArg . append ( c ) ; state = NORMAL_TOKEN_STATE ; } else if ( state == NORMAL_TOKEN_STATE ) { // Whitespace ends the token ; start a new one
argList . add ( currArg . toString ( ) ) ; currArg = new StringBuilder ( ) ; state = NO_TOKEN_STATE ; } } break ; default : throw new IllegalStateException ( "ArgumentTokenizer state " + state + " is invalid!" ) ; } } } // If we ' re still escaped , put in the backslash
if ( escaped ) { currArg . append ( '\\' ) ; argList . add ( currArg . toString ( ) ) ; } // Close the last argument if we haven ' t yet
else if ( state != NO_TOKEN_STATE ) { argList . add ( currArg . toString ( ) ) ; } // Format each argument if we ' ve been told to stringify them
if ( stringify ) { for ( int i = 0 ; i < argList . size ( ) ; i ++ ) { argList . set ( i , "\"" + _escapeQuotesAndBackslashes ( argList . get ( i ) ) + "\"" ) ; } } return argList ;


signature:
public class ArgumentTokenizer { /** * Inserts backslashes before any occurrences of a backslash or
 * quote in the given string . Also converts any special characters
 * appropriately . */
protected static String _escapeQuotesAndBackslashes ( String s ) { } }

implementation:
final StringBuilder buf = new StringBuilder ( s ) ; // Walk backwards , looking for quotes or backslashes .
// If we see any , insert an extra backslash into the buffer at
// the same index . ( By walking backwards , the index into the buffer
// will remain correct as we change the buffer . )
for ( int i = s . length ( ) - 1 ; i >= 0 ; i -- ) { char c = s . charAt ( i ) ; if ( ( c == '\\' ) || ( c == '"' ) ) { buf . insert ( i , '\\' ) ; } // Replace any special characters with escaped versions
else if ( c == '\n' ) { buf . deleteCharAt ( i ) ; buf . insert ( i , "\\n" ) ; } else if ( c == '\t' ) { buf . deleteCharAt ( i ) ; buf . insert ( i , "\\t" ) ; } else if ( c == '\r' ) { buf . deleteCharAt ( i ) ; buf . insert ( i , "\\r" ) ; } else if ( c == '\b' ) { buf . deleteCharAt ( i ) ; buf . insert ( i , "\\b" ) ; } else if ( c == '\f' ) { buf . deleteCharAt ( i ) ; buf . insert ( i , "\\f" ) ; } } return buf . toString ( ) ;


signature:
public class HttpHeaderUtils { /** * A http content type should contain a character set like
 * " application / json ; charset = utf - 8 " .
 * If you only want to get the character set you can use this method .
 * See also : http : / / www . w3 . org / Protocols / rfc2616 / rfc2616 - sec3 . html # sec3.7.1
 * @ param rawContentType " application / json ; charset = utf - 8 " or " application / json "
 * @ return only the character set like utf - 8 OR the defaultEncoding when not set */
public static String getCharsetOfContentType ( String rawContentType , String defaultEncoding ) { } }

implementation: if ( rawContentType . contains ( "charset=" ) ) { String charset = rawContentType . split ( "charset=" ) [ 1 ] ; return charset ; } else { return defaultEncoding ; }


signature:
public class RouteParameter { /** * Parse a path such as " / user / { id : [ 0-9 ] + } / email / { addr } " for the named
 * parameters .
 * @ param path The path to parse
 * @ return A map containing the named parameters in the order they were
 * parsed or null if no parameters were parsed . */
static public Map < String , RouteParameter > parse ( String path ) { } }

implementation:
Map < String , RouteParameter > params = new LinkedHashMap < > ( ) ; // extract any named parameters
Matcher matcher = Route . PATTERN_FOR_VARIABLE_PARTS_OF_ROUTE . matcher ( path ) ; while ( matcher . find ( ) ) { RouteParameter param = new RouteParameter ( matcher . start ( 0 ) , matcher . group ( 0 ) , matcher . group ( 1 ) , matcher . group ( 3 ) ) ; params . put ( param . getName ( ) , param ) ; } return params ;


signature:
public class NinjaServletContext { /** * When a servlet engine gets a content type like : " application / json " it
 * assumes a default encoding of iso - xxxxx .
 * That is not what Ninja does ( and is not consistent with default encodings
 * of application / json and application / xml ) .
 * Therefore we ' ll set utf - 8 as request encoding if it is not set . */
private void enforceCorrectEncodingOfRequest ( ) { } }

implementation: String charset = NinjaConstant . UTF_8 ; String contentType = getHeader ( CONTENT_TYPE ) ; if ( contentType != null ) { charset = HttpHeaderUtils . getCharsetOfContentTypeOrUtf8 ( contentType ) ; } try { httpServletRequest . setCharacterEncoding ( charset ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Server does not support charset of content type: " + contentType ) ; }


signature:
public class NinjaServletContext { /** * Utility method to convert a Guava Multimap to an unmodifiable Map that
 * uses a List < T > as a value . Optimized for the case where values are already
 * internally stored as a List < T > ( e . g . ArrayListMultimap ) .
 * @ param < T > The value type
 * @ param multimap The multimap to convert from
 * @ return The unmodifiable converted map */
private < T > Map < String , List < T > > toUnmodifiableMap ( Multimap < String , T > multimap ) { } }

implementation: Map < String , List < T > > map = new HashMap < > ( multimap . size ( ) ) ; for ( Entry < String , Collection < T > > entry : multimap . asMap ( ) . entrySet ( ) ) { Collection < T > value = entry . getValue ( ) ; if ( value == null ) { Collections . emptyList ( ) ; } else if ( value instanceof List ) { map . put ( entry . getKey ( ) , ( List < T > ) value ) ; } else { map . put ( entry . getKey ( ) , new ArrayList < > ( value ) ) ; } } return Collections . unmodifiableMap ( map ) ;


signature:
public class ReverseRouter { /** * Retrieves a the reverse route for a method referenced with Java - 8
 * lambdas ( functional method references ) .
 * @ param controllerMethod The Java - 8 style method reference such as
 * < code > ApplicationController : : index < / code > .
 * @ return A < code > Builder < / code > allowing setting path placeholders and
 * queryParam string parameters . */
@ Override public Builder with ( ControllerMethod controllerMethod ) { } }

implementation:
LambdaRoute lambdaRoute = LambdaRoute . resolve ( controllerMethod ) ; // only need the functional method for the reverse lookup
Method method = lambdaRoute . getFunctionalMethod ( ) ; return builder ( method . getDeclaringClass ( ) , method . getName ( ) ) ;


signature:
public class NinjaServletListener { /** * Getting the injector is done via double locking in conjuction
 * with volatile keyword for thread safety .
 * See also : http : / / en . wikipedia . org / wiki / Double - checked _ locking
 * @ return The injector for this application . */
@ Override public Injector getInjector ( ) { } }

implementation:
// fetch instance variable into method , so that we access the volatile
// global variable only once - that ' s better performance wise .
Bootstrap ninjaBootstrapLocal = ninjaBootstrap ; if ( ninjaBootstrapLocal == null ) { synchronized ( this ) { ninjaBootstrapLocal = ninjaBootstrap ; if ( ninjaBootstrapLocal == null ) { // if properties
if ( ninjaProperties == null ) { ninjaProperties = new NinjaPropertiesImpl ( NinjaModeHelper . determineModeFromSystemPropertiesOrProdIfNotSet ( ) ) ; } ninjaBootstrap = createNinjaBootstrap ( ninjaProperties , contextPath ) ; ninjaBootstrapLocal = ninjaBootstrap ; } } } return ninjaBootstrapLocal . getInjector ( ) ;


signature:
public class AssetsController { /** * Serves resources from the assets directory of your application .
 * For instance :
 * route : / robots . txt
 * A request to / robots . txt will be served from / assets / robots . txt .
 * You can also use a path like the following to serve files :
 * route : / assets / { fileName : . * }
 * matches
 * / assets / app / app . css
 * and will return
 * / assets / app / app . css ( from your jar ) . */
public Result serveStatic ( ) { } }

implementation: Object renderable = new Renderable ( ) { @ Override public void render ( Context context , Result result ) { String fileName = getFileNameFromPathOrReturnRequestPath ( context ) ; URL url = getStaticFileFromAssetsDir ( fileName ) ; streamOutUrlEntity ( url , context , result ) ; } } ; return Results . ok ( ) . render ( renderable ) ;


signature:
public class AssetsController { /** * Loads files from assets directory . This is the default directory
 * of Ninja where to store stuff . Usually in src / main / java / assets / . */
private URL getStaticFileFromAssetsDir ( String fileName ) { } }

implementation:
URL url = null ; if ( ninjaProperties . isDev ( ) // Testing that the file exists is important because
// on some dev environments we do not get the correct asset dir
// via System . getPropery ( " user . dir " ) .
// In that case we fall back to trying to load from classpath
&& new File ( assetsDirInDevModeWithoutTrailingSlash ( ) ) . exists ( ) ) { String finalNameWithoutLeadingSlash = assetsControllerHelper . normalizePathWithoutLeadingSlash ( fileName , false ) ; File possibleFile = new File ( assetsDirInDevModeWithoutTrailingSlash ( ) + File . separator + finalNameWithoutLeadingSlash ) ; url = getUrlForFile ( possibleFile ) ; } else { String finalNameWithoutLeadingSlash = assetsControllerHelper . normalizePathWithoutLeadingSlash ( fileName , true ) ; url = this . getClass ( ) . getClassLoader ( ) . getResource ( ASSETS_DIR + "/" + finalNameWithoutLeadingSlash ) ; } return url ;


signature:
public class AssetsController { /** * Loads files from META - INF / resources directory .
 * This is compatible with Servlet 3.0 specification and allows
 * to use e . g . webjars project . */
private URL getStaticFileFromMetaInfResourcesDir ( String fileName ) { } }

implementation: String finalNameWithoutLeadingSlash = assetsControllerHelper . normalizePathWithoutLeadingSlash ( fileName , true ) ; URL url = null ; url = this . getClass ( ) . getClassLoader ( ) . getResource ( "META-INF/resources/webjars/" + finalNameWithoutLeadingSlash ) ; return url ;


signature:
public class AssetsController { /** * Used in dev mode : Streaming directly from src dir without jetty reload . */
private String assetsDirInDevModeWithoutTrailingSlash ( ) { } }

implementation: String srcDir = System . getProperty ( "user.dir" ) + File . separator + "src" + File . separator + "main" + File . separator + "java" ; return srcDir + File . separator + ASSETS_DIR ;


signature:
public class TemplateEngineJsonP { /** * Tests whether the given function name is a valid JSONP function
 * name / path .
 * @ param callback Callback value to test .
 * @ return Whether the given function name is a valid JSONP function
 * name / path . */
public static boolean isThisASecureCallbackName ( String callback ) { } }

implementation: return ! Strings . isNullOrEmpty ( callback ) && ! callback . contains ( ".." ) && CALLBACK_SECURITY_VALIDATION_REGEXP . matcher ( callback ) . matches ( ) ;


signature:
public class MessagesImpl { /** * Attempts to load a message file and sets the file changed reloading
 * strategy on the configuration if the runtime mode is Dev . */
private PropertiesConfiguration loadLanguageConfiguration ( String fileOrUrl ) { } }

implementation:
PropertiesConfiguration configuration = SwissKnife . loadConfigurationInUtf8 ( fileOrUrl ) ; if ( configuration != null && ninjaProperties . isDev ( ) ) { // enable runtime reloading of translations in dev mode
FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy ( ) ; configuration . setReloadingStrategy ( strategy ) ; } return configuration ;


signature:
public class MessagesImpl { /** * Does all the loading of message files .
 * Only registered messages in application . conf are loaded . */
private Map < String , Configuration > loadAllMessageFilesForRegisteredLanguages ( ) { } }

implementation:
Map < String , Configuration > langToKeyAndValuesMappingMutable = Maps . newHashMap ( ) ; // Load default messages :
Configuration defaultLanguage = loadLanguageConfiguration ( "conf/messages.properties" ) ; // Make sure we got the file .
// Everything else does not make much sense .
if ( defaultLanguage == null ) { throw new RuntimeException ( "Did not find conf/messages.properties. Please add a default language file." ) ; } else { langToKeyAndValuesMappingMutable . put ( "" , defaultLanguage ) ; } // Get the languages from the application configuration .
String [ ] applicationLangs = ninjaProperties . getStringArray ( NinjaConstant . applicationLanguages ) ; // If we don ' t have any languages declared we just return .
// We ' ll use the default messages . properties file .
if ( applicationLangs == null ) { return ImmutableMap . copyOf ( langToKeyAndValuesMappingMutable ) ; } // Load each language into the HashMap containing the languages :
for ( String lang : applicationLangs ) { // First step : Load complete language eg . en - US
Configuration configuration = loadLanguageConfiguration ( String . format ( "conf/messages_%s.properties" , lang ) ) ; Configuration configurationLangOnly = null ; // If the language has a country code load the default values for
// the language , too . For instance missing variables in en - US will
// be
// Overwritten by the default languages .
if ( lang . contains ( "-" ) ) { // get the lang
String langOnly = lang . split ( "-" ) [ 0 ] ; // And load the configuraion
configurationLangOnly = loadLanguageConfiguration ( String . format ( "conf/messages_%s.properties" , langOnly ) ) ; } // This is strange . If you defined the language in application . conf
// it should be there propably .
if ( configuration == null ) { logger . info ( "Did not find conf/messages_{}.properties but it was specified in application.conf. Using default language instead." , lang ) ; } else { // add new language , but combine with default language if stuff
// is missing . . .
CompositeConfiguration compositeConfiguration = new CompositeConfiguration ( ) ; // Add eg . " en - US "
compositeConfiguration . addConfiguration ( configuration ) ; // Add eg . " en "
if ( configurationLangOnly != null ) { compositeConfiguration . addConfiguration ( configurationLangOnly ) ; } // Add messages . conf ( default pack )
compositeConfiguration . addConfiguration ( defaultLanguage ) ; // and add the composed configuration to the hashmap with the
// mapping .
langToKeyAndValuesMappingMutable . put ( lang , ( Configuration ) compositeConfiguration ) ; } } return ImmutableMap . copyOf ( langToKeyAndValuesMappingMutable ) ;


signature:
public class MessagesImpl { /** * Retrieves the matching language file from an arbitrary one or two part
 * locale String ( " en - US " , or " en " or " de " . . . ) .
 * @ param language
 * A two or one letter language code such as " en - US " or " en " or
 * " en - US , en ; q = 0.8 , de ; q = 0.6 " .
 * @ return The matching configuration from the hashmap . Or the default
 * mapping if no one has been found . */
private Configuration getLanguageConfigurationForLocale ( Optional < String > language ) { } }

implementation:
// if language is null we return the default language .
if ( ! language . isPresent ( ) ) { return langToKeyAndValuesMapping . get ( "" ) ; } // Check if we get a registered mapping for the language input string .
// At that point the language may be either language - country or only country .
// extract multiple languages from Accept - Language header
String [ ] languages = language . get ( ) . split ( "," ) ; for ( String l : languages ) { l = l . trim ( ) ; // Ignore the relative quality factor in Accept - Language header
if ( l . contains ( ";" ) ) { l = l . split ( ";" ) [ 0 ] ; } Configuration configuration = langToKeyAndValuesMapping . get ( l ) ; if ( configuration != null ) { return configuration ; } // If we got a two part language code like " en - US " we split it and
// search only for the language " en " .
if ( l . contains ( "-" ) ) { String [ ] array = l . split ( "-" ) ; String languageWithoutCountry = array [ 0 ] ; // Modify country code to upper case for IE and Firefox
if ( array . length > 1 ) { String country = array [ 1 ] ; String languageWithUpperCaseCountry = languageWithoutCountry + "-" + country . toUpperCase ( ) ; configuration = langToKeyAndValuesMapping . get ( languageWithUpperCaseCountry ) ; if ( configuration != null ) { return configuration ; } } configuration = langToKeyAndValuesMapping . get ( languageWithoutCountry ) ; if ( configuration != null ) { return configuration ; } } } // Oops . Nothing found . We return the default language ( by convention guaranteed to work ) .
return langToKeyAndValuesMapping . get ( "" ) ;


signature:
public class LogbackConfigurator { /** * Looks up a potential file from
 * 1 ) The classpahth
 * 2 ) From the filesystem
 * 3 ) From an URL
 * @ param logbackConfigurationFile
 * @ return null if not found or a valid url created from the logbackConfigurationFile */
protected static URL getUrlForStringFromClasspathAsFileOrUrl ( String logbackConfigurationFile ) { } }

implementation:
URL url = null ; try { url = Resources . getResource ( logbackConfigurationFile ) ; } catch ( IllegalArgumentException ex ) { // doing nothing intentionally . .
} if ( url == null ) { // configuring from file :
try { File file = new File ( logbackConfigurationFile ) ; if ( file . exists ( ) ) { url = new File ( logbackConfigurationFile ) . toURI ( ) . toURL ( ) ; } } catch ( MalformedURLException ex ) { // doing nothing intentionally . .
} } if ( url == null ) { try { // we assume we got a real http : / / . . . url here . . .
url = new URL ( logbackConfigurationFile ) ; } catch ( MalformedURLException ex ) { // doing nothing intentionally . .
} } return url ;


signature:
public class LangImpl { /** * Retrieves the language cookie or generates one with a very long max age ( ten years ) .
 * @ param context
 * @ return The cookie */
private Cookie generateNinjaLanguageCookie ( ) { } }

implementation: Cookie cookie = Cookie . builder ( applicationCookiePrefix + ninja . utils . NinjaConstant . LANG_COOKIE_SUFFIX , "" ) . setMaxAge ( TEN_YEARS ) . build ( ) ; return cookie ;


signature:
public class SecretGenerator { /** * ! ! ! ! Only for testing purposes ! ! ! !
 * Usually you want to use { @ link SecretGenerator # generateSecret ( ) }
 * @ param random the random generator to use . Usually new Random ( ) , but for testing you can
 * use a predefined seed .
 * @ return A String suitable as random secret for eg signing a session . */
protected static String generateSecret ( Random random ) { } }

implementation: String charsetForSecret = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ; StringBuilder stringBuilder = new StringBuilder ( 64 ) ; for ( int i = 0 ; i < 64 ; i ++ ) { int charToPoPickFromCharset = random . nextInt ( charsetForSecret . length ( ) ) ; stringBuilder . append ( charsetForSecret . charAt ( charToPoPickFromCharset ) ) ; } return stringBuilder . toString ( ) ;


signature:
public class NinjaRunMojo { /** * so we can mock a fake one for unit testing */
protected RunClassInSeparateJvmMachine buildRunClassInSeparateJvmMachine ( String name , String classNameWithMainToRun , List < String > classpath , List < String > jvmArguments , File mavenBaseDir ) { } }

implementation: return new RunClassInSeparateJvmMachine ( name , classNameWithMainToRun , classpath , buildJvmArguments ( ) , mavenBaseDir ) ;


signature:
public class NinjaRunMojo { /** * This might be a bit hacky . But just a little bit .
 * We have to add ninja - standalone and all of its dependencies to
 * the classpath , so that NinjaJetty can start .
 * But we do not want the user to declare the dependencies inside his
 * project pom . xml .
 * Therefore we declare the dependency in this plugin pom . xml .
 * But we do not want to include all of this plugin ' s dependencies in the
 * classpath for NinjaJetty . Therefore this method filters everything and
 * only adds dependencies ( also transitive deps ) that originate
 * from ninja - standalone . That way we get all deps we need .
 * @ param artifacts A list of artifacts that will be filtered .
 * @ return All artifacts coming from artifactId " ninja - standalone "
 * ( including transitive dependencies ) */
protected List < Artifact > getAllArtifactsComingFromNinjaStandalone ( List < Artifact > artifacts ) { } }

implementation:
List < Artifact > resultingArtifacts = new ArrayList < > ( ) ; for ( Artifact artifact : artifacts ) { for ( String dependencyTrail : artifact . getDependencyTrail ( ) ) { // something like : org . ninjaframework : ninja - standalone : jar : 2.5.2
if ( dependencyTrail . contains ( NinjaMavenPluginConstants . NINJA_STANDALONE_ARTIFACT_ID ) ) { resultingArtifacts . add ( artifact ) ; break ; } } } return resultingArtifacts ;


signature:
public class StandaloneHelper { /** * Resolves which standalone class to use . Either defined as a system
 * property or falling back to the default .
 * @ return The resolved standalone class to use */
static public Class < ? extends Standalone > resolveStandaloneClass ( ) { } }

implementation: return resolveStandaloneClass ( System . getProperty ( Standalone . KEY_NINJA_STANDALONE_CLASS ) , ForwardingServiceLoader . loadWithSystemServiceLoader ( Standalone . class ) , Standalone . DEFAULT_STANDALONE_CLASS ) ;


signature:
public class StandaloneHelper { /** * used for testing ( so we can inject mocks of system static methods ) */
static Class < ? extends Standalone > resolveStandaloneClass ( String standaloneClassNameSystemProperty , ForwardingServiceLoader < Standalone > standaloneServiceLoader , String standaloneClassNameDefaultValue ) { } }

implementation:
Class < ? extends Standalone > resolvedStandaloneClass = null ; // 1 . System property for ' ninja . standalone . class '
if ( standaloneClassNameSystemProperty != null ) { try { resolvedStandaloneClass = ( Class < Standalone > ) Class . forName ( standaloneClassNameSystemProperty ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to find standalone class '" + standaloneClassNameSystemProperty + "' (class does not exist)" ) ; } } // 2 . Implementation on classpath that ' s registered as service ?
if ( resolvedStandaloneClass == null ) { try { Iterator < Standalone > standaloneIterator = standaloneServiceLoader . iterator ( ) ; // first one wins
if ( standaloneIterator . hasNext ( ) ) { resolvedStandaloneClass = standaloneIterator . next ( ) . getClass ( ) ; } // more than one triggers warning
if ( standaloneIterator . hasNext ( ) ) { log . warn ( "More than one implementation of {} on classpath! Using {} which was the first" , Standalone . class , resolvedStandaloneClass ) ; } } finally { // always kill cache ( since ServiceLoader actually instantiates an instance )
standaloneServiceLoader . reload ( ) ; } } // 3 . Fallback to ninja default
if ( resolvedStandaloneClass == null ) { try { resolvedStandaloneClass = ( Class < Standalone > ) Class . forName ( standaloneClassNameDefaultValue ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to find standalone class '" + standaloneClassNameDefaultValue + "' (class does not exist)" ) ; } } return resolvedStandaloneClass ;


signature:
public class CookieEncryption { /** * Encrypts data with secret key .
 * @ param data text to encrypt
 * @ return encrypted text in base64 format */
public String encrypt ( String data ) { } }

implementation:
Objects . requireNonNull ( data , "Data to be encrypted" ) ; if ( ! secretKeySpec . isPresent ( ) ) { return data ; } try { // encrypt data
Cipher cipher = Cipher . getInstance ( ALGORITHM ) ; cipher . init ( Cipher . ENCRYPT_MODE , secretKeySpec . get ( ) ) ; byte [ ] encrypted = cipher . doFinal ( data . getBytes ( StandardCharsets . UTF_8 ) ) ; // convert encrypted bytes to string in base64
return Base64 . encodeBase64URLSafeString ( encrypted ) ; } catch ( InvalidKeyException ex ) { logger . error ( getHelperLogMessage ( ) , ex ) ; throw new RuntimeException ( ex ) ; } catch ( GeneralSecurityException ex ) { logger . error ( "Failed to encrypt data." , ex ) ; return "" ; }


signature:
public class CookieEncryption { /** * Decrypts data with secret key .
 * @ param data text to decrypt in base64 format
 * @ return decrypted text */
public String decrypt ( String data ) { } }

implementation:
Objects . requireNonNull ( data , "Data to be decrypted" ) ; if ( ! secretKeySpec . isPresent ( ) ) { return data ; } // convert base64 encoded string to bytes
byte [ ] decoded = Base64 . decodeBase64 ( data ) ; try { // decrypt bytes
Cipher cipher = Cipher . getInstance ( ALGORITHM ) ; cipher . init ( Cipher . DECRYPT_MODE , secretKeySpec . get ( ) ) ; byte [ ] decrypted = cipher . doFinal ( decoded ) ; // convert bytes to string
return new String ( decrypted , StandardCharsets . UTF_8 ) ; } catch ( InvalidKeyException ex ) { logger . error ( getHelperLogMessage ( ) , ex ) ; throw new RuntimeException ( ex ) ; } catch ( GeneralSecurityException ex ) { logger . error ( "Failed to decrypt data." , ex ) ; return "" ; }


signature: public class NinjaDefault { @ Override public Result onException ( Context context , Exception exception ) { } }

implementation: return onException ( context , exception , null ) ;


signature:
public class NinjaDefault { /** * Deprecated . Check { @ link Ninja # getInternalServerErrorResult ( Context , Exception , Result ) } . */
@ Deprecated public Result getInternalServerErrorResult ( Context context , Exception exception ) { } }

implementation: return getInternalServerErrorResult ( context , exception , null ) ;


signature:
public class NinjaDefault { /** * Simply reads a property resource file that contains the version of this
 * Ninja build . Helps to identify the Ninja version currently running .
 * @ return The version of Ninja . Eg . " 1.6 - SNAPSHOT " while developing of " 1.6 " when released . */
private final String readNinjaVersion ( ) { } }

implementation:
// location of the properties file
String LOCATION_OF_NINJA_BUILTIN_PROPERTIES = "ninja/ninja-builtin.properties" ; // and the key inside the properties file .
String NINJA_VERSION_PROPERTY_KEY = "ninja.version" ; String ninjaVersion ; try ( InputStream stream = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( LOCATION_OF_NINJA_BUILTIN_PROPERTIES ) ) { Properties prop = new Properties ( ) ; prop . load ( stream ) ; ninjaVersion = prop . getProperty ( NINJA_VERSION_PROPERTY_KEY ) ; } catch ( Exception e ) { // this should not happen . Never .
throw new RuntimeErrorException ( new Error ( "Something is wrong with your build. Cannot find resource " + LOCATION_OF_NINJA_BUILTIN_PROPERTIES ) ) ; } return ninjaVersion ;


signature:
public class WatchAndRestartMachine { /** * Register the given path with the WatchService */
private void register ( Path path ) throws IOException { } }

implementation:
// / / USUALLY THIS IS THE DEFAULT WAY TO REGISTER THE EVENTS :
// WatchKey watchKey = path . register (
// watchService ,
// ENTRY _ CREATE ,
// ENTRY _ DELETE ,
// ENTRY _ MODIFY ) ;
// / / BUT THIS IS DAMN SLOW ( at least on a Mac )
// / / THEREFORE WE USE EVENTS FROM COM . SUN PACKAGES THAT ARE WAY FASTER
// / / THIS MIGHT BREAK COMPATIBILITY WITH OTHER JDKs
// / / MORE : http : / / stackoverflow . com / questions / 9588737 / is - java - 7 - watchservice - slow - for - anyone - else
WatchKey watchKey = path . register ( watchService , new WatchEvent . Kind [ ] { StandardWatchEventKinds . ENTRY_CREATE , StandardWatchEventKinds . ENTRY_MODIFY , StandardWatchEventKinds . ENTRY_DELETE } , SensitivityWatchEventModifier . HIGH ) ; mapOfWatchKeysToPaths . put ( watchKey , path ) ;


signature:
public class Route { /** * Matches / index to / index or / me / 1 to / person / { id }
 * @ return True if the actual route matches a raw rout . False if not . */
public boolean matches ( String httpMethod , String uri ) { } }

implementation: if ( this . httpMethod . equalsIgnoreCase ( httpMethod ) ) { Matcher matcher = regex . matcher ( uri ) ; return matcher . matches ( ) ; } else { return false ; }


signature:
public class Route { /** * This method does not do any decoding / encoding .
 * If you want to decode you have to do it yourself .
 * Most likely with :
 * http : / / docs . oracle . com / javase / 6 / docs / api / java / net / URI . html
 * @ param uri The whole encoded uri .
 * @ return A map with all parameters of that uri . Encoded in = > encoded out . */
public Map < String , String > getPathParametersEncoded ( String uri ) { } }

implementation: Map < String , String > map = Maps . newHashMap ( ) ; Matcher m = regex . matcher ( uri ) ; if ( m . matches ( ) ) { Iterator < String > it = this . parameters . keySet ( ) . iterator ( ) ; for ( int i = 1 ; i < m . groupCount ( ) + 1 ; i ++ ) { String parameterName = it . next ( ) ; map . put ( parameterName , m . group ( i ) ) ; } } return map ;


signature:
public class Route { /** * Gets a raw uri like " / { name } / id / * " and returns " / ( [ ^ / ] * ) / id / * . "
 * Also handles regular expressions if defined inside routes :
 * For instance " / users / { username : [ a - zA - Z ] [ a - zA - Z _ 0-9 ] } " becomes
 * " / users / ( [ a - zA - Z ] [ a - zA - Z _ 0-9 ] ) "
 * @ return The converted regex with default matching regex - or the regex
 * specified by the user . */
protected static String convertRawUriToRegex ( String rawUri ) { } }

implementation:
// convert capturing groups in route regex to non - capturing groups
// this is to avoid count mismatch of path params and groups in uri regex
Matcher groupMatcher = Pattern . compile ( "\\(([^?].*)\\)" ) . matcher ( rawUri ) ; String converted = groupMatcher . replaceAll ( "\\(?:$1\\)" ) ; Matcher matcher = PATTERN_FOR_VARIABLE_PARTS_OF_ROUTE . matcher ( converted ) ; StringBuffer stringBuffer = new StringBuffer ( ) ; while ( matcher . find ( ) ) { // By convention group 3 is the regex if provided by the user .
// If it is not provided by the user the group 3 is null .
String namedVariablePartOfRoute = matcher . group ( 3 ) ; String namedVariablePartOfORouteReplacedWithRegex ; if ( namedVariablePartOfRoute != null ) { // we convert that into a regex matcher group itself
namedVariablePartOfORouteReplacedWithRegex = "(" + Matcher . quoteReplacement ( namedVariablePartOfRoute ) + ")" ; } else { // we convert that into the default namedVariablePartOfRoute regex group
namedVariablePartOfORouteReplacedWithRegex = VARIABLE_ROUTES_DEFAULT_REGEX ; } // we replace the current namedVariablePartOfRoute group
matcher . appendReplacement ( stringBuffer , namedVariablePartOfORouteReplacedWithRegex ) ; } // . . and we append the tail to complete the stringBuffer
matcher . appendTail ( stringBuffer ) ; return stringBuffer . toString ( ) ;


signature:
public class NinjaModeHelper { /** * returns an empty Optional < NinjaMode > if no mode is set . Or the valid mode
 * set via a System Property called " ninja . mode " .
 * E . g . under mvn you can use mvn . . . - Dninja . mode = prod or so . Valid values
 * for ninja . mode are " prod " , " dev " , " test " .
 * @ return The valid mode set via a System Property called " ninja . mode "
 * or Optional absent if we cannot get one . */
public static Optional < NinjaMode > determineModeFromSystemProperties ( ) { } }

implementation:
NinjaMode ninjaMode = null ; // Get mode possibly set via a system property
String modeFromGetSystemProperty = System . getProperty ( NinjaConstant . MODE_KEY_NAME ) ; // If the user specified a mode we set the mode accordingly :
if ( modeFromGetSystemProperty != null ) { if ( modeFromGetSystemProperty . equals ( NinjaConstant . MODE_TEST ) ) { ninjaMode = NinjaMode . test ; } else if ( modeFromGetSystemProperty . equals ( NinjaConstant . MODE_DEV ) ) { ninjaMode = NinjaMode . dev ; } else if ( modeFromGetSystemProperty . equals ( NinjaConstant . MODE_PROD ) ) { ninjaMode = NinjaMode . prod ; } } return Optional . ofNullable ( ninjaMode ) ;


signature:
public class NinjaModeHelper { /** * returns NinjaMode . dev if no mode is set . Or the valid mode
 * set via a System Property called " ninja . mode " .
 * E . g . under mvn you can use mvn . . . - Dninja . mode = prod or so . Valid values
 * for ninja . mode are " prod " , " dev " , " test " .
 * @ return The valid mode set via a System Property called " ninja . mode "
 * or NinjaMode . dev if it is not set . */
public static NinjaMode determineModeFromSystemPropertiesOrProdIfNotSet ( ) { } }

implementation: Optional < NinjaMode > ninjaModeOptional = determineModeFromSystemProperties ( ) ; NinjaMode ninjaMode ; if ( ! ninjaModeOptional . isPresent ( ) ) { ninjaMode = NinjaMode . prod ; } else { ninjaMode = ninjaModeOptional . get ( ) ; } logger . info ( "Ninja is running in mode {}" , ninjaMode . toString ( ) ) ; return ninjaMode ;


signature:
public class MimeTypes { /** * return the mimetype from a file name . < br / >
 * @ param filename
 * the file name
 * @ param defaultMimeType
 * the default mime type to return when no matching mimetype is
 * found
 * @ return the mimetype */
public String getMimeType ( String filename , String defaultMimeType ) { } }

implementation: Matcher matcher = extPattern . matcher ( filename . toLowerCase ( ) ) ; String ext = "" ; if ( matcher . matches ( ) ) { ext = matcher . group ( 1 ) ; } if ( ext . length ( ) > 0 ) { String mimeType = mimetypes . getProperty ( ext ) ; if ( mimeType == null ) { return defaultMimeType ; } return mimeType ; } return defaultMimeType ;


signature:
public class MimeTypes { /** * check the mimetype is referenced in the mimetypes database
 * @ param mimeType
 * the mimeType to verify */
public boolean isValidMimeType ( String mimeType ) { } }

implementation: if ( mimeType == null ) { return false ; } else if ( mimeType . indexOf ( ";" ) != - 1 ) { return mimetypes . contains ( mimeType . split ( ";" ) [ 0 ] ) ; } else { return mimetypes . contains ( mimeType ) ; }


signature:
public class WebSocketUtils { /** * Parses header ` Sec - WebSocket - Protocol : chat , superchat ` into a list
 * such as ` chat ` , and ` superchat ` .
 * @ param value The header value
 * @ return A set of values or null if value was null or empty */
static public Set < String > parseProtocolRequestHeader ( String value ) { } }

implementation: Set < String > subprotocols = new LinkedHashSet < > ( ) ; if ( ! StringUtils . isEmpty ( value ) ) { String [ ] values = value . split ( "," ) ; for ( String v : values ) { subprotocols . add ( v . trim ( ) ) ; } } return subprotocols ;


signature:
public class RouteBuilderImpl { /** * Routes are usually defined in conf / Routes . java as
 * router . GET ( ) . route ( " / teapot " ) . with ( FilterController . class , " teapot " ) ;
 * Unfortunately " teapot " is not checked by the compiler . We do that here at
 * runtime .
 * We are reloading when there are changes . So this is almost as good as
 * compile time checking .
 * @ param controller
 * The controller class
 * @ param controllerMethod
 * The method
 * @ return The actual method */
private Method verifyControllerMethod ( Class < ? > controllerClass , String controllerMethod ) { } }

implementation:
try { Method methodFromQueryingClass = null ; // 1 . Make sure method is in class
// 2 . Make sure only one method is there . Otherwise we cannot really
// know what to do with the parameters .
for ( Method method : controllerClass . getMethods ( ) ) { if ( method . getName ( ) . equals ( controllerMethod ) ) { if ( methodFromQueryingClass == null ) { methodFromQueryingClass = method ; } else { throw new NoSuchMethodException ( ) ; } } } if ( methodFromQueryingClass == null ) { throw new NoSuchMethodException ( ) ; } // make sure that the return type of that controller method
// is of type Result .
if ( Result . class . isAssignableFrom ( methodFromQueryingClass . getReturnType ( ) ) ) { return methodFromQueryingClass ; } else { throw new NoSuchMethodException ( ) ; } } catch ( SecurityException e ) { log . error ( "Error while checking for valid Controller / controllerMethod combination" , e ) ; } catch ( NoSuchMethodException e ) { log . error ( "Error in route configuration!!!" ) ; log . error ( "Can not find Controller " + controllerClass . getName ( ) + " and method " + controllerMethod ) ; log . error ( "Hint: make sure the controller returns a ninja.Result!" ) ; log . error ( "Hint: Ninja does not allow more than one method with the same name!" ) ; } return null ;


signature:
public class RouteBuilderImpl { /** * Build the route .
 * @ param injector The injector to build the route with
 * @ return The built route */
public Route buildRoute ( Injector injector ) { } }

implementation:
if ( functionalMethod == null ) { log . error ( "Error in route configuration for {}" , uri ) ; throw new IllegalStateException ( "Route missing a controller method" ) ; } // Calculate filters
LinkedList < Class < ? extends Filter > > allFilters = new LinkedList < > ( ) ; allFilters . addAll ( calculateGlobalFilters ( this . globalFiltersOptional , injector ) ) ; allFilters . addAll ( this . localFilters ) ; allFilters . addAll ( calculateFiltersForClass ( functionalMethod . getDeclaringClass ( ) ) ) ; FilterWith filterWith = functionalMethod . getAnnotation ( FilterWith . class ) ; if ( filterWith != null ) { allFilters . addAll ( Arrays . asList ( filterWith . value ( ) ) ) ; } FilterChain filterChain = buildFilterChain ( injector , allFilters ) ; return new Route ( httpMethod , uri , functionalMethod , filterChain ) ;


signature:
public class Lambdas { /** * Tries to get a SerializedLambda from an Object by searching the class
 * hierarchy for a < code > writeReplace < / code > method . The lambda must
 * be serializable in order for this method to return a value .
 * @ param lambda An object that is an instance of a functional interface .
 * @ return The SerializedLambda */
public static SerializedLambda getSerializedLambda ( Object lambda ) { } }

implementation:
Objects . requireNonNull ( lambda ) ; if ( ! ( lambda instanceof java . io . Serializable ) ) { throw new IllegalArgumentException ( "Functional object does not implement java.io.Serializable" ) ; } for ( Class < ? > clazz = lambda . getClass ( ) ; clazz != null ; clazz = clazz . getSuperclass ( ) ) { try { Method replaceMethod = clazz . getDeclaredMethod ( "writeReplace" ) ; replaceMethod . setAccessible ( true ) ; Object serializedForm = replaceMethod . invoke ( lambda ) ; if ( serializedForm instanceof SerializedLambda ) { return ( SerializedLambda ) serializedForm ; } } catch ( NoSuchMethodError e ) { // fall through the loop and try the next class
} catch ( NoSuchMethodException e ) { throw new IllegalArgumentException ( "Functional object is not a lambda" ) ; } catch ( SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new RuntimeException ( "Unable to cleanly serialize lambda" , e ) ; } } throw new RuntimeException ( "writeReplace method not found" ) ;


signature:
public class AbstractStandalone { /** * Configure , start , add shutdown hook , and join . Does not exit . */
@ Override final public void run ( ) { } }

implementation:
// name current thread for improved logging / debugging
Thread . currentThread ( ) . setName ( this . name ) ; try { this . configure ( ) ; } catch ( Exception e ) { logger . error ( "Unable to configure {}" , name , e ) ; System . exit ( 1 ) ; } try { this . start ( ) ; } catch ( Exception e ) { logger . error ( "Unable to start {}" , name , e ) ; System . exit ( 1 ) ; } Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { shutdown ( ) ; } } ) ; try { // do not simply exit main ( ) - - join something ( likely server )
join ( ) ; } catch ( Exception e ) { logger . warn ( "Interrupted (most likely JVM is shutting down and this is safe to ignore)" ) ; }


signature:
public class AbstractStandalone { /** * helpful utilities for subclasses */
protected String createServerUrl ( String scheme , String host , Integer port ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; sb . append ( scheme ) ; sb . append ( "://" ) ; sb . append ( ( host != null ? host : "localhost" ) ) ; if ( ( "http" . equals ( scheme ) && port != 80 ) || ( "https" . equals ( scheme ) && port != 443 ) ) { sb . append ( ":" ) ; sb . append ( port ) ; } return sb . toString ( ) ;


signature:
public class JaxyRoutes { /** * Scans , identifies , and registers annotated controller methods for the
 * current runtime settings .
 * @ param router */
@ Override public void init ( Router router ) { } }

implementation: this . router = router ; configureReflections ( ) ; controllers = Maps . newHashMap ( ) ; methods = Sets . newHashSet ( ) ; processFoundMethods ( ) ; sortMethods ( ) ; registerMethods ( ) ;


signature:
public class JaxyRoutes { /** * Takes all methods and registers them at the controller using the path : Class : @ Path + Method : @ Path .
 * If no @ Path Annotation is present at the method just the Class : @ Path is used . */
private void registerMethods ( ) { } }

implementation:
// register routes for all the methods
for ( Method method : methods ) { final Class < ? > controllerClass = method . getDeclaringClass ( ) ; final Path methodPath = method . getAnnotation ( Path . class ) ; final Set < String > controllerPaths = controllers . get ( controllerClass ) ; String [ ] paths = { "/" } ; if ( methodPath != null ) { paths = methodPath . value ( ) ; } for ( String controllerPath : controllerPaths ) { for ( String methodPathSpec : paths ) { final String httpMethod = getHttpMethod ( method ) ; final String fullPath = controllerPath + methodPathSpec ; final String methodName = method . getName ( ) ; router . METHOD ( httpMethod ) . route ( fullPath ) . with ( controllerClass , methodName ) ; } } }


signature:
public class JaxyRoutes { /** * Takes the found methods and checks if they have a valid format .
 * If they do , the controller path classes for these methods are generated */
private void processFoundMethods ( ) { } }

implementation:
for ( Method method : findControllerMethods ( ) ) { if ( allowMethod ( method ) ) { // add the method to our todo list
methods . add ( method ) ; // generate the paths for the controller class
final Class < ? > controllerClass = method . getDeclaringClass ( ) ; if ( ! controllers . containsKey ( controllerClass ) ) { Set < String > paths = collectPaths ( controllerClass ) ; controllers . put ( controllerClass , paths ) ; } } }


signature:
public class JaxyRoutes { /** * Sorts the methods into registration order */
private void sortMethods ( ) { } }

implementation:
List < Method > methodList = new ArrayList < > ( methods ) ; Collections . sort ( methodList , new Comparator < Method > ( ) { @ Override public int compare ( Method m1 , Method m2 ) { int o1 = Integer . MAX_VALUE ; if ( m1 . isAnnotationPresent ( Order . class ) ) { Order order = m1 . getAnnotation ( Order . class ) ; o1 = order . value ( ) ; } int o2 = Integer . MAX_VALUE ; if ( m2 . isAnnotationPresent ( Order . class ) ) { Order order = m2 . getAnnotation ( Order . class ) ; o2 = order . value ( ) ; } if ( o1 == o2 ) { // same or unsorted , compare controller + method
String s1 = m1 . getDeclaringClass ( ) . getName ( ) + "." + m1 . getName ( ) ; String s2 = m2 . getDeclaringClass ( ) . getName ( ) + "." + m2 . getName ( ) ; return s1 . compareTo ( s2 ) ; } if ( o1 < o2 ) { return - 1 ; } else { return 1 ; } } } ) ; methods = new LinkedHashSet < > ( methodList ) ;


signature:
public class JaxyRoutes { /** * Searches for Methods that have either a Path Annotation or a HTTP - Method Annotation */
@ SuppressWarnings ( "unchecked" ) private Set < Method > findControllerMethods ( ) { } }

implementation:
Set < Method > methods = Sets . newLinkedHashSet ( ) ; methods . addAll ( reflections . getMethodsAnnotatedWith ( Path . class ) ) ; boolean enableCustomHttpMethods = ninjaProperties . getBooleanWithDefault ( NINJA_CUSTOM_HTTP_METHODS , false ) ; if ( enableCustomHttpMethods ) { Reflections annotationReflections = new Reflections ( "" , new TypeAnnotationsScanner ( ) , new SubTypesScanner ( ) ) ; for ( Class < ? > httpMethod : annotationReflections . getTypesAnnotatedWith ( HttpMethod . class ) ) { if ( httpMethod . isAnnotation ( ) ) { methods . addAll ( reflections . getMethodsAnnotatedWith ( ( Class < ? extends Annotation > ) httpMethod ) ) ; } } } else { // Only look for standard HTTP methods annotations
Reflections annotationReflections = new Reflections ( "ninja.jaxy" , new TypeAnnotationsScanner ( ) , new SubTypesScanner ( ) ) ; for ( Class < ? > httpMethod : annotationReflections . getTypesAnnotatedWith ( HttpMethod . class ) ) { if ( httpMethod . isAnnotation ( ) ) { methods . addAll ( reflections . getMethodsAnnotatedWith ( ( Class < ? extends Annotation > ) httpMethod ) ) ; } } } return methods ;


signature:
public class JaxyRoutes { /** * Configures the set of packages to scan for annotated controller methods . */
private void configureReflections ( ) { } }

implementation: Optional < String > basePackage = Optional . ofNullable ( ninjaProperties . get ( NinjaConstant . APPLICATION_MODULES_BASE_PACKAGE ) ) ; if ( basePackage . isPresent ( ) ) { reflections = new Reflections ( basePackage . get ( ) + "." + NinjaConstant . CONTROLLERS_DIR , new MethodAnnotationsScanner ( ) ) ; } else { reflections = new Reflections ( NinjaConstant . CONTROLLERS_DIR , new MethodAnnotationsScanner ( ) ) ; }


signature:
public class JaxyRoutes { /** * Determines if this method may be registered as a route . Ninja properties
 * are considered as well as runtime modes .
 * @ param method
 * @ return true if the method can be registered as a route */
private boolean allowMethod ( Method method ) { } }

implementation:
// NinjaProperties - based route exclusions / inclusions
if ( method . isAnnotationPresent ( Requires . class ) ) { String key = method . getAnnotation ( Requires . class ) . value ( ) ; String value = ninjaProperties . get ( key ) ; if ( value == null ) { return false ; } } // NinjaMode - based route exclusions / inclusions
Set < NinjaMode > modes = Sets . newTreeSet ( ) ; for ( Annotation annotation : method . getAnnotations ( ) ) { Class < ? extends Annotation > annotationClass = annotation . annotationType ( ) ; if ( annotationClass . isAnnotationPresent ( RuntimeMode . class ) ) { RuntimeMode mode = annotationClass . getAnnotation ( RuntimeMode . class ) ; modes . add ( mode . value ( ) ) ; } } return modes . isEmpty ( ) || modes . contains ( runtimeMode ) ;


signature:
public class JaxyRoutes { /** * Returns the HTTP method for the controller method . Defaults to GET if
 * unspecified .
 * @ param method
 * @ return the http method for this controller method */
private String getHttpMethod ( Method method ) { } }

implementation:
for ( Annotation annotation : method . getAnnotations ( ) ) { Class < ? extends Annotation > annotationClass = annotation . annotationType ( ) ; if ( annotationClass . isAnnotationPresent ( HttpMethod . class ) ) { HttpMethod httpMethod = annotationClass . getAnnotation ( HttpMethod . class ) ; return httpMethod . value ( ) ; } } // default to GET
logger . info ( String . format ( "%s.%s does not specify an HTTP method annotation! Defaulting to GET." , method . getClass ( ) . getName ( ) , method . getName ( ) ) ) ; return HttpMethod . GET ;


signature:
public class ControllerMethodInvoker { /** * Builds an invoker for a functional method . Understands what parameters
 * to inject and extract based on type and annotations .
 * @ param functionalMethod The method to be invoked
 * @ param implementationMethod The method to use for determining what
 * actual parameters and annotations to use for each argument . Useful
 * when type / lambda erasure makes the functional interface not reliable
 * for reflecting .
 * @ param injector The guice injector
 * @ param ninjaProperties The NinjaProperties of this application
 * @ return An invoker */
public static ControllerMethodInvoker build ( Method functionalMethod , Method implementationMethod , Injector injector , NinjaProperties ninjaProperties ) { } }

implementation:
// get both the parameters . . .
final Type [ ] genericParameterTypes = implementationMethod . getGenericParameterTypes ( ) ; final MethodParameter [ ] methodParameters = MethodParameter . convertIntoMethodParameters ( genericParameterTypes ) ; // . . . and all annotations for the parameters
final Annotation [ ] [ ] paramAnnotations = implementationMethod . getParameterAnnotations ( ) ; ArgumentExtractor < ? > [ ] argumentExtractors = new ArgumentExtractor < ? > [ methodParameters . length ] ; // now we skip through the parameters and process the annotations
for ( int i = 0 ; i < methodParameters . length ; i ++ ) { try { argumentExtractors [ i ] = getArgumentExtractor ( methodParameters [ i ] , paramAnnotations [ i ] , injector ) ; } catch ( RoutingException e ) { throw new RoutingException ( "Error building argument extractor for parameter " + i + " in method " + implementationMethod . getDeclaringClass ( ) . getName ( ) + "." + implementationMethod . getName ( ) + "()" , e ) ; } } // Replace a null extractor with a bodyAs extractor , but make sure there ' s only one
int bodyAsFound = - 1 ; for ( int i = 0 ; i < argumentExtractors . length ; i ++ ) { if ( argumentExtractors [ i ] == null ) { if ( bodyAsFound > - 1 ) { throw new RoutingException ( "Only one parameter may be deserialised as the body " + implementationMethod . getDeclaringClass ( ) . getName ( ) + "." + implementationMethod . getName ( ) + "()\n" + "Extracted parameter is type: " + methodParameters [ bodyAsFound ] . parameterClass . getName ( ) + "\n" + "Extra parmeter is type: " + methodParameters [ i ] . parameterClass . getName ( ) ) ; } else { argumentExtractors [ i ] = new ArgumentExtractors . BodyAsExtractor ( methodParameters [ i ] . parameterClass ) ; bodyAsFound = i ; } } } // Now that every parameter has an argument extractor we can run validation on the annotated
// parameters
for ( int i = 0 ; i < argumentExtractors . length ; i ++ ) { argumentExtractors [ i ] = validateArgumentWithExtractor ( methodParameters [ i ] , paramAnnotations [ i ] , injector , argumentExtractors [ i ] ) ; } boolean useStrictArgumentExtractors = determineWhetherToUseStrictArgumentExtractorMode ( ninjaProperties ) ; return new ControllerMethodInvoker ( functionalMethod , argumentExtractors , useStrictArgumentExtractors ) ;


signature:
public class BodyParserEnginePost { /** * Allows to instantiate inner objects with a prefix for each parameter key */
private < T > T invoke ( Context context , Map < String , String [ ] > parameters , Class < T > classOfT , String paramPrefix ) { } }

implementation:
T t = null ; try { t = classOfT . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { logger . error ( "Can't create new instance of class {}" , classOfT . getName ( ) , e ) ; return null ; } for ( String declaredField : getAllDeclaredFieldsAsStringSet ( classOfT ) ) { try { Field field = classOfT . getDeclaredField ( declaredField ) ; Class < ? > fieldType = field . getType ( ) ; field . setAccessible ( true ) ; if ( parameters . containsKey ( paramPrefix + declaredField ) ) { String [ ] values = parameters . get ( paramPrefix + declaredField ) ; if ( Collection . class . isAssignableFrom ( fieldType ) || List . class . isAssignableFrom ( fieldType ) ) { ListParamParser < ? > parser = ( ListParamParser < ? > ) paramParsers . getListParser ( getGenericType ( field ) ) ; if ( parser == null ) { logger . warn ( "No parser defined for a collection of type {}" , getGenericType ( field ) . getCanonicalName ( ) ) ; } else { field . set ( t , parser . parseParameter ( field . getName ( ) , values , context . getValidation ( ) ) ) ; } } else if ( fieldType . isArray ( ) ) { ArrayParamParser < ? > parser = paramParsers . getArrayParser ( fieldType ) ; if ( parser == null ) { logger . warn ( "No parser defined for an array of type {}" , fieldType . getComponentType ( ) . getCanonicalName ( ) ) ; } else { field . set ( t , parser . parseParameter ( field . getName ( ) , values , context . getValidation ( ) ) ) ; } } else { ParamParser < ? > parser = ( ParamParser < ? > ) paramParsers . getParamParser ( fieldType ) ; if ( parser == null ) { logger . warn ( "No parser defined for type {}" , fieldType . getCanonicalName ( ) ) ; } else { field . set ( t , parser . parseParameter ( field . getName ( ) , values [ 0 ] , context . getValidation ( ) ) ) ; } } } else { // Check if we have one parameter key corresponding to one valued inner attribute of this object field
for ( String parameter : parameters . keySet ( ) ) { if ( parameter . startsWith ( paramPrefix + declaredField + "." ) ) { if ( isEmptyParameter ( parameters . get ( parameter ) ) ) { field . set ( t , invoke ( context , parameters , fieldType , paramPrefix + declaredField + "." ) ) ; break ; } } } } } catch ( NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e ) { logger . warn ( "Error parsing incoming Post request into class {}. Key {} and value {}." , classOfT . getName ( ) , paramPrefix + declaredField , parameters . get ( paramPrefix + declaredField ) , e ) ; } } return t ;


signature:
public class Results { /** * A redirect that uses 303 see other .
 * The redirect does NOT need a template and does NOT
 * render a text in the Http body by default .
 * If you wish to do so please
 * remove the { @ link NoHttpBody } that is set as renderable of
 * the Result .
 * @ param url
 * The url used as redirect target .
 * @ return A nicely configured result with status code 303 and the url set
 * as Location header . Renders no Http body by default . */
public static Result redirect ( String url ) { } }

implementation: Result result = status ( Result . SC_303_SEE_OTHER ) ; result . addHeader ( Result . LOCATION , url ) ; result . render ( Result . NO_HTTP_BODY ) ; return result ;


signature:
public class Results { /** * A redirect that uses 307 see other .
 * The redirect does NOT need a template and does NOT
 * render a text in the Http body by default .
 * If you wish to do so please
 * remove the { @ link NoHttpBody } that is set as renderable of
 * the Result .
 * @ param url
 * The url used as redirect target .
 * @ return A nicely configured result with status code 307 and the url set
 * as Location header . Renders no Http body by default . */
public static Result redirectTemporary ( String url ) { } }

implementation: Result result = status ( Result . SC_307_TEMPORARY_REDIRECT ) ; result . addHeader ( Result . LOCATION , url ) ; result . render ( Result . NO_HTTP_BODY ) ; return result ;


signature:
public class CommonsmailHelperImpl { /** * Creates a MultiPartEmail . Selects the correct implementation
 * regarding html ( MultiPartEmail ) and / or txt content or both .
 * Populates the mutlipart email accordingly with the txt / html content . */
@ Override public MultiPartEmail createMultiPartEmailWithContent ( Mail mail ) throws EmailException { } }

implementation:
MultiPartEmail multiPartEmail ; // set if it is a txt or html mail :
if ( mail . getBodyHtml ( ) == null || mail . getBodyHtml ( ) . equals ( "" ) ) { multiPartEmail = new MultiPartEmail ( ) ; multiPartEmail . setMsg ( mail . getBodyText ( ) ) ; } else if ( mail . getBodyText ( ) == null || mail . getBodyText ( ) . equals ( "" ) ) { multiPartEmail = new HtmlEmail ( ) . setHtmlMsg ( mail . getBodyHtml ( ) ) ; } else { multiPartEmail = new HtmlEmail ( ) . setHtmlMsg ( mail . getBodyHtml ( ) ) . setTextMsg ( mail . getBodyText ( ) ) ; } // and return the nicely configured mail :
return multiPartEmail ;


signature:
public class SwissKnife { /** * This is important : We load stuff as UTF - 8.
 * We are using in the default Apache Commons loading mechanism .
 * With two little tweaks : 1 . We don ' t accept any delimimter by default 2.
 * We are reading in UTF - 8
 * More about that :
 * http : / / commons . apache . org / configuration / userguide / howto _ filebased
 * . html # Loading
 * From the docs : - If the combination from base path and file name is a
 * full URL that points to an existing file , this URL will be used to load
 * the file . - If the combination from base path and file name is an
 * absolute file name and this file exists , it will be loaded . - If the
 * combination from base path and file name is a relative file path that
 * points to an existing file , this file will be loaded . - If a file with
 * the specified name exists in the user ' s home directory , this file will be
 * loaded . - Otherwise the file name is interpreted as a resource name , and
 * it is checked whether the data file can be loaded from the classpath .
 * @ param fileOrUrlOrClasspathUrl Location of the file . Can be on file
 * system , or on the classpath . Will both work .
 * @ return A PropertiesConfiguration or null if there were problems getting
 * it . */
public static PropertiesConfiguration loadConfigurationInUtf8 ( String fileOrUrlOrClasspathUrl ) { } }

implementation: PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration ( ) ; propertiesConfiguration . setEncoding ( NinjaConstant . UTF_8 ) ; propertiesConfiguration . setDelimiterParsingDisabled ( true ) ; propertiesConfiguration . setFileName ( fileOrUrlOrClasspathUrl ) ; propertiesConfiguration . getLayout ( ) . setSingleLine ( NinjaConstant . applicationSecret , true ) ; try { propertiesConfiguration . load ( fileOrUrlOrClasspathUrl ) ; } catch ( ConfigurationException e ) { logger . info ( "Could not load file " + fileOrUrlOrClasspathUrl + " (not a bad thing necessarily, but I am returing null)" ) ; return null ; } return propertiesConfiguration ;


signature:
public class SwissKnife { /** * Returns the lower class name . Eg . A class named MyObject will become
 * " myObject " .
 * @ param object Object for which to return the lowerCamelCaseName
 * @ return the lowerCamelCaseName of the Object */
public static String getRealClassNameLowerCamelCase ( Object object ) { } }

implementation: return CaseFormat . UPPER_CAMEL . to ( CaseFormat . LOWER_CAMEL , object . getClass ( ) . getSimpleName ( ) ) ;


signature:
public class SwissKnife { /** * Used to check whether a class exists on the classpath .
 * @ param nameWithPackage for instance com . example . conf . GloablFilters
 * @ param instanceToGetClassloaderFrom usually " this " if you call this method .
 * @ return true if class exists , false if not . */
public static boolean doesClassExist ( String nameWithPackage , Object instanceToGetClassloaderFrom ) { } }

implementation: boolean exists = false ; try { Class . forName ( nameWithPackage , false , instanceToGetClassloaderFrom . getClass ( ) . getClassLoader ( ) ) ; exists = true ; } catch ( ClassNotFoundException e ) { exists = false ; } return exists ;


signature:
public class DiagnosticErrorBuilder { /** * Calculates the relative path of the source code file of a StackTrace
 * element if its available . Uses the packageName of the class to create a relative path
 * and appends the " filename " included with the stack trace element .
 * @ param ste The stack trace element
 * @ return The relative path of the source code file or null if the information
 * wasn ' t available in the stack trace element . */
static public String getSourceCodeRelativePathForStackTraceElement ( StackTraceElement ste ) { } }

implementation:
String packageName = ste . getClassName ( ) ; // e . g . com . fizzed . test . Application $ 1 for an internal class
int pos = packageName . lastIndexOf ( '.' ) ; if ( pos > 0 ) { packageName = packageName . substring ( 0 , pos ) ; return packageName . replace ( "." , File . separator ) + File . separator + ste . getFileName ( ) ; } else { // must be in default package
return ste . getFileName ( ) ; }


signature:
public class NinjaCache { /** * Add an element only if it doesn ' t exist .
 * @ param key Element key
 * @ param value Element value
 * @ param expiration Ex : 10s , 3mn , 8h */
public void add ( String key , Object value , String expiration ) { } }

implementation: checkSerializable ( value ) ; cache . add ( key , value , TimeUtil . parseDuration ( expiration ) ) ;


signature:
public class NinjaCache { /** * Convenient clazz to get a value a class type ;
 * @ param < T > The needed type
 * @ param key The element key
 * @ param clazz The type class
 * @ return The element value or null */
@ SuppressWarnings ( "unchecked" ) public < T > T get ( String key , Class < T > clazz ) { } }

implementation: return ( T ) cache . get ( key ) ;


signature:
public class NinjaCache { /** * Utility that check that an object is serializable . */
void checkSerializable ( Object value ) { } }

implementation: if ( value != null && ! ( value instanceof Serializable ) ) { throw new CacheException ( "Cannot cache a non-serializable value of type " + value . getClass ( ) . getName ( ) , new NotSerializableException ( value . getClass ( ) . getName ( ) ) ) ; }


signature:
public class Result { /** * This method handles two principal cases :
 * 1 ) If the this . renderable of this result is null , the object passed is simply set as renderable
 * for this Result
 * 2 ) If the this . renderable of this result is not null an new map is generated as
 * object to render and both the former renderable and the new object added to the map .
 * The former object is gets the class name in camelCase as key .
 * If the converted camelCase key of this object already exists an { @ link IllegalArgumentException }
 * is being thrown .
 * @ param object The object to add ( either an arbitrary class or Renderable ) .
 * @ return Result this result for chaining . */
public Result render ( Object object ) { } }

implementation:
if ( this . renderable == null ) { this . renderable = object ; } else { assertObjectNoRenderableOrThrowException ( this . renderable ) ; Map < String , Object > map ; // prepare the this . renderable as we now have at least two
// objects to render
if ( this . renderable instanceof Map ) { map = ( Map ) this . renderable ; } else { map = Maps . newHashMap ( ) ; // add original this . renderable
map . put ( SwissKnife . getRealClassNameLowerCamelCase ( this . renderable ) , this . renderable ) ; this . renderable = map ; } // add object of this method
String key = SwissKnife . getRealClassNameLowerCamelCase ( object ) ; if ( map . containsKey ( key ) ) { throw new IllegalArgumentException ( String . format ( "Cannot store object with default name %s." + "An object with the same name is already stored." + "Consider using render(key, value) to name objects implicitly." , key ) ) ; } else { map . put ( SwissKnife . getRealClassNameLowerCamelCase ( object ) , object ) ; } } return this ;


signature:
public class Result { /** * Handles following cases :
 * 1 ) If this . renderable is null : a new HashMap is generated and this entry being added
 * to the map .
 * 2 ) If this . renderable is a Map : the entry is added
 * 3 ) If this . renderable is an object ( not a renderable ) : a Map is generated and both
 * the former object and the new entry are being added .
 * 4 ) If this . renderable is a Renderable : an { @ link IllegalArgumentException } is thrown .
 * If the entry key already exists in the map of this . renderable an { @ link IllegalArgumentException }
 * is thrown .
 * @ param entry The entry to add .
 * @ return The result for further chaining . */
public Result render ( Entry < String , Object > entry ) { } }

implementation: if ( this . renderable == null ) { Map < String , Object > map = Maps . newHashMap ( ) ; this . renderable = map ; map . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } else { assertObjectNoRenderableOrThrowException ( this . renderable ) ; Map < String , Object > map ; if ( this . renderable instanceof Map ) { map = ( Map ) this . renderable ; if ( map . containsKey ( entry . getKey ( ) ) ) { throw new IllegalArgumentException ( String . format ( "Entry with key %s already stored inside this Result object. " + "This is currently not supported and does not make sense. " + "Consider using your own map." , entry . getKey ( ) ) ) ; } else { map . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } else { map = Maps . newHashMap ( ) ; map . put ( SwissKnife . getRealClassNameLowerCamelCase ( this . renderable ) , this . renderable ) ; this . renderable = map ; } map . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return this ;


signature:
public class Result { /** * Implicitly generates a hashmap as object being rendered and adds
 * this key , value pair . If the object being rendered is already a hashmap
 * it simply adds this key value pair to it .
 * @ param key The key to use .
 * @ param value The value to use .
 * @ return The Result for chaining . */
public Result render ( String key , Object value ) { } }

implementation: render ( new AbstractMap . SimpleEntry < String , Object > ( key , value ) ) ; return this ;


signature:
public class Result { /** * This method directly renders the String to the output . It completely
 * bypasses any rendering engine .
 * Thus you can render anything you want .
 * Chaining of resultRaw ( ) . resultRaw ( ) . . . is NOT supported . Mixing with
 * render ( ) is NOT supported .
 * It is always recommended to implement your own RenderingEngine OR use
 * existing rendering engines .
 * Example : < code >
 * public Result controllerMethod ( ) {
 * String customJson = " { \ " user \ " : \ " john @ woo . com \ " } " ;
 * return Results . json ( ) . renderRaw ( customJson ) ;
 * < / code >
 * @ param string
 * The string to render .
 * @ return A result that will render the string directly to the output
 * stream .
 * @ deprecated = > use text ( ) . render ( string ) , html ( ) . render ( string ) ,
 * json ( ) . render ( string ) , xml ( ) . render ( string ) , or
 * contentType ( type ) . render ( string ) . */
@ Deprecated public Result renderRaw ( final String string ) { } }

implementation: Renderable renderable = new Renderable ( ) { @ Override public void render ( Context context , Result result ) { if ( result . getContentType ( ) == null ) { result . contentType ( Result . TEXT_PLAIN ) ; } ResponseStreams resultJsonCustom = context . finalizeHeaders ( result ) ; try ( Writer writer = resultJsonCustom . getWriter ( ) ) { writer . write ( string ) ; } catch ( IOException ioException ) { logger . error ( "Error rendering raw String via renderRaw(...)" , ioException ) ; } } } ; render ( renderable ) ; return this ;


signature:
public class Result { /** * This method directly renders the byte array to the output . It
 * completely bypasses any rendering engine .
 * Thus you can render anything you want .
 * Chaining of resultRaw ( ) . resultRaw ( ) . . . is NOT supported . Mixing with render ( )
 * is NOT supported .
 * It is always recommended to implement your own RenderingEngine OR
 * use existing rendering engines .
 * @ param bytes The bytes to render .
 * @ return A result that will render the string directly to the output stream . */
public Result renderRaw ( final byte [ ] bytes ) { } }

implementation: Renderable renderable = new Renderable ( ) { @ Override public void render ( Context context , Result result ) { if ( result . getContentType ( ) == null ) { result . contentType ( Result . APPLICATION_OCTET_STREAM ) ; } ResponseStreams responseStreams = context . finalizeHeaders ( result ) ; try ( OutputStream outputStream = responseStreams . getOutputStream ( ) ) { outputStream . write ( bytes ) ; } catch ( IOException ioException ) { throw new InternalServerErrorException ( ioException ) ; } } } ; render ( renderable ) ; return this ;


signature:
public class Result { /** * Returns cookie with that name or null .
 * @ param cookieName Name of the cookie
 * @ return The cookie or null if not found . */
public Cookie getCookie ( String cookieName ) { } }

implementation: for ( Cookie cookie : getCookies ( ) ) { if ( cookie . getName ( ) . equals ( cookieName ) ) { return cookie ; } } return null ;


signature:
public class Result { /** * A redirect that uses 303 see other .
 * @ param url
 * The url used as redirect target .
 * @ return A nicely configured result with status code 303 and the url set
 * as Location header . */
public Result redirect ( String url ) { } }

implementation: status ( Result . SC_303_SEE_OTHER ) ; addHeader ( Result . LOCATION , url ) ; return this ;


signature:
public class Result { /** * A redirect that uses 307 see other .
 * @ param url
 * The url used as redirect target .
 * @ return A nicely configured result with status code 307 and the url set
 * as Location header . */
public Result redirectTemporary ( String url ) { } }

implementation: status ( Result . SC_307_TEMPORARY_REDIRECT ) ; addHeader ( Result . LOCATION , url ) ; return this ;


signature:
public class Result { /** * This function sets
 * Cache - Control : no - cache , no - store
 * Date : ( current date )
 * Expires : 1970
 * = > it therefore effectively forces the browser and every proxy in between
 * not to cache content .
 * See also https : / / devcenter . heroku . com / articles / increasing - application - performance - with - http - cache - headers
 * @ return this result for chaining . */
public Result doNotCacheContent ( ) { } }

implementation: addHeader ( CACHE_CONTROL , CACHE_CONTROL_DEFAULT_NOCACHE_VALUE ) ; addHeader ( DATE , DateUtil . formatForHttpHeader ( System . currentTimeMillis ( ) ) ) ; addHeader ( EXPIRES , DateUtil . formatForHttpHeader ( 0L ) ) ; return this ;


signature:
public class NinjaPropertiesImplTool { /** * This method checks that your configurations have set a
 * application . secret = 23r213r12r123
 * If application . secret is missing or is empty it will do the following :
 * - In dev and test mode it ' ll generate a new application secret and write the secret
 * to both src / main / java / conf / application . conf and the classes dir were the compiled stuff
 * goes .
 * - In prod it will throw a runtime exception and stop the server . */
public static void checkThatApplicationSecretIsSet ( boolean isProd , String baseDirWithoutTrailingSlash , PropertiesConfiguration defaultConfiguration , Configuration compositeConfiguration ) { } }

implementation:
String applicationSecret = compositeConfiguration . getString ( NinjaConstant . applicationSecret ) ; if ( applicationSecret == null || applicationSecret . isEmpty ( ) ) { // If in production we stop the startup process . It simply does not make
// sense to run in production if the secret is not set .
if ( isProd ) { String errorMessage = "Fatal error. Key application.secret not set. Please fix that." ; logger . error ( errorMessage ) ; throw new RuntimeException ( errorMessage ) ; } logger . info ( "Key application.secret not set. Generating new one and setting in conf/application.conf." ) ; // generate new secret
String secret = SecretGenerator . generateSecret ( ) ; // set in overall composite configuration = > this enables this instance to
// start immediately . Otherwise we would have another build cycle .
compositeConfiguration . setProperty ( NinjaConstant . applicationSecret , secret ) ; // defaultConfiguration is : conf / application . conf ( not prefixed )
defaultConfiguration . setProperty ( NinjaConstant . applicationSecret , secret ) ; try { // STEP 1 : Save in source directories :
// save to compiled version = > in src / main / target /
String pathToApplicationConfInSrcDir = baseDirWithoutTrailingSlash + File . separator + "src" + File . separator + "main" + File . separator + "java" + File . separator + NinjaProperties . CONF_FILE_LOCATION_BY_CONVENTION ; Files . createParentDirs ( new File ( pathToApplicationConfInSrcDir ) ) ; // save to source
defaultConfiguration . save ( pathToApplicationConfInSrcDir ) ; // STEP 2 : Save in classes dir ( target / classes or similar ) .
// save in target directory ( compiled version aka war aka classes dir )
defaultConfiguration . save ( ) ; } catch ( ConfigurationException e ) { logger . error ( "Error while saving new secret to application.conf." , e ) ; } catch ( IOException e ) { logger . error ( "Error while saving new secret to application.conf." , e ) ; } }


signature:
public class AssetsControllerHelper { /** * If we get - for whatever reason - a relative URL like
 * assets / . . / conf / application . conf we expand that to the " real " path . In the
 * above case conf / application . conf .
 * You should then add the assets prefix .
 * Otherwise someone can create an attack and read all resources of our app .
 * If we expand and normalize the incoming path this is no longer possible .
 * @ param fileName A potential " fileName "
 * @ param enforceUnixSeparator If true it will force the usage of the unix separator ' / '
 * If false it will use the separator of the underlying system .
 * usually ' / ' in case of unix and ' \ ' in case of windows .
 * @ return A normalized fileName . */
public String normalizePathWithoutLeadingSlash ( String fileName , boolean enforceUnixSeparator ) { } }

implementation: String fileNameNormalized = enforceUnixSeparator ? FilenameUtils . normalize ( fileName , true ) : FilenameUtils . normalize ( fileName ) ; return StringUtils . removeStart ( fileNameNormalized , "/" ) ;


signature:
public class AssetsControllerHelper { /** * Check the URL is a directory .
 * With war style deployment , AssetsController exposes the file list of assets directories .
 * For example , a request to http : / / localhost : 8080 / assets / css / displays the file list of css directory .
 * So this method checks the URL is a directory .
 * @ param url A URL of assets
 * @ return true if the URL is a directory */
public boolean isDirectoryURL ( URL url ) { } }

implementation: try { return url . getProtocol ( ) . equals ( "file" ) && new File ( url . toURI ( ) ) . isDirectory ( ) ; } catch ( URISyntaxException e ) { logger . error ( "Could not URL convert to URI" , e ) ; } return false ;


signature:
public class StickyListHeadersAdapterDecorator { /** * Sets the { @ link se . emilsjolander . stickylistheaders . StickyListHeadersListView } that this adapter will be bound to . */
public void setStickyListHeadersListView ( @ NonNull final StickyListHeadersListView listView ) { } }

implementation: ListViewWrapper stickyListHeadersListViewWrapper = new StickyListHeadersListViewWrapper ( listView ) ; setListViewWrapper ( stickyListHeadersListViewWrapper ) ;


signature:
public class StickyListHeadersAdapterDecorator { /** * Animates given View if necessary .
 * @ param position the position of the item the View represents .
 * @ param view the View that should be animated .
 * @ param parent the parent the View is hosted in . */
private void animateViewIfNecessary ( final int position , @ NonNull final View view , @ NonNull final ViewGroup parent ) { } }

implementation: Animator [ ] childAnimators ; if ( getDecoratedBaseAdapter ( ) instanceof AnimationAdapter ) { childAnimators = ( ( AnimationAdapter ) getDecoratedBaseAdapter ( ) ) . getAnimators ( parent , view ) ; } else { childAnimators = new Animator [ 0 ] ; } Animator alphaAnimator = ObjectAnimator . ofFloat ( view , ALPHA , 0 , 1 ) ; assert mViewAnimator != null ; mViewAnimator . animateViewIfNecessary ( position , view , AnimatorUtil . concatAnimators ( childAnimators , new Animator [ 0 ] , alphaAnimator ) ) ;


signature:
public class SwipeUndoAdapter { /** * Sets the { @ link com . nhaarman . listviewanimations . itemmanipulation . swipedismiss . DismissableManager } to specify which views can or cannot be swiped .
 * @ param dismissableManager { @ code null } for no restrictions . */
public void setDismissableManager ( @ Nullable final DismissableManager dismissableManager ) { } }

implementation: if ( mSwipeUndoTouchListener == null ) { throw new IllegalStateException ( "You must call setAbsListView() first." ) ; } mSwipeUndoTouchListener . setDismissableManager ( dismissableManager ) ;


signature:
public class AnimationAdapter { /** * Call this method to reset animation status on all views . The next time { @ link # notifyDataSetChanged ( ) } is called on the base adapter , all views will animate again . */
public void reset ( ) { } }

implementation: if ( getListViewWrapper ( ) == null ) { throw new IllegalStateException ( "Call setAbsListView() on this AnimationAdapter first!" ) ; } assert mViewAnimator != null ; mViewAnimator . reset ( ) ; mGridViewPossiblyMeasuring = true ; mGridViewMeasuringPosition = - 1 ; if ( getDecoratedBaseAdapter ( ) instanceof AnimationAdapter ) { ( ( AnimationAdapter ) getDecoratedBaseAdapter ( ) ) . reset ( ) ; }


signature:
public class AnimationAdapter { /** * Animates given View if necessary .
 * @ param position the position of the item the View represents .
 * @ param view the View that should be animated .
 * @ param parent the parent the View is hosted in . */
private void animateViewIfNecessary ( final int position , @ NonNull final View view , @ NonNull final ViewGroup parent ) { } }

implementation:
assert mViewAnimator != null ; /* GridView measures the first View which is returned by getView ( int , View , ViewGroup ) , but does not use that View .
 On KitKat , it does this actually multiple times .
 Therefore , we animate all these first Views , and reset the last animated position when we suspect GridView is measuring . */
mGridViewPossiblyMeasuring = mGridViewPossiblyMeasuring && ( mGridViewMeasuringPosition == - 1 || mGridViewMeasuringPosition == position ) ; if ( mGridViewPossiblyMeasuring ) { mGridViewMeasuringPosition = position ; mViewAnimator . setLastAnimatedPosition ( - 1 ) ; } Animator [ ] childAnimators ; if ( getDecoratedBaseAdapter ( ) instanceof AnimationAdapter ) { childAnimators = ( ( AnimationAdapter ) getDecoratedBaseAdapter ( ) ) . getAnimators ( parent , view ) ; } else { childAnimators = new Animator [ 0 ] ; } Animator [ ] animators = getAnimators ( parent , view ) ; Animator alphaAnimator = ObjectAnimator . ofFloat ( view , ALPHA , 0 , 1 ) ; Animator [ ] concatAnimators = AnimatorUtil . concatAnimators ( childAnimators , animators , alphaAnimator ) ; mViewAnimator . animateViewIfNecessary ( position , view , concatAnimators ) ;


signature:
public class AnimationAdapter { /** * Returns a Parcelable object containing the AnimationAdapter ' s current dynamic state . */
@ NonNull public Parcelable onSaveInstanceState ( ) { } }

implementation: Bundle bundle = new Bundle ( ) ; if ( mViewAnimator != null ) { bundle . putParcelable ( SAVEDINSTANCESTATE_VIEWANIMATOR , mViewAnimator . onSaveInstanceState ( ) ) ; } return bundle ;


signature:
public class AnimationAdapter { /** * Restores this AnimationAdapter ' s state .
 * @ param parcelable the Parcelable object previously returned by { @ link # onSaveInstanceState ( ) } . */
public void onRestoreInstanceState ( @ Nullable final Parcelable parcelable ) { } }

implementation: if ( parcelable instanceof Bundle ) { Bundle bundle = ( Bundle ) parcelable ; if ( mViewAnimator != null ) { mViewAnimator . onRestoreInstanceState ( bundle . getParcelable ( SAVEDINSTANCESTATE_VIEWANIMATOR ) ) ; } }


signature:
public class ArrayAdapter { /** * Appends the specified element to the end of the { @ code List } .
 * @ param object the object to add .
 * @ return always true . */
public boolean add ( @ NonNull final T object ) { } }

implementation: boolean result = mItems . add ( object ) ; notifyDataSetChanged ( ) ; return result ;


signature:
public class ArrayAdapter { /** * Adds the objects in the specified collection to the end of this List . The objects are added in the order in which they are returned from the collection ' s iterator .
 * @ param collection the collection of objects .
 * @ return { @ code true } if this { @ code List } is modified , { @ code false } otherwise . */
public boolean addAll ( @ NonNull final Collection < ? extends T > collection ) { } }

implementation: boolean result = mItems . addAll ( collection ) ; notifyDataSetChanged ( ) ; return result ;


signature:
public class DragAndDropHandler { /** * Starts dragging the item at given position . User must be touching this { @ code DynamicListView } .
 * @ param position the position of the item in the adapter to start dragging . Be sure to subtract any header views .
 * @ throws java . lang . IllegalStateException if the user is not touching this { @ code DynamicListView } ,
 * or if there is no adapter set . */
public void startDragging ( final int position ) { } }

implementation:
if ( mMobileItemId != INVALID_ID ) { /* We are already dragging */
return ; } if ( mLastMotionEventY < 0 ) { throw new IllegalStateException ( "User must be touching the DynamicListView!" ) ; } if ( mAdapter == null ) { throw new IllegalStateException ( "This DynamicListView has no adapter set!" ) ; } if ( position < 0 || position >= mAdapter . getCount ( ) ) { /* Out of bounds */
return ; } mMobileView = mWrapper . getChildAt ( position - mWrapper . getFirstVisiblePosition ( ) + mWrapper . getHeaderViewsCount ( ) ) ; if ( mMobileView != null ) { mOriginalMobileItemPosition = position ; mMobileItemId = mAdapter . getItemId ( position ) ; mHoverDrawable = new HoverDrawable ( mMobileView , mLastMotionEventY ) ; mMobileView . setVisibility ( View . INVISIBLE ) ; }


signature:
public class DragAndDropHandler { /** * Dispatches the { @ link android . view . MotionEvent } s to their proper methods if applicable .
 * @ param event the { @ code MotionEvent } .
 * @ return { @ code true } if the event was handled , { @ code false } otherwise . */
@ Override public boolean onTouchEvent ( @ NonNull final MotionEvent event ) { } }

implementation:
boolean handled = false ; /* We are in the process of animating the hover drawable back , do not start a new drag yet . */
if ( ! mIsSettlingHoverDrawable ) { switch ( event . getAction ( ) & MotionEvent . ACTION_MASK ) { case MotionEvent . ACTION_DOWN : mLastMotionEventY = event . getY ( ) ; handled = handleDownEvent ( event ) ; break ; case MotionEvent . ACTION_MOVE : mLastMotionEventY = event . getY ( ) ; handled = handleMoveEvent ( event ) ; break ; case MotionEvent . ACTION_UP : handled = handleUpEvent ( ) ; mLastMotionEventY = - 1 ; break ; case MotionEvent . ACTION_CANCEL : handled = handleCancelEvent ( ) ; mLastMotionEventY = - 1 ; break ; default : handled = false ; break ; } } return handled ;


signature:
public class DragAndDropHandler { /** * Handles the down event .
 * Finds the position and { @ code View } of the touch point and , if allowed by the { @ link com . nhaarman . listviewanimations . itemmanipulation . dragdrop . DraggableManager } ,
 * starts dragging the { @ code View } .
 * @ param event the { @ link android . view . MotionEvent } that was triggered .
 * @ return { @ code true } if we have started dragging , { @ code false } otherwise . */
private boolean handleDownEvent ( @ NonNull final MotionEvent event ) { } }

implementation: mDownX = event . getRawX ( ) ; mDownY = event . getRawY ( ) ; return true ;


signature:
public class DragAndDropHandler { /** * Retrieves the position in the list corresponding to itemId .
 * @ return the position of the item in the list , or { @ link android . widget . AdapterView # INVALID _ POSITION } if the { @ code View } corresponding to the id was not found . */
private int getPositionForId ( final long itemId ) { } }

implementation: View v = getViewForId ( itemId ) ; if ( v == null ) { return AdapterView . INVALID_POSITION ; } else { return mWrapper . getPositionForView ( v ) ; }