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 = *.mythrusteddomain.it

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

@WebFilter(urlPatterns="/*")
public class ApiOriginFilter implements Filter {

	@Inject
	ConfigService config;
	
	@Inject
	Logger logger;
	
	static String origins;
	
	static Pattern pattern;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		origins = config.getProperty("cors.domain.supported");
		
	}
	
	@Override
	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 = matcher.group(0);
						
						logger.info("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);

	}

	@Override
	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:

127.0.0.1 foo.yourdomain.it

Then every XHRequest will point to http://foo.yourdomain.it/[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 ArqTest.java 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

 

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:

Person

Cities

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:

Optionally:

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 City.java

and Person.java

Create PersonBeanLocal.java as the following:

The PersonRemote.java interface

The PersonBean.java 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 jndi.properties 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.

Create CityResult.java

Create PersonResult.java

Finally, create PersonService.java

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:

http://localhost:8084/sample-web/webapi/person/id/1

restclient

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

MyBatis Generator – How to use MBG

MyBatis Generator – Run MBG

MyBatis Generator can run in several ways, in this guide it will be shown how to run MBG from

  • Java batch
  • Ant

First of all, create your environment with a so built directory tree:

  • src
    • mapper
    • model
    • xml
    • batch
    • log4j.properties
  • lib
    • mybatis-generator-core-x.x.x.jar
    • mybatis-x.x.x.jar
    • log4j-x.x.x.jar
    • (jdbc drivers.jar)
  • build.xml
  • generatorConfig.xml

 

CONFIGURATION

Here’s a sample of generatorConfig.xml:

 

JAVA BATCH

In batch package, create class called Generator and put this code:

 ANT TASK

Notice that line:

allow to find log4j.properties into src folder; otherwise, log4j should be located into project root folder.

MyBatis – Create your custom Example class

Create own Example class with MyBatis

Sometimes it happens you need to extend the Example class generated with myBatis with some a specific criteria requirement.

For example, with a query like this:

the PersonExample model may not be enough, due to the criteria related to tableCar at query last line. How could we write a custom criteria ?
There are severaly ways to do this, however our primary goal is to keep untouched the generated example/critera classes.

The solution comes with extending the PersonExample and Criteria class, in order to achieve an elegant solution like this:

 

Here’s the hint code to write the PersonExtendedCriteria class:

and PersonExampleCustom class: