@Inject public SessionImpl(Crypto crypto, CookieEncryption encryption, NinjaProperties ninjaProperties, Clock clock) { this.crypto = crypto; this.encryption = encryption; this.time = clock; // read configuration stuff: Integer sessionExpireTimeInSeconds = ninjaProperties .getInteger(NinjaConstant.sessionExpireTimeInSeconds); if (sessionExpireTimeInSeconds != null) { this.defaultSessionExpireTimeInMs = sessionExpireTimeInSeconds * 1000L; } else { this.defaultSessionExpireTimeInMs = null; } this.sessionExpireTimeInMs = defaultSessionExpireTimeInMs; this.sessionSendOnlyIfChanged = ninjaProperties.getBooleanWithDefault( NinjaConstant.sessionSendOnlyIfChanged, true); this.sessionTransferredOverHttpsOnly = ninjaProperties .getBooleanWithDefault( NinjaConstant.sessionTransferredOverHttpsOnly, true); this.sessionHttpOnly = ninjaProperties.getBooleanWithDefault( NinjaConstant.sessionHttpOnly, true); this.applicationCookieDomain = ninjaProperties .get(NinjaConstant.applicationCookieDomain); String applicationCookiePrefix = ninjaProperties .getOrDie(NinjaConstant.applicationCookiePrefix); this.sessionCookieName = applicationCookiePrefix + ninja.utils.NinjaConstant.SESSION_SUFFIX; }
@Inject public TemplateEngineJsonP(ObjectMapper objectMapper, NinjaProperties properties) { this.objectMapper = objectMapper; this.callbackParameterName = properties.getWithDefault( NinjaConstant.NINJA_JSONP_CALLBACK_PARAMETER, DEFAULT_CALLBACK_PARAMETER_NAME); }
/** * Whether diagnostics are enabled. If enabled then the default system/views * will be skipped and a detailed diagnostic error result will be returned * by the various methods in this class. You get precise feedback where * an error occurred including original source code. * * @return True if diagnostics are enabled otherwise false. */ public boolean isDiagnosticsEnabled() { // extra safety: only disable detailed diagnostic error pages // if both in DEV mode and diagnostics are enabled 0 return ninjaProperties.isDev() && ninjaProperties.getBooleanWithDefault(NinjaConstant.DIAGNOSTICS_KEY_NAME, Boolean.TRUE); }
@Start(order = 90) public void start() { if (ninjaProperties.getBooleanWithDefault("metrics.influxdb.enabled", false)) { .getOrDie("metrics.influxdb.address"); final int port = ninjaProperties.getIntegerWithDefault( "metrics.influxdb.port", 8086); final String database = ninjaProperties .getOrDie("metrics.influxdb.database"); final String username = ninjaProperties .getOrDie("metrics.influxdb.username"); final String password = ninjaProperties .getOrDie("metrics.influxdb.password"); final String period = ninjaProperties.getWithDefault( "metrics.influxdb.period", "60s"); final int delay = TimeUtil.parseDuration(period);
@Start(order = 90) public void startService() { if (ninjaProperties.getBooleanWithDefault("metrics.librato.enabled", false)) { final String hostname = metricsService.getHostname(); final String username = ninjaProperties .getOrDie("metrics.librato.username"); final String apiKey = ninjaProperties .getOrDie("metrics.librato.apikey"); final String period = ninjaProperties.getWithDefault( "metrics.librato.period", "60s"); final int delay = TimeUtil.parseDuration(period); LibratoReporter.enable(LibratoReporter.builder( metricsService.getMetricRegistry(), username, apiKey, hostname), delay, TimeUnit.SECONDS); log.info( "Started Librato Metrics reporter for '{}', updating every {}", hostname, period); } }
@Override public void migrate() { // Get the connection credentials from application.conf String connectionUrl = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_URL); String connectionUsername = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_USERNAME); String connectionPassword = ninjaProperties.getOrDie(NinjaConstant.DB_CONNECTION_PASSWORD); // We migrate automatically => if you do not want that (eg in production) // set ninja.migration.run=false in application.conf Flyway flyway = new Flyway(); flyway.setDataSource(connectionUrl, connectionUsername, connectionPassword); // In testmode we are cleaning the database so that subsequent testcases // get a fresh database. if (ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_MIGRATION_DROP_SCHEMA, ninjaProperties.isTest() ? true : false )) { flyway.clean(); } flyway.migrate(); }
public void addEtag(Context context, Result result, Long lastModified) { if (!ninjaProperties.isProd()) { result.addHeader(HttpHeaderConstants.CACHE_CONTROL, "no-cache"); } else { String maxAge = ninjaProperties.getWithDefault(HTTP_CACHE_CONTROL, HTTP_CACHE_CONTROL_DEFAULT); boolean useEtag = ninjaProperties.getBooleanWithDefault(HTTP_USE_ETAG, HTTP_USE_ETAG_DEFAULT);
@Inject public CookieEncryption(NinjaProperties properties) { Optional<SecretKeySpec> secretKeySpec = Optional.empty(); if (properties.getBooleanWithDefault(NinjaConstant.applicationCookieEncrypted, false)) { String secret = properties.getOrDie(NinjaConstant.applicationSecret); try { int maxKeyLengthBits = Cipher.getMaxAllowedKeyLength(ALGORITHM); if (maxKeyLengthBits == Integer.MAX_VALUE) { maxKeyLengthBits = 256; } secretKeySpec = Optional.of( new SecretKeySpec(secret.getBytes(), 0, maxKeyLengthBits / Byte.SIZE, ALGORITHM)); logger.info("Ninja session encryption is using {} / {} bit.", secretKeySpec.get().getAlgorithm(), maxKeyLengthBits); } catch (Exception exception) { logger.error("Can not create class to encrypt cookie.", exception); throw new RuntimeException(exception); } } this.secretKeySpec = secretKeySpec; }
public void start() { String applicationName = ninjaProps.getWithDefault( NinjaConstant.applicationName, "Ninja"); if (ninjaProps.getBooleanWithDefault("metrics.jvm.enabled", false)) { if (ninjaProps.getBooleanWithDefault("metrics.logback.enabled", false)) { if (ninjaProps.getBooleanWithDefault("metrics.mbeans.enabled", true)) {
@Inject public NinjaBaseDirectoryResolver(NinjaProperties ninjaProperties) { // custom base package for application modules (e.g. com.example.conf.Routes) this.applicationModulesBasePackage = Optional.ofNullable(ninjaProperties.get( NinjaConstant.APPLICATION_MODULES_BASE_PACKAGE)); }
@Inject public FlashScopeImpl(NinjaProperties ninjaProperties) { this.applicationCookiePrefix = ninjaProperties .getOrDie(NinjaConstant.applicationCookiePrefix); }
private static boolean determineWhetherToUseStrictArgumentExtractorMode(NinjaProperties ninjaProperties) { boolean useStrictArgumentExtractors = ninjaProperties.getBooleanWithDefault(NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS, false); if (useStrictArgumentExtractors == false && nonStrictModeWarningLoggedAlready == false) { String message = "Using deprecated non-strict mode for injection of parameters into controller " + "(" + NinjaConstant.NINJA_STRICT_ARGUMENT_EXTRACTORS + " = false). " + "This mode will soon be removed from Ninja. Make sure you upgrade your application as soon as possible. " + "More: http://www.ninjaframework.org/documentation/basic_concepts/controllers.html 'A note about null and Optional'."; logger.warn(message); nonStrictModeWarningLoggedAlready = true; } return useStrictArgumentExtractors; }
this.templateEngineFreemarkerAssetsAtMethod = templateEngineFreemarkerAssetsAtMethod; this.templateEngineFreemarkerWebJarsAtMethod = templateEngineFreemarkerWebJarsAtMethod; this.fileSuffix = ninjaProperties.getWithDefault(FREEMARKER_CONFIGURATION_FILE_SUFFIX, FILE_SUFFIX); + "java"; if (ninjaProperties.isDev() && new File(srcDir).exists()) {
private void initMimetypes() { // Load default mimetypes from the framework try (InputStream is = this.getClass().getClassLoader().getResourceAsStream(DEFAULT_MIMET_TYPE_LOCATIONS);) { mimetypes.load(is); } catch (Exception e) { logger.error("Failed to load mimetypes", e); } // Load custom mimetypes from the application configuration Enumeration confenum = ninjaProperties.getAllCurrentNinjaProperties() .propertyNames(); while (confenum.hasMoreElements()) { String key = (String) confenum.nextElement(); if (key.startsWith(PROPERTY_MIMETYPE_PREFIX)) { String type = key.substring(key.indexOf('.') + 1).toLowerCase(); String value = (String) ninjaProperties.get(key); mimetypes.setProperty(type, value); } } }
/** * 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) { 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; }
@Inject public PostofficeProvider(Injector injector, NinjaProperties ninjaProperties) { this.factory = new ImplFromPropertiesFactory<>( injector, ninjaProperties, PostofficeConstant.postofficeImplementation, Postoffice.class, (ninjaProperties.isProd() ? "ninja.postoffice.commonsmail.PostofficeCommonsmailImpl" : PostofficeMockImpl.class.getCanonicalName()), true, logger); // lazy singleton this.supplier = Suppliers.memoize(new Supplier<Postoffice>() { @Override public Postoffice get() { return factory.create(); } }); }
@Override public FileItemIterator getFileItemIterator() { long maxFileSize = ninjaProperties.getIntegerWithDefault(NinjaConstant.UPLOADS_MAX_FILE_SIZE, -1); long maxTotalSize = ninjaProperties.getIntegerWithDefault(NinjaConstant.UPLOADS_MAX_TOTAL_SIZE, -1); ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(maxFileSize); upload.setSizeMax(maxTotalSize); FileItemIterator fileItemIterator = null; try { fileItemIterator = upload.getItemIterator(httpServletRequest); } catch (FileUploadException | IOException e) { logger.error("Error while trying to process mulitpart file upload", e); } return fileItemIterator; }
if (ninjaProperties.isTest()) {