### Check Maven Version Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/getting_started/installing_ninja.md Verifies the installed Apache Maven version. Requires Maven to be in the system's PATH. ```shell mvn -version ``` -------------------------------- ### Check Java Version Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/getting_started/installing_ninja.md Verifies the installed Java Development Kit (JDK) version. Requires Java to be in the system's PATH. ```shell java -version ``` -------------------------------- ### Ninja Controller Example Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/getting_started/the_mvc_pattern.md Demonstrates a basic controller class in Ninja. Controller methods must return a 'Result' object, which handles the HTTP response. This example shows a simple index method returning an HTML response. ```Java public class ApplicationController { public Result index() { return Results.html(); } } ``` -------------------------------- ### Ninja View Template Example Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/getting_started/the_mvc_pattern.md A simple Freemarker template for a view. Views are typically stored in `views//.ftl.html`. This example shows a basic HTML structure with a heading. ```Freemarker

Hello world

``` -------------------------------- ### Update web.xml for Ninja Framework Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md Provides an example of the required web.xml structure for Ninja Framework versions 1.1 to 1.2, including namespace declarations. ```xml .... ``` -------------------------------- ### Referencing Ninja Properties Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Demonstrates how Ninja properties can reference other properties using `${propertyName}` syntax, allowing for dynamic configuration. ```properties serverName=myserver.com serverPort=80 fullServerName=${serverName}:${serverPort} ``` -------------------------------- ### Configuring SSL Keystore and Truststore Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Settings for specifying the location and password for SSL keystore and truststore files. ```properties ninja.ssl.keystore.uri=file:///var/etc/mysite.keystore ninja.ssl.keystore.password=changeit ninja.ssl.truststore.uri=file:///var/etc/mysite.truststore ninja.ssl.truststore.password=changeit ``` -------------------------------- ### Setting Ninja Mode Programmatically Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Demonstrates setting the Ninja application mode programmatically by using `System.setProperty`. ```java System.setProperty(NinjaConstant.MODE_KEY_NAME, NinjaConstant.MODE_DEV) ``` -------------------------------- ### Start Ninja Console Application with Custom Java Main Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/console.md Provides an example of programmatically starting a Ninja console application within a custom Java main method. This allows for configuration, such as setting the NinjaMode, and accessing the Guice injector before application shutdown. ```java import ninja.standalone.NinjaConsole; import ninja.utils.NinjaMode; public class MyMain { static public void main(String[] args) throws Exception { NinjaConsole ninja = new NinjaConsole() .ninjaMode(NinjaMode.prod) .start(); // other code (e.g. access guice injector) // ninja.getInjector(); ninja.shutdown(); } } ``` -------------------------------- ### SecureFilter Implementation Example Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/filters.md Provides an example implementation of a `SecureFilter` in Java, demonstrating how to check session data for authentication and either proceed with the request chain or return a forbidden response. ```java public class SecureFilter implements Filter { /** If a username is saved we assume the session is valid */ public final String USERNAME = "username"; @Override public Result filter(FilterChain chain, Context context) { // if we got no cookies we break: if (context.getSession() == null || context.getSession().get(USERNAME) == null) { return Results.forbidden().html().template("/views/forbidden403.ftl.html"); } else { return chain.next(context); } } ``` -------------------------------- ### Install MetricsModule in Module.java Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/metrics.md Install the MetricsModule in your application's Guice Module class to activate Ninja Metrics. ```java package conf; import com.google.inject.AbstractModule; import javax.inject.Singleton; import ninja.metrics.MetricsModule; @Singleton public class Module extends AbstractModule { @Override protected void configure() { install(new MetricsModule()); } } ``` -------------------------------- ### Update Static Asset Serving Routes Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md Replaces the deprecated serve method with serveStatic and serveWebJars for handling static assets and webjars. Demonstrates direct replacement and serving from root. ```java router.GET().route("/assets/.*\").with(AssetsController.class, "serve"); ``` ```java router.GET().route("/assets/webjars/{fileName: .*}\").with(AssetsController.class, "serveWebJars"); router.GET().route("/assets/{fileName: .*}\").with(AssetsController.class, "serveStatic"); ``` ```java router.GET().route("/robots.txt\").with(AssetsController.class, "serveStatic"); ``` -------------------------------- ### Run Ninja Application Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/working_with_relational_dbs/jpa.md Command to package and run a Ninja web application. This command is used after generating or developing a Ninja project to start the server. ```Maven mvn package ninja:run ``` -------------------------------- ### Ninja Route Definition Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/getting_started/the_mvc_pattern.md Illustrates how to define application routes in Ninja. The `Routes.java` file maps URL paths to specific controller methods. This example maps the root URL '/' to the `index` method of `ApplicationController`. ```Java public class Routes implements ApplicationRoutes { @Override public void init(Router router) { router.GET().route("/").with(ApplicationController::index); } } ``` -------------------------------- ### Ninja Framework File Upload Demo Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-integration-test/src/main/java/views/ApplicationController/index.ftl.html Provides an example of how to handle file uploads using the Ninja Framework. ```APIDOC GET /upload Description: Entry point to the file upload demo. POST /upload Description: Handles the uploaded file. Parameters: - Request Body: Multipart form data containing the file. Returns: Confirmation of upload or file processing result. ``` -------------------------------- ### Build and Run Ninja Application in SuperDevMode Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/getting_started/create_your_first_application.md Commands to navigate into your generated project directory, build the project using Maven, and then start Ninja's SuperDevMode. SuperDevMode allows for fast and responsive development cycles. ```Shell cd MY_INSTALLED_PROJECT mvn clean install mvn ninja:run ``` -------------------------------- ### Ninja Framework Redirect Example Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-integration-test/src/main/java/views/PrettyTimeController/index.ftl.html Illustrates a basic redirect functionality within the Ninja Framework. It shows how a URL path can be configured to redirect users to another page, in this case, back to the index. ```html A redirect at /redirects back to index... [/redirect](/redirect) ``` -------------------------------- ### Disabling HTTP and Enabling HTTPS Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Configuration to disable the standard HTTP connector and only run the HTTPS connector. ```properties ninja.port=-1 # disable clear text http connector ninja.ssl.port=8443 # enable ssl https connector ``` -------------------------------- ### Ninja Framework Routing Examples Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-integration-test/src/main/java/views/ApplicationController/index.ftl.html Illustrates various routing patterns supported by Ninja Framework, including default routes, parameterized routes, and redirects. ```APIDOC GET / Description: Default route, often the home page. GET /route_with_result Description: A route that returns a specific result. GET /user/{id}/{name}/userDashboard Description: A parameterized route accepting user ID and name. Parameters: - id: User identifier (e.g., integer). - name: User's name (e.g., string). Example Path: /user/12345/john_user/userDashboard GET /redirect Description: A route that performs a redirect to another page (e.g., index). ``` -------------------------------- ### Example Flyway SQL Migration Script Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/working_with_relational_dbs/db_migrations.md Demonstrates a basic SQL script for database schema evolution using Flyway's naming convention (V1__...). This script creates a 'GuestbookEntry' table and a sequence. ```sql -- Just a simple table create table GuestbookEntry ( id int8 not null, email varchar(255), text varchar(255), primary key (id) ); --needed for hibernate running on postgresql create sequence hibernate_sequence; ``` -------------------------------- ### Basic HTML Template Example Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/html_templating/getting_started.md A fundamental HTML template file using the Freemarker templating engine. Templates are typically stored in the 'views/' directory and use the '.ftl.html' extension by default. ```freemarker My title ``` -------------------------------- ### Running Ninja with SSL Port via Maven Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md How to run the Ninja application with a specific SSL port using the Maven plugin. ```bash mvn ninja:run -Dninja.ssl.port=8443 ``` -------------------------------- ### Configure JPA and Migration Modules in Guice Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md In version 6.7.0, you need to explicitly install JpaModule and MigrationClassicModule in your Guice Module to enable database support. ```java import com.google.inject.AbstractModule; import com.google.inject.Singleton; import ninja.NinjaProperties; import ninja.jpa.JpaModule; import ninja.migrations.MigrationClassicModule; @Singleton public class Module extends AbstractModule { private final NinjaProperties ninjaProperties; public Module(NinjaProperties ninjaProperties) { this.ninjaProperties = ninjaProperties; } @Override protected void configure() { install(new JpaModule(ninjaProperties)); install(new MigrationClassicModule()); // ... likely more modules... } } ``` -------------------------------- ### Install NinjaPostofficeModule Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/sending_mail.md Install the NinjaPostofficeModule in your Ninja application's Module.java file to activate the postoffice functionality. ```Java @Singleton public class Module extends AbstractModule { @Override protected void configure() { install(new NinjaPostofficeModule()); } } ``` -------------------------------- ### Ninja Service Lifecycle: @Start and @Dispose Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/lifecycle.md Demonstrates how to use the `@Start` and `@Dispose` annotations in Ninja Framework to control the order of service startup and shutdown. The `order` attribute specifies the execution priority, with higher numbers indicating later execution. ```java @Singleton public class MyService { @Start(order = 90) public void startService() { //do something } @Dispose(order = 90) public void stopService() { //do something } public Result getCount(Context ctx) { return Results.json(count.get()); } } ``` -------------------------------- ### Enabling SSL/HTTPS in Ninja Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Configuration to enable HTTPS support in Ninja, including setting the SSL port. ```properties ninja.ssl.port=8443 ``` -------------------------------- ### Basic Route Definition with Regex Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/routing.md Defines a GET route that matches any path starting with '/assets/' followed by any characters, mapping it to a controller method. The '.*' is a regular expression matching zero or more arbitrary characters. ```Java router.GET().route("/assets/.*\").with(AssetsController::serveArbitrary); ``` -------------------------------- ### Configure Application Base Package Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Demonstrates how to set the `application.modules.package` property in `application.conf` to specify custom package locations for Routes and Guice application configuration modules. ```conf application.modules.package=com.someorganinization.somepackage ``` -------------------------------- ### Setting Ninja Mode via Command Line Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md How to set the Ninja application mode (e.g., `dev`, `test`, `prod`) using a Java system property on the command line. ```bash java -Dninja.mode=dev ``` -------------------------------- ### Define GET Route with Instance Method Reference Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/routing.md Maps a GET request to a specific path using a method reference to an instance method of a particular controller object. Guice does not manage this instance. ```Java public class Routes implements ApplicationRoutes { @Override public void init(Router router) { AppController controller = new AppController(); router.GET().route("/").with(controller::index); } } ``` -------------------------------- ### Ninja External Configuration via System Property Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/security/getting_started.md Demonstrates how to point to an alternate configuration file for production settings using a system variable. This is useful for managing production-specific secrets like the application secret. ```shell ... -Dninja.external.configuration=/mydir/deployment.conf ``` -------------------------------- ### Ninja Application Properties Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Basic configuration properties for a Ninja application, such as application name and cookie prefix. These are typically stored in `application.conf`. ```properties application.name=Ninja demo application application.cookie.prefix=NINJA ``` -------------------------------- ### Example Logback Configuration (logback.xml) Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/logging.md A sample logback.xml file illustrating how to define appenders for file and console output, along with a root logger configuration. This file is automatically picked up by Logback if placed in the application's root. ```XML myApp.log %date %level [%thread] %logger{10} [%file:%line] %msg%n %msg%n ``` -------------------------------- ### Simple Freemarker View Example Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/basic_concepts.md Views are templates used to render the final output. By convention, views are stored in `views/CONTROLLER_NAME/METHOD_NAME.ftl.html` for Freemarker. ```html

