SlideShare una empresa de Scribd logo
1 de 52
Descargar para leer sin conexión
OWNER
Java™ properties reinvented.
Get rid of the boilerplate code in properties based configuration.
!
http://owner.aeonbits.org

Luigi R. Viggiano
luigi.viggiano@gmail.com
About this presentation

WARNING:
Viewer discretion is advised

This presentation contains source code. 

Non technical people may experience confusional states, dizziness, sleepiness and fainting.
The author is not good in putting colors together.
In a nutshell
•

OWNER's goal is to minimize the code required for
properties based configuration in Java applications.

•

An open source (BSD License) Java library.

•

Artifacts are available on Maven Central Repository

•

Source code is managed on GitHub (24 forks and 111 stars).

•

Inspired on how GWT i18n manages translations on client
side.

•

Requires Java 5 or newer.

•

No dependencies on 3rd party libraries.
Why?

Programmers are left to do many tasks on their own
when using java.util.Properties
It requires a lot of code. Repetitive code.
What?
What are the very basic things needed to handle properties
files?
•

load the file (from the filesystem? from the classpath?)

•

define a configuration object that exposes its settings via
convenient business methods.

•

do the conversion (boolean, int, URLs, Files, Objects…).

•

define default values when not specified in the file.

•

etc…
How?
How OWNER do its stuff without being repetitive?
1. Imagine you have a Properties file ‘ServerConfig.properties’ in a given java
package:

!
!
2. Define a class named the same way ‘ServerConfig.java’:

!
!
!
How?
How OWNER do its stuff without being repetitive?
3. Use it!
!
!

Since the properties file does have the same name as the Java class, and
they are located in the same package, OWNER will be able to associate
them.
The properties names defined in the properties file will be associated to
the methods in the Java class having the same name.
Principles
“Simple things should be simple, 

complex things should be possible.”
-- Alan Kay (Computer Scientist)

•

Things should be as much simple as they can be. 

New/advanced features should not complicate the
basic usages.

•

Convention over configuration. 

Require as less code as possible.

•

Use of annotations to customize the default behavior.
Goals
•

Be fully documented.

See: http://owner.aeonbits.org/

•

Be stable. OWNER is fully tested, development follows TDD
approach. Test coverage is currently 97%

See: https://coveralls.io/r/lviggiano/owner

•

Be feature rich.

See: http://owner.aeonbits.org/docs/features/

•

Don’t narrow the possibilities to the end user. The user should
be able to do with OWNER everything that he is already doing
with java.util.Properties. And more, of course.
Features Overview
•

Powerful Type Conversion; supports collections, primitives,
common Java objects and user defined objects.

•

Loading properties from multiple resources.

•

Two different “Loading Strategies”: load the FIRST
resource, MERGE all the available resources.

•

Importing (wrap) existing properties objects, as well as
system properties and environment variables.

•

Variables Expansion via the ${variable}notation.
Features Overview
•

Hot Reload and programmable reload.

•

Event notification. On reload, and on property change. With
some basic validation mechanism.

•

“Accessible” and “Mutable” interface to add capabilities to
access or change a Config object.

•

Debugging facilities.

•

Multiple formats: XML and Properties files support; user can
implement and configure custom loader for more file formats.
@DefaultValue and @Key
@Key and @DefaultValue example
Type Conversion
The return type on the Configuration interface determines
how to convert the property value (String) to user’s specified
type. OWNER support primitive types, enumerations …
Type Conversion
As well as common Java types or User’s specified business
objects…
Type Conversion
Collections and arrays (of all the supported types)…
Type Conversion
User defined collections and concrete collections from the
JRE…
Type Conversion
You can define a @TokenizerClass when @Separator is
not enough
Type Conversion
And as last resort, you can define a @ConverterClass
Type Conversion
To recap, all the types supported by OWNER for conversion:
1. Primitive types: boolean, byte, short, integer, long,
float, double.
2. Enums (notice that the conversion is case sensitive, so FOO !=
foo or Foo).
3. java.lang.String, of course (no conversion is needed).
4. java.net.URL, java.net.URI.
5. java.io.File (the character ~ will be expanded to user.home
System Property).
6. java.lang.Class (this can be useful, for instance, if you want
to load the jdbc driver, or similar cases).
Type Conversion
7. Any instantiable class declaring a public constructor with a single
argument of type java.lang.String.
8. Any instantiable class declaring a public constructor with a single
argument of type java.lang.Object.
9. Any class declaring a public static method
valueOf(java.lang.String) that returns an instance of itself.
10. Any class for which you can register a PropertyEditor via
PropertyEditorManager.registerEditor(). (See PropertyEditorTest
as an example).
11. Any array having above types as elements.
12. Any object that can be instantiated via @ConverterClass annotation
explained before.
13. Any Java Collections of all above types: Set, List, SortedSet or
concrete implementations like LinkedHashSet or user defined
collections having a default no-arg constructor. Map and sub-interfaces
are not supported (yet).
Loading Strategies
Common utilities (especially in unix) allow multiple
configuration files.
Tipically a System Level configuration located in
/etc/myapp.conf
and a User Level configuration located in
~/.myapp.conf
an example is the git scm command line tool.
Loading Strategies
A User Level configuration may totally override the
configuration at System Level, or may just redefine some
options. Example:

