Expand my Community achievements bar.

Nomination window for the Adobe Community Advisor Program, Class of 2025, is now open!
SOLVED

Extract environment name i.e. DEV/UAT/STAGING in model class or servlet?

Avatar

Level 4

Hi,

I have to dynamically extract the environment on which the code is currently running?

Any pointers on how to do it?

Regards,

Shalul Rohilla

1 Accepted Solution

Avatar

Correct answer by
Employee

Hi Shalul,

It depends a bit on how you are defining the environment name. If you are using Sling runmodes, then you would use the SlingSettingsService (http://dev.day.com/docs/en/cq/current/javadoc/org/apache/sling/settings/SlingSettingsService.html) to get the current set of runmodes.

However, I'd suggest trying to avoid this. Typically, it is better to write your code against named configuration variables and then have those variables change per envrionment.

For example, let's say that you have a service which needs to send an email, but only in stage and production. One way would be to write:

Set<String> runmodes = slingSettingsService.getRunModes(); if (runmodes.contains(PRODUCTION) || runmodes.contains(STAGE)) { sendEmail(); }

Better would be:

if (shouldSendEmail) { sendEmail(); }

where shouldSendEmail is an OSGi-configured property which defaults to false. To set it in production and stage, you'd create /apps/myapp/config.production/<serviceclass> and /apps/myapp/config.stage/<serviceclass>.

This isn't appropriate 100% of the time, but it is appropriate far more frequently than manually checking for the runmodes.

HTH,

Justin 

View solution in original post

1 Reply

Avatar

Correct answer by
Employee

Hi Shalul,

It depends a bit on how you are defining the environment name. If you are using Sling runmodes, then you would use the SlingSettingsService (http://dev.day.com/docs/en/cq/current/javadoc/org/apache/sling/settings/SlingSettingsService.html) to get the current set of runmodes.

However, I'd suggest trying to avoid this. Typically, it is better to write your code against named configuration variables and then have those variables change per envrionment.

For example, let's say that you have a service which needs to send an email, but only in stage and production. One way would be to write:

Set<String> runmodes = slingSettingsService.getRunModes(); if (runmodes.contains(PRODUCTION) || runmodes.contains(STAGE)) { sendEmail(); }

Better would be:

if (shouldSendEmail) { sendEmail(); }

where shouldSendEmail is an OSGi-configured property which defaults to false. To set it in production and stage, you'd create /apps/myapp/config.production/<serviceclass> and /apps/myapp/config.stage/<serviceclass>.

This isn't appropriate 100% of the time, but it is appropriate far more frequently than manually checking for the runmodes.

HTH,

Justin