Hello world

``` -------------------------------- ### Environment-Specific Memcached Configuration Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/using_the_cache.md Example of configuring Memcached specifically for the production environment using profile-specific properties in application.conf. ```properties %prod.cache.implementation=ninja.cache.CacheMemcachedImpl ``` -------------------------------- ### Ninja Framework Layout Template Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-archetype-simple/src/main/resources/archetype-resources/src/main/java/views/layout/defaultLayout.ftl.html This snippet shows a basic layout template using FreeMarker syntax for the Ninja Framework. It includes setting variables, defining a macro, including other templates, and conditional display of flash messages. ```freemarker #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) <${symbol_pound}macro myLayout title="Layout example"> ${symbol_dollar}{title} body { padding-top: 60px; padding-bottom: 40px; } .error-template {padding: 40px 15px;text-align: center;} <${symbol_pound}include "header.ftl.html"/> <${symbol_pound}if (flash.error)??> ${symbol_dollar}{flash.error} <${symbol_pound}if (flash.success)??> ${symbol_dollar}{flash.success} <${symbol_pound}nested/> <${symbol_pound}include "footer.ftl.html"/> ``` -------------------------------- ### META-INF/persistence.xml Configuration Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/working_with_relational_dbs/jpa.md Example META-INF/persistence.xml file demonstrating JPA persistence unit configuration for development and production environments, including Hibernate dialect and C3P0 connection pooling settings. ```xml org.hibernate.jpa.HibernatePersistenceProvider org.hibernate.jpa.HibernatePersistenceProvider ``` -------------------------------- ### Run ninja:run command Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/super_dev_mode.md Execute the Maven command to start Ninja's SuperDevMode, which provides a fast hot-reload code server. ```bash mvn ninja:run ``` -------------------------------- ### Accessing Properties via NinjaProperties Injection Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Shows how to inject `NinjaProperties` into a Java class to retrieve configuration values programmatically. ```java @Inject NinjaProperties ninjaProperties; public void myMethod() { String value = ninjaProperties.get("fullServerName") // ... do even more... } ``` -------------------------------- ### FreeMarker Layout Macro Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-jpa-blog-integration-test/src/main/java/views/layout/defaultLayout.ftl.html Defines a reusable layout macro named 'myLayout' that accepts a 'title' parameter. It includes basic CSS styling for the body and placeholders for header, footer, and dynamic content. ```freemarker <#macro myLayout title="Layout example"> ${title} body { padding-top: 60px; padding-bottom: 40px; } <#include "header.ftl.html"/> <#if (flash.error)??> ${flash.error} <#if (flash.success)??> ${flash.success} <#nested/> <#include "footer.ftl.html"/> ``` -------------------------------- ### Configure Ninja Servlet Dependency Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md Details the change from 'ninja-core' to 'ninja-servlet' artifactId in pom.xml for Ninja Framework versions 1.2 to 1.3. ```xml org.ninjaframework ninja-servlet 1.3 ``` -------------------------------- ### Test Homepage Request with NinjaTestBrowser Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/testing_your_application/ninja_test.md Demonstrates using NinjaTestBrowser to make a GET request to the application's homepage. It shows how to retrieve the response content and assert its presence, verifying basic page functionality and content. ```java public class ApplicationControllerTest extends NinjaTest { @Before public void setup() { ninjaTestBrowser.makeRequest(getServerAddress() + "setup"); } @Test public void testThatHomepageWorks() { // /redirect will send a location: redirect in the headers String result = ninjaTestBrowser.makeRequest(getServerAddress() + "/"); // If the redirect has worked we must see the following text // from the index screen: assertTrue(result.contains("Hello to the blog example!")); assertTrue(result.contains("My second post")); } } ``` -------------------------------- ### Mode-Specific Property Configuration Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Configuring properties that vary based on the application's mode (e.g., `dev`, `test`, `prod`) using a prefix convention. ```properties database.name=database_production # will be used when no mode is set (or prod) %prod.database.name=database_prod # will be used when running in prod mode %dev.database.name=database_dev # will be used when running in dev mode %test.database.name=database_test # will be used when running in test mode ``` -------------------------------- ### Ninja: Render User Object with Content Negotiation Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/controllers.md Example of a Java controller method that retrieves a User object and renders it. Ninja automatically handles content negotiation based on the 'Accept' header, defaulting to JSON or XML. ```java public Result getUser() { User user = userDao.getUser(); return Results.ok().render(user); } ``` -------------------------------- ### Override Properties with NinjaTestServer Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/testing_your_application/getting_started.md Illustrates how to override Ninja configuration properties programmatically when starting the NinjaTestServer. This is useful for dynamic configurations, such as integrating with testcontainers for databases. ```java import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import ninja.NinjaTestServer; public class DatabaseBaseTest { // Let's assume ARunningPostgresServer encapsulates a Testcontainer running // a Postgres instance. // More here: https://www.testcontainers.org/test_framework_integration/manual_lifecycle_control/ // Once the Postgres Docker container is running Testcontainers can return as the jdbc url public String jdbcUrl = "jdbc:postgresql://localhost:5432/testdb"; // Example URL @Before public void showcase_test() { // Now we start Ninja. // Make sure we set the property. That property will then be picked up // by anything that gets properties from NinjaProperties like for instance Flyway and NinjaDb. NinjaTestServer ninjaTestServer = NinjaTestServer.builder() .overrideProperties(ImmutableMap.of("application.datasource.default.url", jdbcUrl)) .build(); // ... now you can do your tests on that Ninja instance // ... at the end we again shut down Ninja ninjaTestServer.shutdown(); } // Dummy Test method to satisfy @Test annotation if needed for a class @Test public void dummyTest() { // This method is just a placeholder to make the class runnable as a JUnit test. // The actual test logic is in the @Before method. } } ``` -------------------------------- ### Ninja Framework Filter and Session Examples Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-integration-test/src/main/java/views/ApplicationController/index.ftl.html Demonstrates the usage of Ninja's filter chain and session management features, including security filters and flash cookie support. ```APIDOC GET /filter Description: Demonstrates a working security filter. GET /teapot Description: A filter that generates output, changes status, and disallows further filter chain execution. GET /session Description: Demonstrates Ninja's session support, typically using signed cookies. GET /flash_success Description: Displays a success message transmitted via a flash cookie. GET /flash_error Description: Displays an error message transmitted via a flash cookie. GET /flash_any Description: Displays an arbitrary flash message transmitted via a flash cookie. ``` -------------------------------- ### Configure Logback via application.conf Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/logging.md This example shows how to use the application.conf file to dynamically switch Logback configurations based on the application's environment (e.g., production or development). Ninja reads the specified file path to initialize Logback. ```Properties # An example for application.conf based configuration of logback %prod.logback.configurationFile=logback_prod.xml # will be used in production %dev.logback.configurationFile=logback_dev.xml # will be used in dev mode ``` -------------------------------- ### Freemarker Template Structure and Internationalization Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-archetype-simple/src/main/resources/archetype-resources/src/main/java/views/ApplicationController/index.ftl.html This snippet demonstrates the basic structure of a Freemarker template file (.ftl.html) used within the Ninja framework. It includes variable assignments, layout imports, macro calls, and expressions for internationalized text retrieval. ```ftl #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) <${symbol_pound}import "../layout/defaultLayout.ftl.html" as layout> <@layout.myLayout "Home page"> ${symbol_dollar}{i18n("hello.world")} ====================================== ${symbol_dollar}{i18n("hello.world.json")} [Hello World Json](/hello_world.json) ``` -------------------------------- ### Example Messages for English (en) in messages_en.properties Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/internationalization.md Contains key-value pairs for English language translations. These files follow the naming convention `messages_LANGUAGE.properties` and are used by the framework for internationalization. ```properties # registration.ftl.html cASINO_REGISTRATION_TITLE=Register cASINO_REGISTRATION_EMAIL=Your email cASINO_REGISTRATION_CONFIRM=Confirm cASINO_REGISTRATION_ACCEPT_TERMS_OF_SERVICE=Accept terms of service cASINO_REGISTRATION_REGISTER=Register cASINO_REGISTRATION_FLASH_ERROR=An error occurred. cASINO_YOUR_USERNAME=Your username is: {0} ``` -------------------------------- ### Maven Site Deployment Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/developer/getting_started.md Command to deploy the Ninja Framework website after a successful release. ```bash cd ninja-core mvn site site:deploy ``` -------------------------------- ### Java Test with NinjaFluentLeniumTest Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/testing_your_application/ninja_fluentlenium_test.md Demonstrates how to extend NinjaFluentLeniumTest to write browser tests. This example navigates to the homepage, checks the title, clicks a login element, and verifies the URL change. ```java import org.junit.Test; import static org.junit.Assert.*; public class ApplicationControllerFluentLeniumTest extends NinjaFluentLeniumTest { @Test public void testThatHomepageWorks() { goTo(getBaseUrl() + "/"); System.out.println("title: " + window().title()); assertTrue(window().title().contains("Home page")); $("#login").click(); assertTrue(url().contains("login")); } } ``` -------------------------------- ### Freemarker Main View Template Importing Layout Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/html_templating/getting_started.md An example of a main view template that imports a layout template (`defaultLayout.ftl.html`) and utilizes its macro (`myLayout`). It passes a specific title and content to be rendered within the layout. ```freemarker <#import "defaultLayout.ftl.html" as layout> <@layout.myLayout "Home page">