Repository Level Configuration overrides user level configuration
Loading Strategies
OWNER allows configuration overriding in 2 different way. 

The “Load FIRST” approach (LoadType.FIRST):

Only the first available resource is loaded. Others are ignored.
Loading Strategies
OWNER allows configuration overriding in 2 different way. 

The “Load MERGE” approach (LoadType.MERGE):

The actual configuration is the result of the merge between
all the specified resources. Topmost configuration
resources redefine properties in lowest resources.
Loading Strategies
@Sources annotation supports variable expansion:
•

file:${user.home}/.myapp.config (system property)

•

file:${HOME}/.myapp.config (environment variable)

•

file:~/.myapp.config (the ‘~’ literal accepted by bash)

Above examples are equivalent.
Loading Strategies
@Sources annotation can also expand variables
specified programmatically:
Loading Strategies
@Sources annotation can also expand variables
specified programmatically:

The ConfigFactory can accept configuration
properties itself. I call this “Metaconfiguring”
Importing (or “wrapping”)
existing Properties objects
Existing Properties objects can be “wrapped” or
imported.
Importing Properties
You can specify multiple properties to import on the
same line:
!

If there are prop1 and prop2 defining two different values
for the same property key, the one specified first will
prevail.
Importing Properties
This comes handy even for System properties or
Environment Variables:
Variable Expansion
Sometimes it may be useful to expand properties values
from other properties.

The property story() will expand to:

“The quick brown fox jumped over the lazy dog”
Variable Expansion
This will also work with just the annotations:
Reload and Hot Reload
Reloading configuration resources programmatically:
Reload and Hot Reload
Automatic “Hot Reload”

Hot Reload works fine with following URLs:
• file:path/to/your.properties filesystem backed URL
• jar:file:path/to/some.jar!/path/to/your.properties
a jar file in your local filesystem that contains a properties files.
• classpath:path/to/your.properties a resource loaded
from the classpath, if the classpath resource is stored on
filesystem (from inside a jar or from inside a classpath folder).
Reload and Hot Reload
The “Hot Reload” annotation definition:
Reload and Hot Reload
“Hot Reload” can be synchronous (HotReloadType.SYNC)…
Reload and Hot Reload
…or asynchronous (HotReloadType.ASYNC)…
Reload and Hot Reload
Intercepting reload events:
Interfaces Tree

•
•
•
•

Config (is a marker interface).
Reloadable defines methods to programmatically realod the
configuration and to attach ReloadListeners
Accessible define methods to access internal properties values,
and to save/dump to OutputStream or Writer
Mutable defines methods to change properties values
programmatically and attach PropertyChangeListeners
Listening for reloads
Listening for property
changes
Debugging Facilities
Config objects define a convenient toString()
method:
Debugging Facilities
In your mapping interfaces you can optionally define one of
the following methods that may be convenient for
debugging:
XML Support
The java.util.Properties class supports an XML
format that looks like this:

…a fantastic* facility compared to the plain textual format of
properties files, uh?
The * means “I’m ironic”
XML Support
OWNER supports the previous XML format for properties
as well as any XML that can be possible mapped to a
properties list. Example:

The developer is free to use tags and attributes to define
properties names. Better now?
XML Support
Q: How to load the XML into the

