CORS – How to allow origin by domain using wildcard operator

Create a filter class for enabling CORS

CORS ( Cross-Origin Resource Sharing ) is a mechanism provided by modern web browser to allow cross-site HTTP requests like XmlHttpRequest (Ex. Ajax).

This article does not cover discussions and articles about the CORS standard, – for which we refer to Wikipedia or MSDN article – instead we’ll show an example in Java on how dinamically enable CORS and send back the information to the client browser.

an XmlHttpRequest request

According the above scenario, our CORS filter must intercept the Origin value contained on the HEAD part of the request sent by the client.

Configure allowed site or domains

On the web application’s properties file, add a dedicated key where insert thrusted domain.

Something like this:

cors.domain.supported = *

Then consider writing a class that implements a javax.servlet.Filter.

public class ApiOriginFilter implements Filter {

	ConfigService config;
	Logger logger;
	static String origins;
	static Pattern pattern;
	public void init(FilterConfig filterConfig) throws ServletException {
		origins = config.getProperty("cors.domain.supported");
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException 
		if (StringUtils.isNotEmpty(origins))
			String[] list = origins.split(",");
			HttpServletRequest httpServletRequest = (HttpServletRequest)request;
			String origin = httpServletRequest.getHeader("Origin");
			logger.debug("origin: {}", origin);
			if (StringUtils.isNotEmpty(origin))
				for (String item : list) {
					String input = item.trim();
					String regex = "^"   input.replace("*", ".*")   "(?::d )$";
					Pattern pattern = Pattern.compile(regex);
					Matcher matcher = pattern.matcher(origin);
					if (matcher.find())
						String output =;
			"origin allowed: {}", output);
						HttpServletResponse httpServletResponse = (HttpServletResponse) response;
						httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
						httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
						httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");
		chain.doFilter(request, response);


	public void destroy() {


Notice that if you are developting with REST API and JAX-RS 2.0, a better choice would be to implement ContainerResponseFilter class instead.

Test on local environment

In order to test ajax call on the same local environment, a simple way is to edit OS host’s file by adding a line:

Then every XHRequest will point to[service_address].

Web Application – Integration test with Arquillian

Integration test with Arquillian

Arqullian is an infrastucture for doing integration tests by creating a reproduction archive of the source web app included of the unit test.

It integrates either with JUnit and TestNG.

This is the mission of Arquillian:

  • managing the lifecycle of the container (start/stop),
  • bundling the test class with dependent classes and resources into a deployable archive,
  • enhancing the test class (e.g., resolving @Inject, @EJB and @Resource injections),
  • deploying the archive to test (deploy/undeploy) and
  • capturing results and failures.

Basically, once the developer create the test archive using ShrinkWrap class, Arquillian automatically deal with it by deploying the package, run the test and optionally starting / stopping the container.

Arquillian basic example

You can download the Arquillian Example code HERE

Looking at documentation or maven archetypes, you’ll see examples like the following:

This code is maybe good for showing Arquillian usage, but not for real world, where your web app could be multi-module composed with a many, many dependencies.

Arquillian real world example

In this chapter we’ll create a Rest Integration Test archive that contains ALL the module dependencies automatically imported by the Maven resolver.

First off, create an empty ear archive using maven archetype; for this purpose we’ll create a compliant jboss 6.4 ear module.

Then you can create a simple EJB that return “hello” word.

Now open the web module, edit pom.xml and add these dependencies:

So have added:

  • shrinkwrap artifact and arquillian modules;
  • a logging library
  • resteasy library (compliant with JBoss spec)

We can now include a class JaxRsActivator that extends jax rs Application for initialiting our rest methods.

And our rest implementation entity

Despite is not – obviously – a real world example what we really need to know if how to create an ear test module without the need of importing all classes and dependencies manually

Under maven test package, create a class named with the following lines:

Since ShrinkWrap doesn’t support EJB archive actually  (at least with 2.0.0 version) what we need is:

  1. Create an EAR archive
  2. Import EJB dependencies with Maven resolver
  3. Create an EJB package and add all needed classes (even resolving these by package)
  4. Add imported EJB dependencies as resources within the EJB archive
  5. Create war (don’t forget to create beans.xml both in war end ejb archive in order to make injection work)

We have also created a test-application.xml file, which is needed to conformly create our ear archive

For the test part, @RunAsClient annotation is used because we want these test to run OUTSIDE the container.

Notice also that @ArquillianResource is useful because automatically resolve our deployed ear test URL (which may be even a remote URL by properly configure the arquillian.xml file).

Arquillian configuration

The following is an example of arquillian.xml properly configured for running a test on a local or remote container, even with managed option

If you are willing to create the archive for the first time, it’s also very important to see the built package for verifying the result, so setting deploymentExportPath will produce the output in the selected path.

Run the Arquillian integration test

If you created the project using a maven archetype like written on the first part of this article, you’ll notice that pom.xml has already some arquillian profiles created.

If you already started your local JBoss environment, simply launch this command:

If you need to test your web application in a AS remote address, type the following:

Download example

You can download the Arquillian Example code HERE


JBoss EAP 6.4.0 – Configure web application security from zero

JBOSS 6 – Configure web application security

In this example we’ll show how to manage web application security using the ManagementRealm of Jboss 6.x and filtering roles directly on a rest service by using javax annotations.
Even more, since we are using BASIC authentication, our site will make exclusive use of SSL protocol in order to avoid easy sniffing of credentials through ordinary HTTP.

The final result, once the user enter the rest service address, is to let authenticate the user to check if is role is allowed, otherwise the server will refuse him to access.


For the code, click on the link below:

Download code

1. Configure JBOSS

First off, JBoss 6.x requires user to be added in order to access the administration management.

Under bin directory, create a user “testuser” of “Operator” group in ManagementRealm by using adduser command.

Notice that user is added by default in ManagementRealm.

Now we have to make some changes on standalone.xml, or whatever configuration is used by the JBoss instance.

We have to map groups to roles so testuser may access with the Operator role.

The next step is to create a security domain called “management“, used by our application, that delegate to realm ManagementRealm with the add of these lines:

For more informations on security domains and realms, there is an interesting StackOverflow post here

Last one, to enable https protocol, make sure we have the following lines:

For every http request the server will automatically redirect to the 8443 port that bind to the secure ssl protocol.


2. Generate SSL key

For generating an RSA key, type the following:

The default password for keystore should be changeit.

For more info, check this page.

3. Create JBOSS 6.x Web Application

Starting a new JBoss project can be really simple using Maven archetypes;
Below there are some examples for Jboss 6.4

4. Configure the Web Application

Create a file called jboss-web.xml under WEB-INF directory and fill with this:

So our application will use of “management” domain.

Then create or update web.xml, (still under WEB-INF) in this way:

We have set the following rules:

  • User access method based on BASIC authentication
  • All pages of our domain will run only by HTTPS protocol
  • All roles are granted to access by default

5. Create a rest service with role restrictions

In order to activate Jax-rs, create the following class:

Now it’s time to create our rest service implementation:

Notice that while service is accessible by all roles, the foo method is restricted only to Operator group.

To complete our example we can create a pre process interceptor to add a security layer.

6. Deploy and test our application

compile and deploy war with the following command:


Download code

Create JMS Topic with JBoss 5.1 GA and Java 6

Send message with JMS and JBoss 5.1 GA

This example will show how to produce an async JMS message after a success update operation.

The source code is based on the previous article on how to set up a restful webapp that uses ejb3 and jpa technology.

So the minimum requirements for this example are:

  • Java J2ee 6.0
  • JPA 1
  • EJB 3.x
  • JBoss 5.1 GA
  • Jersey 2.6

Topic configuration on JBoss

Under {JBOSS_HOME}/server/default/deploy directory, create a “topic” folder and add a file named MyTopic-service.xml, then write in the following content:

Notice it is also possible to put the content above on the already existent file destination-service.xml.

Send message topic from JBoss

Take the sample-ejb project of the previous article and edit the classes as described below: and

PersonBean EJB now expose the create and update method.

Execute the following command from the Windows prompt:


Expose Restful methods for create and update

Take the sample-web project of the previous article and edit the classes as described below:


Execute the following command from the Windows prompt:

Create a simple app client for subscribe to Topic

Create a simple app project archetype by executing the maven command

Edit pom.xml in this way:

Under src/main/resources, place a file named with the following content:



Run the app, it will wait for a message.

From a restclient like Postman or RestClient , set the request body in this way:

Set Content-Type on request headers with value “application/json

On the address bar, type the following with PUT method



From the app client console, a log message should display something like this

Create a Java Restful Web Application (Jersey, EJB3, JPA, JBoss 5.1, JDK 6) from ZERO with Maven

Create a web application with JBoss 5.1 and JDK 6

In this post we’ll see how to set up a complete life-cyle webapp within JBoss 5.1 on JDK 6.

Please notice this example is no-IDE dependant, therefore the procedure below is created with maven and manual editing.

The requirements / specs for this example are:

  • JDK 6
  • JBoss 5.1 GA
  • JPA (1.0)
  • EJB 3.x
  • Jersey 2.6
  • MySql

You can download the full example here

MySQL Database

Download full Database definition and script

Basically, create a database called JPADB  and two tables definied as below:



Make sure you execute the following scripts:

JBoss configuration

To make MySql work on JBoss environment, copy mysql-connector-java-5.1.18.jar under {JBOSS_HOME}/server/default/lib.

Then, create a file called mysql-ds.xml under {JBOSS_HOME}/server/default/deploy with this content:


If you want to enable remote debugging with JBoss, edit run.conf or run.bat.conf (depending on your sistem) and under the line “Sample JPDA settings for remote socket debugging“, type in the following line:

Please notice:

Setting localhost instead of yourhostname can result in access error on mysql db.

Create EJB module

From the command line, type in the following command:

This will create an ejb project compatible with Java6.

Edit pom.xml and edit the following line

By enabling the generation of the client, all the modules using the ejb can include the ejb-client on its classpath


Then, create a file called persistence.xml with the following content:




Create as the following:

The interface

The implementation

Your ejb module is now completed. Build and deploy it under {JBOSS_HOME}/server/default/deploy directory with the following command under project directory:

Windows example

The last line will install the ejb-client.jar under maven local repository in order to be included in the webapp classpath.

Create web module

First off, create a web module with the jersey archetype

Edit pom.xml so the result will be the following:

According to Jersey Documentation, last Jersey compatible with JDK 6 is version 2.6.

Notice that with the line

the war package will not include the ejb-client libraries, otherwise the binding to the ejb interfaces will fail.

Under src directory, create a file named with the following:

Now it’s time to create the model returned from our future rest service; we’ll use JAXB specs in order to return an  xml response, if requested.



Finally, create

That’s all.

Deploy web module with the following command from project root directory:

Windows command example

You can better test PersonService from a rest client browser like postman or restclient:

Type in the following on the address bar:



Set Accept: application/xml on the request header will return an xml response instead.

Tomcat – Configure remote debugging

The following hints allow to do remote debugging on tomcat using Java Platorm Debugger Architecture (JPDA).

This article is taken from the following source.

Configure Tomcat for remote debugging

Basically, it is enough to edit startup file (which can be startup.bat or under tomcat bin directory, and adding the following lines, for example below the set local command.



Finally, edit the call to the executable by adding “jpda” before “start” statement:



At this point start tomcat on the usual way.

Configure eclipse for remote debugging

The procedure for configuring eclipse for remote application is extremely simple.


Start tomcat with the above configuration, then on eclipse do the following steps:

  1. Select project to debug
  2. Choose “Debug configurations..” on Debug menu
  3. On “Remote Java Application” left menu, click “New Launch Configuration” button
  4. On Connection Type, select “Standard (Socket Attach)” combo item
  5. Type on the listening port (on the above tomcat configuration, was 8000)
  6. Click on Debug and start listening

That’s all!

Ractive.js – Create a droppable image div component with configurable size property

This example shows how to create a drag & drop image container with a configurable width and height; example’s requirements are jQuery and Ractive.js.

Download code

First off, let’s make a preview of what the user see when the page load:



To display the page above, the developer has just to write the following code:

Ractive.js allows creating component for reusing in any web application.

The code for the image drag & drop div component is the following:


The viewmodel will initialize the component and the page itself with the data to display; furthermore, the component fires an event ‘imagerefused’ in case the image dropped does not satisfy the width / height requirements specified in the imageuploader component, so it’s up to the viewmodel to catch and display a properly message.


Here’s the final result:


image uploader


Maven – Generate a package with external resources

Maven – How to generate a package with external resources

While making a java batch, it’s a common way to generate a working directory structure like the following:

The directories above will contain:

  • conf – external configuration properties
  • lib – the jar libraries, comprensive of the main jar
  • logs – the log files
  • bin – the sh / bat script file within the instructions to run the batch properly

Our source structure folder will be similar:

  • applconf – external configuration properties
  • scripts – the sh / bat script file within the instructions to run the batch properly
  • logs – the log files

Now it’s time to edit pom.xml properly.


The following lines will copy applconf content inside target conf directory

The following lines copy scripts file inside bin directory

The following copy main jar with dependencies inside lib directory:

The following will generate manifest.inf within the main jar package

Finally, the pom.xml declare that directive to build the zipped package are contained inside assembly-app.xml file


These directives will copy jar dependencies inside lib directory and applconf content inside conf directory.

If our need is to place main jar outside lib directory, copy the following lines instead:


Maven – build package for different environments

Build package for different environments using Maven

To make life easier for programmers who need to test and deploy application to a remote environment using different properties, it is possible to properly configure the pom file to fit with own necessity with just one command.

Suppose your are dealing with a web application that is tested on a local Tomcat;
the application itself read from a properties file mapped for the proper environment, one for local testing and one for distribution environment; so your need could be:

  • Build the webapp locally and distribuite to the local tomcat
  • Build the webapp and deploy it together with the properly properties file

Use the profile directive on the pom.xml to specify a test or deploy action in the following way:

Notice the following points of interest:

  • The tomcat7-maven-plugin can automatically deploy a war inside tomcat deploy folder by just giving the address in which tomcat is listening
  • The maven-antrun-plugin can execute some ant based tasks; In the case above we first delete the previous file and then copy the file (included in the source folder) to the output build directory, renaming it to

Also notice that, mvn clean install run the test profile by default, because of the activeByDefault property set to true.

Therefore, to run the deploy profile just type the following command:




WPF – deal with application settings in MVVM

WPF – Application settings in MVVM

When I had to do with WPF and decided to follow the MVVM paradigm as strictly as possible, my first questions where how to treat application settings, where and when.

The best suggestion I read come from stackoverflow, so below I’ll write the code to implement what I understood from there.

For this purpose, there are no special requirements except by using any MVVM framework you like (Personally I use MVVM Foundation by Josh Smith) and an IOC container:

In my applications I always use TinyIoC because it’s considerable smart and fast.

When the application starts,  the IoC register a component that acts like a bridge between the viewmodel and the settings class by copying, loading and saving the properties.

So for this example let’s create a simple settings class that has two properties named Host and Port.


The class above will not be directly referenced by view, viewmodel or business service.

Since we need a single instance of settings par application, the singleton pattern is our natural choice.


Now create an interface that instead will be used to reference the app settings class and contains the abstraction of all the settings properties plus the methods Load() and Save().


After creating the interface we create its implementation:


The class above does all the stuff we need to deal with our application settings !

Now it’s time to register the interface using the IoC at the startup of our application;

we do this by creating an event that is called when the application starts.




Now the interface is registered, we can finally resolve it from the ViewModel:


Final considerations

Despite the large use of code neeeded for doing this job, the strong point of adopting this pattern is the decoupling of the “business part” and the viewmodel; just think you can replace – in any moment with a minimal change of code – the SettingsConfigProvider class with another one that write and load data from a Database!