my text

``` -------------------------------- ### Add Ninja DB Classic Dependency Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md For version 6.7.0, JPA and Flyway were migrated to a separate maven module. Add the 'ninja-db-classic' dependency to your project. ```xml org.ninjaframework ninja-db-classic ${ninja.version} ``` -------------------------------- ### Add MySQL Connector Java Dependency Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md If you need to use the MySQL Driver with Flyway 8.2.x+, ensure the MySQL Connector/J dependency is present in your project. ```xml mysql mysql-connector-java 8.0.27 ``` -------------------------------- ### Override Configuration with System Properties Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Illustrates how system properties can override configuration keys. This includes direct overrides and mode-specific overrides using prefixes like `%test.key` for properties defined in `application.conf` or external files. ```shell java -Dninja.external.configuration=conf/production.conf -Ddb.connection.password=otherpass ``` ```shell java -Dninja.external.configuration=conf/production.conf -D%test.db.connection.password=otherpass ``` -------------------------------- ### Maven Settings for Release Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/developer/getting_started.md Configuration required in the .m2/settings.xml file for deploying to the central Maven repository and publishing the website. ```xml ossrh sonatype username sonatype password github-project-site git your_github_token_or_ssh_key_password ``` -------------------------------- ### Configure Ninja Dev Mode with Jetty Maven Plugin Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md Shows how to set the 'ninja.mode' system property to 'dev' when running Ninja with the Jetty Maven plugin, overriding the default 'prod' mode. ```xml org.eclipse.jetty jetty-maven-plugin .... ninja.mode dev ``` -------------------------------- ### Load External Configuration via System Property Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Explains how to use the `ninja.external.configuration` Java system property to load an external configuration file (e.g., `conf/production.conf`). Values in the external file override those in `conf/application.conf`. ```shell java -Dninja.external.configuration=conf/production.conf ``` -------------------------------- ### Ninja Framework Login Form Structure Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-jpa-blog-integration-test/src/main/java/views/LoginLogoutController/login.ftl.html This snippet illustrates the basic structure of a login page within the Ninja Framework. It includes importing a default layout, displaying internationalized labels for username and password fields, a 'Remember me' checkbox, and a login button. It also provides default user credentials for testing. ```ftl <#import "../layout/defaultLayout.ftl.html" as layout> <@layout.myLayout "Login"> **Pssst.** Default user is "bob@gmail.com" / password is "secret". ${i18n("login.username")} ${i18n("login.password")} checked\> Remember me ${i18n("login.loginNowButton")} ``` -------------------------------- ### Ninja Framework Layout Macro Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-integration-test/src/main/java/views/layout/defaultLayout.ftl.html This snippet demonstrates a FreeMarker macro for defining a reusable page layout in the Ninja framework. It accepts a title parameter and includes header, footer, and nested content sections, along with basic CSS for body padding. ```freemarker <#macro myLayout title="Layout example"> ${title} body { padding-top: 60px; padding-bottom: 40px; } <#include "header.ftl.html"/> <#nested/> <#include "footer.ftl.html"/> ``` ```css body { padding-top: 60px; padding-bottom: 40px; } ``` -------------------------------- ### Add Flyway MySQL Driver Dependency Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md For versions 8.2.x and later, Flyway no longer includes the MySQL driver due to licensing. Add this dependency to your pom.xml to use the MySQL driver. ```xml org.flywaydb flyway-mysql 8.2.2 ``` -------------------------------- ### NinjaCache Usage Example Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/using_the_cache.md Demonstrates injecting NinjaCache into a class and using its get/set methods to cache and retrieve data. It shows a common pattern for fetching data, checking the cache first, and setting it if not found. ```java @Inject NinjaCache ninjaCache; public Result allPosts() { List posts = ninjaCache.get("posts", List.class); if(posts == null) { posts = postDao.findAll(); ninjaCache.set("posts", posts, "30mn"); } return Results.html().render(posts); } ``` -------------------------------- ### Update Message Key Syntax for i18n Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md Demonstrates the updated syntax for including i18n messages in templates, favoring ${i18n("key")} over deprecated shorthand, and shows message formatting with variables. ```html ${i18n("myMessageKey")} ${i18n("myMessageKey", myVariable)} ``` -------------------------------- ### Generate Ninja Project with Maven Archetype Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/getting_started/create_your_first_application.md Uses Maven to generate a new Ninja project from the 'ninja-servlet-archetype-simple' archetype. You will be prompted to enter sensible values for 'groupId' and 'artifactId'. ```Maven mvn archetype:generate -DarchetypeGroupId=org.ninjaframework -DarchetypeArtifactId=ninja-servlet-archetype-simple ``` -------------------------------- ### FreeMarker Template for Article Display Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-jpa-blog-archetype/src/main/resources/archetype-resources/src/main/java/views/ApplicationController/index.ftl.html This snippet shows a FreeMarker template used in a Ninja Framework project. It includes directives for importing layouts, conditional rendering of articles, date formatting, and iterating over a list of older articles. It uses FreeMarker's built-in variables and expressions for dynamic content. ```ftl #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) <${symbol_pound}import "../layout/defaultLayout.ftl.html" as layout> <@layout.myLayout "Home page"> <${symbol_pound}if frontArticle??> [${symbol_dollar}{frontArticle.title}](/article/${symbol_dollar}{frontArticle.id}) =================================================================================== ${symbol_dollar}{frontArticle.postedAt?date} ${symbol_dollar}{frontArticle.content?no_esc} * * * <${symbol_pound}if olderArticles??> <${symbol_pound}list olderArticles as article> ### [${symbol_dollar}{article.title}](/article/${symbol_dollar}{article.id}) ${symbol_dollar}{article.postedAt?date} <${symbol_pound}endif> <${symbol_pound}else>