Config object?
A: Simple: in the same way as you already do for properties file.
1. Suppose you have a mapping interface class in a source file
called foo.bar.ServerConfig.java, just place a resource in
your classpath in foo.bar.ServerConfig.xml.
2. Or you can specify the @Sources annotation with an URL
pointing to an file.xml. OWNER will notice the .xml extension
and will load the configuration source as XML.
User defined file formats
If you want to support your own file format, you can
register your loader in the ConfigFactory. Example:
ConfigFactory.registerLoader(new YamlLoader());

XML and Properties file format are in fact internally
implemented in this way. More file formats support are
planned for future releases.
Parameter Formatting
This comes directly from the GWT i18n:

Not really related to configuration. Maybe I should drop
this feature in favor of something better? The parameter
could have been used for different purpose (i.e. a type
safe setter method)
Disabling unwanted features
Variables expansion and parameters formatting can be
inconvenient if you have your own mechanisms. If for
any reason you want to disable it, on class level or
method level, you can use @DisableFeature annotation.
Conclusion

•

Lots of features.

•

Little to code.

•

If you are using properties files, you may give it a try.
Future
•
•
•
•
•
•
•

Validation (JSR 349? Bean Validation?)
Encryptable Properties (i.e. for keeping passwords)
Variable Expansion in @Key annotation. Example:
@Key("servers.${env}.name")
More file formats: INI, JSON, YAML, HOCON, plist,
applet params, servlet params, jndi, jdbc…
JMX bean for Config objects.
Singleton mechanism.
Any other idea? Join and help!
Thank you!

Más contenido relacionado

La actualidad más candente

Deep drive into rust programming language
Deep drive into rust programming languageDeep drive into rust programming language
Deep drive into rust programming languageVigneshwer Dhinakaran
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseChristian Melchior
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingC4Media
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 
Introduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsIntroduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsyann_s
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewMarkus Schneider
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldYura Nosenko
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8José Paumard
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 
Ruby Presentation
Ruby Presentation Ruby Presentation
Ruby Presentation platico_dev
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ applicationAdd an interactive command line to your C++ application
Add an interactive command line to your C++ applicationDaniele Pallastrelli
 

La actualidad más candente (20)

Deep drive into rust programming language
Deep drive into rust programming languageDeep drive into rust programming language
Deep drive into rust programming language
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
Why rust?
Why rust?Why rust?
Why rust?
 
Rust programming-language
Rust programming-languageRust programming-language
Rust programming-language
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Void pointer in c
Void pointer in cVoid pointer in c
Void pointer in c
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Introduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractionsIntroduction to rust: a low-level language with high-level abstractions
Introduction to rust: a low-level language with high-level abstractions
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
Testing Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 worldTesting Spring Boot application in post-JUnit 4 world
Testing Spring Boot application in post-JUnit 4 world
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Ruby Presentation
Ruby Presentation Ruby Presentation
Ruby Presentation
 
Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ applicationAdd an interactive command line to your C++ application
Add an interactive command line to your C++ application
 

Destacado

Configure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaConfigure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaAnatole Tresch
 
다국어 UI 스트링의 효과적인 관리방안
다국어 UI 스트링의 효과적인 관리방안다국어 UI 스트링의 효과적인 관리방안
다국어 UI 스트링의 효과적인 관리방안Seonbae Kim
 
Xe 오픈소스 읽어보기 part 3
Xe  오픈소스 읽어보기 part 3Xe  오픈소스 읽어보기 part 3
Xe 오픈소스 읽어보기 part 3재린 김
 
MySQL协议分析
MySQL协议分析MySQL协议分析
MySQL协议分析ruoyi ruan
 
Hexagonal Architecture using Grails
Hexagonal Architecture using GrailsHexagonal Architecture using Grails
Hexagonal Architecture using GrailsDavid Dawson
 
Процессы разработки в Яндексе
Процессы разработки в ЯндексеПроцессы разработки в Яндексе
Процессы разработки в ЯндексеAndrey Kazarinov
 
Детская обувь Allure
Детская обувь AllureДетская обувь Allure
Детская обувь AllureAllure-Ukraine
 
Selenium Grid: Culinary tips #optconf.ru
Selenium Grid: Culinary tips #optconf.ruSelenium Grid: Culinary tips #optconf.ru
Selenium Grid: Culinary tips #optconf.ruAlexander Khaerov
 
