My web application has several integrations with external systems and all these integration Rest URLs are kept in a config file with in web app. My application reads this config file at start up and use the URL values while making connections to external systems. But quite often it happens that one of the external systems is down and we have to use an alternate URL. In that case, we typically will have to modify the config and redeploy the war file. Is there a way to modify config file with new value without going through a redeployment of the war file?
In my projects i usually work with Apache Commons Configuration for the management of config files (properties). This library has the capability of automatic reload the values when file changes.
This is muy suggestion of implementation:
Create a class "MyAppConfigProperties" for load the properties file and read your configuration keys:
public class MyAppConfig {
//Apache Commons library object
private PropertiesConfiguration configFile;
private void init() {
try {
//Load the file
configFile = new PropertiesConfiguration(
MyAppConfig.class.getClassLoader().getResource("configFile.properties"));
// Create refresh strategy with "FileChangedReloadingStrategy"
FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy();
fileChangedReloadingStrategy.setRefreshDelay(1000);
configFile.setReloadingStrategy(fileChangedReloadingStrategy);
} catch (ConfigurationException e) {
//Manage the exception
}
}
/**
* Constructor por defecto.
*/
public MyAppConfig() {
super();
init();
}
public String getKey(final String key) {
try {
if (configFile.containsKey(key)) {
return configFile.getString(key);
} else {
return null;
}
} catch (ConversionException e) {
//Manage Exception
}
}
}
Now you have to construct a instance of this class (singleton) and use it in all places in that you need to reed a config key.
Every time you use the method "getKey" you will get the last value of the key without deploy and restart.
Related
Currently, I am sending app crashes logs of Android app via HTTP to my server (acra) and my server saves them in properties like this:
#RestController
public class EndlessBlowReportController {
public int counter;
#Autowired
public static final Properties defaultProperties = new Properties();
#PostMapping("/add_report")
public void addReport(#RequestBody String report) {
try {
JSONObject jsonObject = new JSONObject(report);
defaultProperties.put(counter, report);
counter++;
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
#GetMapping("/get_reports")
public List<String> getReports() {
List<String> reports = new ArrayList<>();
try {
for(int i=0;i<defaultProperties.size();i++) {
reports.add((String)defaultProperties.get(i));
}
} catch (Exception ex) {
}
return reports;
}
}
and it works fine until I deploy a new version of the server.
How can I keep my properties even after deploy?
The properties are only stored in memory and won't be persisted to any permanent storage, such a file or database. My recommendation would be to not store this information in properties, but instead store it in a database, or alternatively in the file storage as a file.
For example, if you went with the file solution, you could load the file during the startup and update the file each time you get new reports. By doing so, you would persist the information and it wouldn't disappear each time you restart your server.
I hope you find this answer helpful.
Good luck!
I am using EJB 3.0 and CDI to develop a java ee application which will be deployed in Websphere application server.
I have a requirement to have a property file from which i read certain configuration parameters and this property file should reside in the filesystem of the host system where my code will be deployed.
The base path ( directory where the property file will be placed ) for the property file is configured as a Name space binding String resource in Websphere application server.
Currently i have coded a Utility class to retrieve and use the property file which looks as below.
#Singleton
public class AppPropertyUtil {
private static Hashtable apppProperties;
#Resource(name="jndi/basePath",lookup="jndi/basePath")
private static String basePath;
private static final Logger LOGGER = LoggerFactory.getLogger(AppPropertyUtil.class);
protected void loadPropertyBundleFromFileSystem(String path)
{
InputStream inputStream = null;
Properties properties = null;
try {String fullPath=basePath+"/"+path+".properties";
LOGGER.info("Property file path : "+fullPath);
inputStream = new FileInputStream(new File(fullPath));
if (inputStream != null) {
properties = new Properties();
properties.load(inputStream);
LOGGER.info("Properties loaded");
apppProperties = (Hashtable)properties;
}
} catch (FileNotFoundException exception) {
LOGGER.error("Cannot read property bundle ",exception);
}
catch (IOException | IllegalArgumentException exception) {
LOGGER.error("Unable to loadproperties ",
exception);
}
}
public String getProperty(String key)
{
if(apppProperties == null)
{
loadPropertyBundleFromFileSystem("AppProps");
}
Object value = apppProperties.get(key);
if(value != null){
return (String) value;
}
return null;
}
}
But having the #Resource annotation will mandate that the AppPropertyUtil class be injected inside any class that wishes to use it. So, I will not be able to use this in any POJO classes which are not managed.
Please help me understand whether this is the best approach to go with for the above requirement or could this be improved. I would also like to make the getProperty method and loadPropertyBundleFromFileSystem method static to have it being used from a static context, but it is not possible as the class should be injected to be used.
Thanks in advance
Ideally, you shouldn't need to access to your class from any POJO. Use design patterns and separate your concerns. Use your class as a service to load up your property file and serve out a Map or Set of it's contents. POJO Models shouldn't care, but your other classes can read that map/set of properties and pass them to your pojo's or other classes which need it but don't have direct access to it.
The other option is to remove the #Resource and make this just a plain old util class that you pass in the filename to read in it's constructor, then when you call getProperty, you do what you do to check to see if it's been loaded already, if not, load it.
Wrap that in a factory that supplies the #Resource parts and it keeps your EE code from bleeding into your other jars (utils).
Is it possible to have my app update the config settings at runtime? I can easily expose the settings I want in my UI but is there a way to allow the user to update settings and make them permanent ie save them to the config.yaml file? The only way I can see it to update the file by hand then restart the server which seems a bit limiting.
Yes. It is possible to reload the service classes at runtime.
Dropwizard by itself does not have the way to reload the app, but jersey has.
Jersey uses a container object internally to maintain the running application. Dropwizard uses the ServletContainer class of Jersey to run the application.
How to reload the app without restarting it -
Get a handle to the container used internally by jersey
You can do this by registering a AbstractContainerLifeCycleListener in Dropwizard Environment before starting the app. and implement its onStartup method as below -
In your main method where you start the app -
//getting the container instance
environment.jersey().register(new AbstractContainerLifecycleListener() {
#Override
public void onStartup(Container container) {
//initializing container - which will be used to reload the app
_container = container;
}
});
Add a method to your app to reload the app. It will take in the list of string which are the names of the service classes you want to reload. This method will call the reload method of the container with the new custom DropWizardConfiguration instance.
In your Application class
public static synchronized void reloadApp(List<String> reloadClasses) {
DropwizardResourceConfig dropwizardResourceConfig = new DropwizardResourceConfig();
for (String className : reloadClasses) {
try {
Class<?> serviceClass = Class.forName(className);
dropwizardResourceConfig.registerClasses(serviceClass);
System.out.printf(" + loaded class %s.\n", className);
} catch (ClassNotFoundException ex) {
System.out.printf(" ! class %s not found.\n", className);
}
}
_container.reload(dropwizardResourceConfig);
}
For more details see the example documentation of jersey - jersey example for reload
Consider going through the code and documentation of following files in Dropwizard/Jersey for a better understanding -
Container.java
ContainerLifeCycleListener.java
ServletContainer.java
AbstractContainerLifeCycleListener.java
DropWizardResourceConfig.java
ResourceConfig.java
No.
Yaml file is parsed at startup and given to the application as Configuration object once and for all. I believe you can change the file after that but it wouldn't affect your application until you restart it.
Possible follow up question: Can one restart the service programmatically?
AFAIK, no. I've researched and read the code somewhat for that but couldn't find a way to do that yet. If there is, I'd love to hear that :).
I made a task that reloads the main yaml file (it would be useful if something in the file changes). However, it is not reloading the environment. After researching this, Dropwizard uses a lot of final variables and it's quite hard to reload these on the go, without restarting the app.
class ReloadYAMLTask extends Task {
private String yamlFileName;
ReloadYAMLTask(String yamlFileName) {
super("reloadYaml");
this.yamlFileName = yamlFileName;
}
#Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
if (yamlFileName != null) {
ConfigurationFactoryFactory configurationFactoryFactory = new DefaultConfigurationFactoryFactory<ReportingServiceConfiguration>();
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
ObjectMapper objectMapper = Jackson.newObjectMapper();
final ConfigurationFactory<ServiceConfiguration> configurationFactory = configurationFactoryFactory.create(ServiceConfiguration.class, validator, objectMapper, "dw");
File confFile = new File(yamlFileName);
configurationFactory.build(new File(confFile.toURI()));
}
}
}
You can change the configuration in the YAML and read it while your application is running. This will not however restart the server or change any server configurations. You will be able to read any changed custom configurations and use them. For example, you can change the logging level at runtime or reload other custom settings.
My solution -
Define a custom server command. You should use this command to start your application instead of the "server" command.
ArgsServerCommand.java
public class ArgsServerCommand<WC extends WebConfiguration> extends EnvironmentCommand<WC> {
private static final Logger LOGGER = LoggerFactory.getLogger(ArgsServerCommand.class);
private final Class<WC> configurationClass;
private Namespace _namespace;
public static String COMMAND_NAME = "args-server";
public ArgsServerCommand(Application<WC> application) {
super(application, "args-server", "Runs the Dropwizard application as an HTTP server specific to my settings");
this.configurationClass = application.getConfigurationClass();
}
/*
* Since we don't subclass ServerCommand, we need a concrete reference to the configuration
* class.
*/
#Override
protected Class<WC> getConfigurationClass() {
return configurationClass;
}
public Namespace getNamespace() {
return _namespace;
}
#Override
protected void run(Environment environment, Namespace namespace, WC configuration) throws Exception {
_namespace = namespace;
final Server server = configuration.getServerFactory().build(environment);
try {
server.addLifeCycleListener(new LifeCycleListener());
cleanupAsynchronously();
server.start();
} catch (Exception e) {
LOGGER.error("Unable to start server, shutting down", e);
server.stop();
cleanup();
throw e;
}
}
private class LifeCycleListener extends AbstractLifeCycle.AbstractLifeCycleListener {
#Override
public void lifeCycleStopped(LifeCycle event) {
cleanup();
}
}
}
Method to reload in your Application -
_ymlFilePath = null; //class variable
public static boolean reloadConfiguration() throws IOException, ConfigurationException {
boolean reloaded = false;
if (_ymlFilePath == null) {
List<Command> commands = _configurationBootstrap.getCommands();
for (Command command : commands) {
String commandName = command.getName();
if (commandName.equals(ArgsServerCommand.COMMAND_NAME)) {
Namespace namespace = ((ArgsServerCommand) command).getNamespace();
if (namespace != null) {
_ymlFilePath = namespace.getString("file");
}
}
}
}
ConfigurationFactoryFactory configurationFactoryFactory = _configurationBootstrap.getConfigurationFactoryFactory();
ValidatorFactory validatorFactory = _configurationBootstrap.getValidatorFactory();
Validator validator = validatorFactory.getValidator();
ObjectMapper objectMapper = _configurationBootstrap.getObjectMapper();
ConfigurationSourceProvider provider = _configurationBootstrap.getConfigurationSourceProvider();
final ConfigurationFactory<CustomWebConfiguration> configurationFactory = configurationFactoryFactory.create(CustomWebConfiguration.class, validator, objectMapper, "dw");
if (_ymlFilePath != null) {
// Refresh logging level.
CustomWebConfiguration webConfiguration = configurationFactory.build(provider, _ymlFilePath);
LoggingFactory loggingFactory = webConfiguration.getLoggingFactory();
loggingFactory.configure(_configurationBootstrap.getMetricRegistry(), _configurationBootstrap.getApplication().getName());
// Get my defined custom settings
CustomSettings customSettings = webConfiguration.getCustomSettings();
reloaded = true;
}
return reloaded;
}
Although this feature isn't supported out of the box by dropwizard, you're able to accomplish this fairly easy with the tools they give you.
Before I get started, note that this isn't a complete solution for the question asked as it doesn't persist the updated config values to the config.yml. However, this would be easy enough to implement yourself simply by writing to the config file from the application. If anyone would like to write this implementation feel free to open a PR on the example project I've linked below.
Code
Start off with a minimal config:
config.yml
myConfigValue: "hello"
And it's corresponding configuration file:
ExampleConfiguration.java
public class ExampleConfiguration extends Configuration {
private String myConfigValue;
public String getMyConfigValue() {
return myConfigValue;
}
public void setMyConfigValue(String value) {
myConfigValue = value;
}
}
Then create a task which updates the config:
UpdateConfigTask.java
public class UpdateConfigTask extends Task {
ExampleConfiguration config;
public UpdateConfigTask(ExampleConfiguration config) {
super("updateconfig");
this.config = config;
}
#Override
public void execute(Map<String, List<String>> parameters, PrintWriter output) {
config.setMyConfigValue("goodbye");
}
}
Also for demonstration purposes, create a resource which allows you to get the config value:
ConfigResource.java
#Path("/config")
public class ConfigResource {
private final ExampleConfiguration config;
public ConfigResource(ExampleConfiguration config) {
this.config = config;
}
#GET
public Response handleGet() {
return Response.ok().entity(config.getMyConfigValue()).build();
}
}
Finally wire everything up in your application:
ExampleApplication.java (exerpt)
environment.jersey().register(new ConfigResource(configuration));
environment.admin().addTask(new UpdateConfigTask(configuration));
Usage
Start up the application then run:
$ curl 'http://localhost:8080/config'
hello
$ curl -X POST 'http://localhost:8081/tasks/updateconfig'
$ curl 'http://localhost:8080/config'
goodbye
How it works
This works simply by passing the same reference to the constructor of ConfigResource.java and UpdateConfigTask.java. If you aren't familiar with the concept see here:
Is Java "pass-by-reference" or "pass-by-value"?
The linked classes above are to a project I've created which demonstrates this as a complete solution. Here's a link to the project:
scottg489/dropwizard-runtime-config-example
Footnote: I haven't verified this works with the built in configuration. However, the dropwizard Configuration class which you need to extend for your own configuration does have various "setters" for internal configuration, but it may not be safe to update those outside of run().
Disclaimer: The project I've linked here was created by me.
I have a rest class which accepts a multipart request, saves a file in a particular location and calls an ejb service to save so hash in our database.
The flow is like below
Rest -> service -> dao
In my service class I am injecting the dao. Due to some reason the dao is not initialized and injected into the service class and I get a null pointer exception.
The file should be deleted in this case because ejbs have transaction management capabilities. But the file is not being deleted.
Do I need to additionally enable transaction management somewhere in the container?
My rest class is not an ejb. Is it because my rest class is not an ejb, that is why the file is not being deleted?
BTW I am using jboss eap 6.1
Can anyone please help?
For simplicity I have written a new code with almost same thing my original code is doing
#Stateless
#Local
#TransactionManagement
public class ImportUpgradeServiceImpl implements ImportUpgradeService {
#Inject
private UpgradePackageDao upgradePackageDao;
#Override
public boolean savePackage() {
File file = new File("d:\\ejbtest.log");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
upgradePackageDao.savePackageHash(null);
return false;
}
}
Below is my DAO
public class UpgradePackageDaoImpl implements UpgradePackageDao {
#Override
public void savePackageHash(String hash) {
throw new RuntimeException("cannot save");
}
}
I ran the ejb with #TransactionManagement and without #TransactionManagement. Both scenarios I can still see "ejbtest.log" file created in my D: drive
I'm quite confused on how to properly setup a logger in an Java EE OSGi environment. Here are my requirements:
Only 1 log file per EBA (grouping of bundles)
Multiple log files per application server (due to multiple EBAs)
Do not want to perform ClassLoader magic (its fine if a library I use does this, I just don't want to have to write it)
Must rotate the log file at the end of the day and only maintain 7 log files at once
Preferably does not require creating a logging bundle per EBA. No other developer will buy in if I tell them to write their own logging interop for each application.
Must work with WebSphere Application Server 8.5.5
First I tried to use SLF4j on top of log4j like our other Java EE applications do, however nothing could find my log4j.properties. I tried variations of importing SLF4j, and also had issues where loading it in 1 bundle prevented it from loading in another.
Next I looked into PAX logger, but it appears to log globally, not per EBA.
Attempting to use the OSGi LogService prevents my bundle from deploying to WebSphere, plus I'm not sure how I could get it to meet my requirements anyway.
I'm at the point where the only option I can see is to write my own bundle that keeps a registry for bundle -> log file (using FrameworkUtil.getBundle on the client class) and implement a full logging framework within it. If that has classloader isolation issues then possibly push to an EJB to do the actual logging. I'm really hoping that's not my only solution.
Can anyone point me to some documentation that will help me out??
Thank you!
People are in general confused about the Log Service ... The Log Service does not store any logs, it just acts as a dispatcher. I understand the confusion since the Log Service is mandated to have a small buffer for the initial start up and provides an API to get the buffer.
For what you want, you should add a Log Listener with the Log Reader services. What you want is quite easy with Declarative Services. This is a component that implements your requirements :
#Component(provide = {}, immediate = true) public class Logger extends Thread
implements LogListener {
final BlockingQueue<LogEntry> queue = new ArrayBlockingQueue<LogEntry>(1000);
File root;
#Reference void setLR(LogReaderService lr) {
lr.addLogListener(this);
}
#Activate void activate(BundleContext context, Map<String,Object> props) {
if ( props.containsKey("root"))
root = new File((String) props.get("root"));
else
root = context.getDataFile("logs");
root.mkdirs();
start();
}
#Deactivate void deactivate() {
interrupt();
}
#Override public void logged(LogEntry entry) {
queue.offer(entry); // ignore full silently
}
public void run() {
while (true)
try {
LogEntry entry = queue.take();
File file = getPath(entry);
if (file.isFile()) {
long days = TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis()
- file.lastModified());
if (days > 2) file.delete();
}
try (OutputStream raf = new FileOutputStream(file, true)) {
String s = String.format("%tT [%03d] %s%n", entry.getTime(), entry
.getBundle().getBundleId(), entry.getMessage());
raf.write(s.getBytes("UTF-8"));
}
} catch (InterruptedException ie) {
return;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private File getPath(LogEntry entry) {
long rollover = TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis()) % 7;
String eba = "eba"; // fill in eba from entry.getBundle()?
return new File(root, "log-" + eba + "-" + rollover + ".msg");
}
}
This could of course be done a bit more efficient, but that is left as an exercise.