No articles found.

<${symbol_pound}endif> ``` -------------------------------- ### Update Flash Cookie Syntax in Freemarker Templates Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md Explains the change from underscore syntax to dot syntax for accessing flash cookies in ftl.html templates, improving consistency. ```html ${flash_error} becomes ${flash.error} ${flash_success} becomes ${flash.success} ${flash_anyMessage} becomes ${flash.anyMessage} ``` -------------------------------- ### Enable Ninja Session Encryption Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/security/getting_started.md Enables session encryption in the Ninja framework by setting a configuration property in `application.conf`. Ninja uses AES/128 by default, which can be strengthened by installing Java Cryptography Extensions. ```conf application.cookie.encryption=true ``` -------------------------------- ### Freemarker PrettyTime Localization Example Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-integration-test/src/main/java/views/PrettyTimeController/index.ftl.html Demonstrates how to use the PrettyTime library within Freemarker templates to format dates. It shows the conversion of a raw date object to a human-readable relative time string, leveraging implicit language settings. ```freemarker <#import "../layout/defaultLayout.ftl.html" as layout> <@layout.myLayout "Home page"> This demonstrates localized PrettyTime dates: ============================================= * * * PrettyTime in the templates --------------------------- ${date?date} = ${prettyTime(date)} ================================== ``` -------------------------------- ### Hot-reload Ninja Configuration with Java Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/configuration_and_modes.md Enables Ninja Framework to hot-reload configuration files during runtime by setting specific Java system properties. This avoids the need to restart the application for configuration changes. ```java java -Dninja.external.reload=true -Dninja.external.configuration=conf/production.conf ``` -------------------------------- ### Basic NinjaTestServer Usage Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/testing_your_application/getting_started.md Demonstrates how to create and use NinjaTestServer to test a running Ninja application. It shows how to obtain the base URL, retrieve Guice-injected instances, and shut down the server. ```java import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import com.google.inject.Injector; import ninja.NinjaTestServer; public class BasicNinjaTest { @Test public void showcaseBasicTest() { // Creating a TestServer is done like this NinjaTestServer ninjaTestServer = NinjaTestServer.builder().build(); // baseUrl is something like "http://localhost:5565" String baseUrl = ninjaTestServer.getBaseUrl(); // ... using this url you can now call endpoints, verify and test your application // You can also get instances that are initialized by Guice out of your testserver. // This is often useful if you want to assert functionality programmatically. // Like testing repositories and so on. MyRepository myRepository = ninjaTestServer.getInjector().getInstance(MyRepository.class); assertThat(myRepository.getNumberOfUsers()).isEqualTo(1); // Don't forget to shut down that instance. // You may also want to put this in a @After JUnit method. ninjaTestServer.shutdown(); } // Dummy MyRepository class for compilation public static class MyRepository { public int getNumberOfUsers() { return 1; } } } ``` -------------------------------- ### Initialize Ninja Application Configuration Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/deployment/war_based_deployment.md Run 'mvn ninja:run' at least once before packaging. This command generates essential configuration, including a unique secret in 'application.conf' used for signing application sessions, ensuring security. ```bash mvn ninja:run ``` -------------------------------- ### Define GET Route with Regex Path Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/routing.md Maps GET requests to paths matching a Java regular expression. This allows for flexible route matching based on patterns. ```Java // matches for instance "/assets/00012", "/assets/12334", ... router.GET().route("/assets/\\d*").with(AssetsController::serveDigits); // matches for instance "/assets/myasset.xml", "/assets/boing.txt", ... // router.GET().route("/assets/.*\\.(xml|txt)").with(AssetsController::serve); ``` -------------------------------- ### Implement WebSocket Handshake and Endpoint Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/websockets.md Provides an example of a WebSocket endpoint controller that extends javax.websocket.Endpoint and implements MessageHandler. The 'handshake' method handles the initial connection, allowing protocol negotiation and handshake acceptance/rejection. The 'onOpen' method is part of the standard JSR-356 lifecycle. ```java public class ChatWebSocket extends Endpoint implements MessageHandler.Whole { public Result handshake(Context context, WebSocketHandshake handshake) { // negotiate the protocol (not always used by clients) handshake.selectProtocol("chat"); // process handshake, save whatever you need, tell ninja to proceed // or return a failure result to reject the request return Results.webSocketContinue(); } @Override public void onOpen(Session session, EndpointConfig config) { // jsr-356 stuff here... } } ``` -------------------------------- ### Define GET Route with Direct Result Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/routing.md Maps a GET request to a path directly to a Result object, allowing for static page rendering or redirects without a dedicated controller method. ```Java public class Routes implements ApplicationRoutes { @Override public void init(Router router) { // a GET request to "/" will be redirect to "/dashboard" router.GET().route("/").with(() -> Results.redirect("/dashboard")); // show a static page router.GET().route("/dashboard").with(() -> Results.html().template("/dashboard.html")); } } ``` -------------------------------- ### Freemarker Logout Page Template Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-servlet-jpa-blog-archetype/src/main/resources/archetype-resources/src/main/java/views/LoginLogoutController/logout.ftl.html This snippet demonstrates setting variables for special characters and importing a layout file, followed by invoking a layout macro. It's typically used in web application templates to manage dynamic content and structure. ```freemarker #set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) <#import "../layout/defaultLayout.ftl.html" as layout> <@layout.myLayout "Home page"> You are now logged out. [Back to main page](/) ``` -------------------------------- ### Define GET Route with Method Reference Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/routing.md Maps a GET request to a specific path to a controller method using a Java method reference. The Router object is used to define this mapping. ```Java public class Routes implements ApplicationRoutes { @Override public void init(Router router) { // a GET request to "index" will be handled by a class called // "AppController" its method "index". router.GET().route("/index").with(AppController::index); } } ``` -------------------------------- ### Test Service Objects with NinjaRunner Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/testing_your_application/advanced.md Demonstrates using NinjaRunner to inject service objects into test classes, simplifying testing by handling dependency injection automatically. This approach eliminates the need for manual setup in @Before methods. ```Java @RunWith(NinjaRunner.class) public class DataServiceTest { @Inject private ServiceObj serviceObj; @Test public void testDataService() { assert (serviceObj != null); } } ``` -------------------------------- ### Maven Release Commands Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/developer/getting_started.md Sequence of Maven commands to execute for preparing and performing a release of the Ninja Framework. ```bash mvn release:clean mvn release:prepare mvn release:perform ``` -------------------------------- ### Define Routes in Ninja Framework Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/routing.md Demonstrates how to define GET routes in a Ninja application using the Router. It shows basic route mapping to controller methods and how to conditionally include routes based on application properties like production mode. ```Java public class Routes implements ApplicationRoutes { @Inject NinjaProperties ninjaProperties; @Override public void init(Router router) { // a GET request to "index" will be handled by a class called // "AppController" its method "index". router.GET().route("/index").with(AppController::index); ... // only active when not in production mode: if (!ninjaProperties.isProd) { router.GET().route("/setup").with(AppController::setup); } } } ``` -------------------------------- ### Define GET Route with Anonymous Lambda Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/basic_concepts/routing.md Maps a GET request to a path using an anonymously defined lambda expression. This lambda can accept zero or more arguments, with injection limited to type-based for Context. ```Java public class Routes implements ApplicationRoutes { @Override public void init(Router router) { router.GET().route("/").with(() -> Results.redirect("/home")); router.GET().route("/home").with((Context context) -> Results.ok()); } } ``` -------------------------------- ### Session and Flash Scope Renaming Source: https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/site/markdown/documentation/upgrade_guide.md API documentation for changes in session and flash scope management. SessionCookie has been renamed to Session, and FlashCookie to FlashScope. The Context object now provides updated methods to access these scopes. ```APIDOC Class Renaming: - SessionCookie -> Session - FlashCookie -> FlashScope Context Object Methods: - getSession() - Returns the current Session object. - getFlashScope() - Returns the current FlashScope object. ```