Micro services – surgical team in test automation with SeleniumSelenium micro...
Micro services – surgical team in test automation with SeleniumSelenium micro...Micro services – surgical team in test automation with SeleniumSelenium micro...
Micro services – surgical team in test automation with SeleniumSelenium micro...egorzzamaraev
 
CodeFest 2014. Макаров Н. — Selenium Grid. OK Version
CodeFest 2014. Макаров Н. — Selenium Grid. OK VersionCodeFest 2014. Макаров Н. — Selenium Grid. OK Version
CodeFest 2014. Макаров Н. — Selenium Grid. OK VersionCodeFest
 
COMAQA.BY Conf #2: “Настройка Allure при использовании TestNG-Retry, Антон Ем...
COMAQA.BY Conf #2: “Настройка Allure при использовании TestNG-Retry, Антон Ем...COMAQA.BY Conf #2: “Настройка Allure при использовании TestNG-Retry, Антон Ем...
COMAQA.BY Conf #2: “Настройка Allure при использовании TestNG-Retry, Антон Ем...COMAQA.BY
 
Docker + Selenium Webdriver в рамках Continuous Integration
Docker + Selenium Webdriver в рамках Continuous IntegrationDocker + Selenium Webdriver в рамках Continuous Integration
Docker + Selenium Webdriver в рамках Continuous IntegrationCOMAQA.BY
 
Automated Deployment with Capistrano
Automated Deployment with CapistranoAutomated Deployment with Capistrano
Automated Deployment with CapistranoSumit Chhetri
 
Multi-provider Vagrant and Chef: AWS, VMware, and more
Multi-provider Vagrant and Chef: AWS, VMware, and moreMulti-provider Vagrant and Chef: AWS, VMware, and more
Multi-provider Vagrant and Chef: AWS, VMware, and moreChef Software, Inc.
 
It Works On My Machine: Vagrant for Software Development
It Works On My Machine: Vagrant for Software DevelopmentIt Works On My Machine: Vagrant for Software Development
It Works On My Machine: Vagrant for Software DevelopmentCarlos Perez
 
Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)Michele Orselli
 
Europycon2011: Implementing distributed application using ZeroMQ
Europycon2011: Implementing distributed application using ZeroMQEuropycon2011: Implementing distributed application using ZeroMQ
Europycon2011: Implementing distributed application using ZeroMQfcrippa
 

Destacado (20)

Configure Your Projects with Apache Tamaya
Configure Your Projects with Apache TamayaConfigure Your Projects with Apache Tamaya
Configure Your Projects with Apache Tamaya
 
다국어 UI 스트링의 효과적인 관리방안
다국어 UI 스트링의 효과적인 관리방안다국어 UI 스트링의 효과적인 관리방안
다국어 UI 스트링의 효과적인 관리방안
 
Xe 오픈소스 읽어보기 part 3
Xe  오픈소스 읽어보기 part 3Xe  오픈소스 읽어보기 part 3
Xe 오픈소스 읽어보기 part 3
 
MySQL协议分析
MySQL协议分析MySQL协议分析
MySQL协议分析
 
Hexagonal Architecture using Grails
Hexagonal Architecture using GrailsHexagonal Architecture using Grails
Hexagonal Architecture using Grails
 
Процессы разработки в Яндексе
Процессы разработки в ЯндексеПроцессы разработки в Яндексе
Процессы разработки в Яндексе
 
Детская обувь Allure
Детская обувь AllureДетская обувь Allure
Детская обувь Allure
 
Selenium Grid: Culinary tips #optconf.ru
Selenium Grid: Culinary tips #optconf.ruSelenium Grid: Culinary tips #optconf.ru
Selenium Grid: Culinary tips #optconf.ru
 
Micro services – surgical team in test automation with SeleniumSelenium micro...
Micro services – surgical team in test automation with SeleniumSelenium micro...Micro services – surgical team in test automation with SeleniumSelenium micro...
Micro services – surgical team in test automation with SeleniumSelenium micro...
 
Consul and Consul Pusher
Consul and Consul PusherConsul and Consul Pusher
Consul and Consul Pusher
 
CodeFest 2014. Макаров Н. — Selenium Grid. OK Version
CodeFest 2014. Макаров Н. — Selenium Grid. OK VersionCodeFest 2014. Макаров Н. — Selenium Grid. OK Version
CodeFest 2014. Макаров Н. — Selenium Grid. OK Version
 
COMAQA.BY Conf #2: “Настройка Allure при использовании TestNG-Retry, Антон Ем...
COMAQA.BY Conf #2: “Настройка Allure при использовании TestNG-Retry, Антон Ем...COMAQA.BY Conf #2: “Настройка Allure при использовании TestNG-Retry, Антон Ем...
COMAQA.BY Conf #2: “Настройка Allure при использовании TestNG-Retry, Антон Ем...
 
Docker + Selenium Webdriver в рамках Continuous Integration
Docker + Selenium Webdriver в рамках Continuous IntegrationDocker + Selenium Webdriver в рамках Continuous Integration
Docker + Selenium Webdriver в рамках Continuous Integration
 
Automated Deployment with Capistrano
Automated Deployment with CapistranoAutomated Deployment with Capistrano
Automated Deployment with Capistrano
 
Multi-provider Vagrant and Chef: AWS, VMware, and more
Multi-provider Vagrant and Chef: AWS, VMware, and moreMulti-provider Vagrant and Chef: AWS, VMware, and more
Multi-provider Vagrant and Chef: AWS, VMware, and more
 
It Works On My Machine: Vagrant for Software Development
It Works On My Machine: Vagrant for Software DevelopmentIt Works On My Machine: Vagrant for Software Development
It Works On My Machine: Vagrant for Software Development
 
Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)
 
Vagrant For DevOps
Vagrant For DevOpsVagrant For DevOps
Vagrant For DevOps
 
Vagrant to-aws-flow
Vagrant to-aws-flowVagrant to-aws-flow
Vagrant to-aws-flow
 
Europycon2011: Implementing distributed application using ZeroMQ
Europycon2011: Implementing distributed application using ZeroMQEuropycon2011: Implementing distributed application using ZeroMQ
Europycon2011: Implementing distributed application using ZeroMQ
 

Similar a Owner - Java properties reinvented.

Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC DeploymentsSujit Kumar
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragonAyushman Jain
 
Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Ryan Cuprak
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.netJanbask ItTraining
 
Writing Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of JelloWriting Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of JelloDan Cuellar
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introductionjyoti_lakhani
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC frameworkMohit Gupta
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersKrishnaov
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCFAKHRUN NISHA
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)Shaharyar khan
 

Similar a Owner - Java properties reinvented. (20)

Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Java Basics
Java BasicsJava Basics
Java Basics
 
CS8392 OOP
CS8392 OOPCS8392 OOP
CS8392 OOP
 
oop unit1.pptx
oop unit1.pptxoop unit1.pptx
oop unit1.pptx
 
SFDC Deployments
SFDC DeploymentsSFDC Deployments
SFDC Deployments
 
Java basic
Java basicJava basic
Java basic
 
How to train the jdt dragon
How to train the jdt dragonHow to train the jdt dragon
How to train the jdt dragon
 
Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)
 
Hibernate 1x2
Hibernate 1x2Hibernate 1x2
Hibernate 1x2
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.net
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
 
Writing Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of JelloWriting Well Abstracted Automation on Foundations of Jello
Writing Well Abstracted Automation on Foundations of Jello
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 

Último

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 

Último (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 

Owner - Java properties reinvented.

  • 1. OWNER Java™ properties reinvented. Get rid of the boilerplate code in properties based configuration. ! http://owner.aeonbits.org Luigi R. Viggiano luigi.viggiano@gmail.com
  • 2. About this presentation WARNING: Viewer discretion is advised This presentation contains source code. 
 Non technical people may experience confusional states, dizziness, sleepiness and fainting. The author is not good in putting colors together.
  • 3. In a nutshell • OWNER's goal is to minimize the code required for properties based configuration in Java applications. • An open source (BSD License) Java library. • Artifacts are available on Maven Central Repository • Source code is managed on GitHub (24 forks and 111 stars). • Inspired on how GWT i18n manages translations on client side. • Requires Java 5 or newer. • No dependencies on 3rd party libraries.
  • 4. Why? Programmers are left to do many tasks on their own when using java.util.Properties It requires a lot of code. Repetitive code.
  • 5. What? What are the very basic things needed to handle properties files? • load the file (from the filesystem? from the classpath?) • define a configuration object that exposes its settings via convenient business methods. • do the conversion (boolean, int, URLs, Files, Objects…). • define default values when not specified in the file. • etc…
  • 6. How? How OWNER do its stuff without being repetitive? 1. Imagine you have a Properties file ‘ServerConfig.properties’ in a given java package: ! ! 2. Define a class named the same way ‘ServerConfig.java’: ! ! !
  • 7. How? How OWNER do its stuff without being repetitive? 3. Use it! ! ! Since the properties file does have the same name as the Java class, and they are located in the same package, OWNER will be able to associate them. The properties names defined in the properties file will be associated to the methods in the Java class having the same name.
  • 8. Principles “Simple things should be simple, 
 complex things should be possible.” -- Alan Kay (Computer Scientist) • Things should be as much simple as they can be. 
 New/advanced features should not complicate the basic usages. • Convention over configuration. 
 Require as less code as possible. • Use of annotations to customize the default behavior.
  • 9. Goals • Be fully documented.
 See: http://owner.aeonbits.org/ • Be stable. OWNER is fully tested, development follows TDD approach. Test coverage is currently 97%
 See: https://coveralls.io/r/lviggiano/owner • Be feature rich.
 See: http://owner.aeonbits.org/docs/features/ • Don’t narrow the possibilities to the end user. The user should be able to do with OWNER everything that he is already doing with java.util.Properties. And more, of course.
  • 10. Features Overview • Powerful Type Conversion; supports collections, primitives, common Java objects and user defined objects. • Loading properties from multiple resources. • Two different “Loading Strategies”: load the FIRST resource, MERGE all the available resources. • Importing (wrap) existing properties objects, as well as system properties and environment variables. • Variables Expansion via the ${variable}notation.
  • 11. Features Overview • Hot Reload and programmable reload. • Event notification. On reload, and on property change. With some basic validation mechanism. • “Accessible” and “Mutable” interface to add capabilities to access or change a Config object. • Debugging facilities. • Multiple formats: XML and Properties files support; user can implement and configure custom loader for more file formats.
  • 12. @DefaultValue and @Key @Key and @DefaultValue example
  • 13. Type Conversion The return type on the Configuration interface determines how to convert the property value (String) to user’s specified type. OWNER support primitive types, enumerations …
  • 14. Type Conversion As well as common Java types or User’s specified business objects…
  • 15. Type Conversion Collections and arrays (of all the supported types)…
  • 16. Type Conversion User defined collections and concrete collections from the JRE…
  • 17. Type Conversion You can define a @TokenizerClass when @Separator is not enough
  • 18. Type Conversion And as last resort, you can define a @ConverterClass
  • 19. Type Conversion To recap, all the types supported by OWNER for conversion: 1. Primitive types: boolean, byte, short, integer, long, float, double. 2. Enums (notice that the conversion is case sensitive, so FOO != foo or Foo). 3. java.lang.String, of course (no conversion is needed). 4. java.net.URL, java.net.URI. 5. java.io.File (the character ~ will be expanded to user.home System Property). 6. java.lang.Class (this can be useful, for instance, if you want to load the jdbc driver, or similar cases).
  • 20. Type Conversion 7. Any instantiable class declaring a public constructor with a single argument of type java.lang.String. 8. Any instantiable class declaring a public constructor with a single argument of type java.lang.Object. 9. Any class declaring a public static method valueOf(java.lang.String) that returns an instance of itself. 10. Any class for which you can register a PropertyEditor via PropertyEditorManager.registerEditor(). (See PropertyEditorTest as an example). 11. Any array having above types as elements. 12. Any object that can be instantiated via @ConverterClass annotation explained before. 13. Any Java Collections of all above types: Set, List, SortedSet or concrete implementations like LinkedHashSet or user defined collections having a default no-arg constructor. Map and sub-interfaces are not supported (yet).
  • 21. Loading Strategies Common utilities (especially in unix) allow multiple configuration files. Tipically a System Level configuration located in /etc/myapp.conf and a User Level configuration located in ~/.myapp.conf an example is the git scm command line tool.
  • 22. Loading Strategies A User Level configuration may totally override the configuration at System Level, or may just redefine some options. Example: Repository Level Configuration overrides user level configuration
  • 23. Loading Strategies OWNER allows configuration overriding in 2 different way. 
 The “Load FIRST” approach (LoadType.FIRST): Only the first available resource is loaded. Others are ignored.
  • 24. Loading Strategies OWNER allows configuration overriding in 2 different way. 
 The “Load MERGE” approach (LoadType.MERGE): The actual configuration is the result of the merge between all the specified resources. Topmost configuration resources redefine properties in lowest resources.
  • 25. Loading Strategies @Sources annotation supports variable expansion: • file:${user.home}/.myapp.config (system property) • file:${HOME}/.myapp.config (environment variable) • file:~/.myapp.config (the ‘~’ literal accepted by bash) Above examples are equivalent.
  • 26. Loading Strategies @Sources annotation can also expand variables specified programmatically:
  • 27. Loading Strategies @Sources annotation can also expand variables specified programmatically: The ConfigFactory can accept configuration properties itself. I call this “Metaconfiguring”
  • 28. Importing (or “wrapping”) existing Properties objects Existing Properties objects can be “wrapped” or imported.
  • 29. Importing Properties You can specify multiple properties to import on the same line: ! If there are prop1 and prop2 defining two different values for the same property key, the one specified first will prevail.
  • 30. Importing Properties This comes handy even for System properties or Environment Variables:
  • 31. Variable Expansion Sometimes it may be useful to expand properties values from other properties. The property story() will expand to:
 “The quick brown fox jumped over the lazy dog”
  • 32. Variable Expansion This will also work with just the annotations:
  • 33. Reload and Hot Reload Reloading configuration resources programmatically:
  • 34. Reload and Hot Reload Automatic “Hot Reload” Hot Reload works fine with following URLs: • file:path/to/your.properties filesystem backed URL • jar:file:path/to/some.jar!/path/to/your.properties a jar file in your local filesystem that contains a properties files. • classpath:path/to/your.properties a resource loaded from the classpath, if the classpath resource is stored on filesystem (from inside a jar or from inside a classpath folder).
  • 35. Reload and Hot Reload The “Hot Reload” annotation definition:
  • 36. Reload and Hot Reload “Hot Reload” can be synchronous (HotReloadType.SYNC)…
  • 37. Reload and Hot Reload …or asynchronous (HotReloadType.ASYNC)…
  • 38. Reload and Hot Reload Intercepting reload events:
  • 39. Interfaces Tree • • • • Config (is a marker interface). Reloadable defines methods to programmatically realod the configuration and to attach ReloadListeners Accessible define methods to access internal properties values, and to save/dump to OutputStream or Writer Mutable defines methods to change properties values programmatically and attach PropertyChangeListeners
  • 42. Debugging Facilities Config objects define a convenient toString() method:
  • 43. Debugging Facilities In your mapping interfaces you can optionally define one of the following methods that may be convenient for debugging:
  • 44. XML Support The java.util.Properties class supports an XML format that looks like this: …a fantastic* facility compared to the plain textual format of properties files, uh? The * means “I’m ironic”
  • 45. XML Support OWNER supports the previous XML format for properties as well as any XML that can be possible mapped to a properties list. Example: The developer is free to use tags and attributes to define properties names. Better now?
  • 46. XML Support Q: How to load the XML into the
 Config object? A: Simple: in the same way as you already do for properties file. 1. Suppose you have a mapping interface class in a source file called foo.bar.ServerConfig.java, just place a resource in your classpath in foo.bar.ServerConfig.xml. 2. Or you can specify the @Sources annotation with an URL pointing to an file.xml. OWNER will notice the .xml extension and will load the configuration source as XML.
  • 47. User defined file formats If you want to support your own file format, you can register your loader in the ConfigFactory. Example: ConfigFactory.registerLoader(new YamlLoader()); XML and Properties file format are in fact internally implemented in this way. More file formats support are planned for future releases.
  • 48. Parameter Formatting This comes directly from the GWT i18n: Not really related to configuration. Maybe I should drop this feature in favor of something better? The parameter could have been used for different purpose (i.e. a type safe setter method)
  • 49. Disabling unwanted features Variables expansion and parameters formatting can be inconvenient if you have your own mechanisms. If for any reason you want to disable it, on class level or method level, you can use @DisableFeature annotation.
  • 50. Conclusion • Lots of features. • Little to code. • If you are using properties files, you may give it a try.
  • 51. Future • • • • • • • Validation (JSR 349? Bean Validation?) Encryptable Properties (i.e. for keeping passwords) Variable Expansion in @Key annotation. Example: @Key("servers.${env}.name") More file formats: INI, JSON, YAML, HOCON, plist, applet params, servlet params, jndi, jdbc… JMX bean for Config objects. Singleton mechanism. Any other idea? Join and help!