External JSON Configuration

Here is one way using JSON as configuration to specify custom settings for an application.


// ConfigurationLoader Interface

public interface ConfigurationLoader {

public Object loadJsonConfiguration();
}

// HandlerConfigurationLoader class
public class HandlerConfigurationLoader implements ConfigurationLoader {
 private static final String HandlerConfigJsonFile = "c:\\Temp\\mapping.json";

 @Override
 public Object loadJsonConfiguration() {
 HandlerConfiguration handlerConfig = null;
 JsonReader reader = null;

 try {
 reader = new JsonReader(new InputStreamReader(
 new FileInputStream(
 new File(HandlerConfigJsonFile))));
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 }

 Gson gson = new Gson();
 return handlerConfig = gson.fromJson(reader, HandlerConfiguration.class);
 }
}

// HandlerConfiguration class
public class HandlerConfiguration implements Serializable {
 private String handlerClazz;
 private List<MethodMapping> methods;

 public HandlerConfiguration(String handlerClazz, List<MethodMapping> methods) {
 this.handlerClazz = handlerClazz;
 this.methods = methods;
 }

 public String getHandlerClazz() {
 return handlerClazz;
 }

 public void setHandlerClazz(String handlerClazz) {
 this.handlerClazz = handlerClazz;
 }

 public List<MethodMapping> getMethods() {
 return methods;
 }

 public void setMethods(List<MethodMapping> methods) {
 this.methods = methods;
 }

 @Override
 public String toString() {
 return "HandlerConfiguration{" +
 "handlerClazz='" + handlerClazz + '\'' +
 ", methods=" + methods +
 '}';
 }
}

// MethodMapping class
public class MethodMapping implements Serializable {
 private String methodName;
 private String clazzName;

 public MethodMapping() {
 }

 public MethodMapping(String methodName, String clazzName) {
 this.methodName = methodName;
 this.clazzName = clazzName;
 }

 public String getMethodName() {
 return methodName;
 }

 public void setMethodName(String methodName) {
 this.methodName = methodName;
 }

 public String getClazzName() {
 return clazzName;
 }

 public void setClazzName(String clazzName) {
 this.clazzName = clazzName;
 }

 @Override
 public boolean equals(Object o) {
 if (this == o) return true;
 if (o == null || getClass() != o.getClass()) return false;

 MethodMapping that = (MethodMapping) o;

 if (clazzName != null ? !clazzName.equals(that.clazzName) : that.clazzName != null) return false;
 if (methodName != null ? !methodName.equals(that.methodName) : that.methodName != null) return false;

 return true;
 }

 @Override
 public int hashCode() {
 int result = methodName != null ? methodName.hashCode() : 0;
 result = 31 * result + (clazzName != null ? clazzName.hashCode() : 0);
 return result;
 }

 @Override
 public String toString() {
 return "MethodMapping{" +
 "methodName='" + methodName + '\'' +
 ", clazzName='" + clazzName + '\'' +
 '}';
 }
}

// Unit Test client class
public class HandlerConfigurationTest {

 @Test
 public void testLoadHandlerConfiguration() {
 ConfigurationLoader configurationLoader = new HandlerConfigurationLoader();
 HandlerConfiguration handlerConfiguration =
 (HandlerConfiguration) configurationLoader.loadJsonConfiguration();

 System.out.printf("HandlerConfiguration Loaded: %s%n", handlerConfiguration);
 }

}

{
"handlerClazz" : "model.ModelObject",
"methods" : [
{ "methodName" : "process", "clazzName" : "some.package.name.Handler" }
]
}

Embedded ActiveMQ

Send and receive a message using embedded active mq.

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>SelfContainedUnitTest</groupId>
<artifactId>SelfContainedUnitTest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
<maven.compiler.plugin>2.3.2</maven.compiler.plugin>
<spring.version>4.0.1.RELEASE</spring.version>
<slf4j.version>1.6.1</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<activemq.version>5.8.0</activemq.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<type>jar</type>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>

<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
</dependency>

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.12</version>
</dependency>

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>

<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>${activemq.version}</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgument>
-XDignore.symbol.file
</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>

</project>

ActiveMQTest.java


package embedded;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.jms.*;
import java.util.UUID;

/**
* Created by david.king
*/
public class ActiveMQTest {
private ActiveMQConnectionFactory activeMQConnectionFactory;
private Connection connection;
private Session session;
private MessageProducer messageProducer;
private MessageConsumer messageConsumer;
private Destination destination;
private String queueName = String.format("EmbeddedQueue%s", UUID.randomUUID().toString().substring(0,6));

@Test
public void spinUpBrokerAndSendAndReceiveMessage() throws Exception {
String message = "<message />";

// Send a message
send(message);

// Receive message
System.out.printf("Message Received: %s%n", receive());

}

private void send(String messageToSend) throws Exception {
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

TextMessage textMessage = session.createTextMessage(messageToSend);

producer.send(textMessage);

System.out.printf("JMS Message Sent: %s%n", textMessage);
}

private String receive() throws Exception {
MessageConsumer consumer = session.createConsumer(destination);

Message message = consumer.receive(3000);

TextMessage theTextMessage = (TextMessage) message;
String xml = theTextMessage.getText();
return xml;
}

@Before
public void setUp() throws Exception {
activeMQConnectionFactory =
new ActiveMQConnectionFactory(
"vm://localhost?broker.persistent=false");

connection = activeMQConnectionFactory.createConnection();

connection.start();

session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

destination = session.createQueue(queueName);
}

@After
public void tearDown() throws Exception {
session.close();
connection.close();
}
}

Spring Java Config for Log4J

Applications write interesting information to its log. For this purpose, there is a well known library named, Log4J. It is used in many iterations, including the ability to write custom logs that are size restricted, so that once the size limit is reached, a new log is created. In addition, there are other tools that make perusing a log nice, Splunk is one of them.

The following code will provide you with a basic starting point for a Restful Web Service using the Spring Framework.

The artifacts are as follows:

  • configuration.LoggingConfig
  • controllers.LoggingController
  • controllers.LoggingServiceInterface
  • controllers.LoggingService
  • resources/log4j.properties
  • webapp/META-INF/log4j.properties
  • webapp/WEB-INF/web.xml
  • webapp/index.jsp

BUILDING THE PROJECT

Create a webapp maven project with the name LoggingConfig.


// LoggingConfig

package configuration;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
* Created by david.king
*/
@Configuration
@EnableWebMvc
@ComponentScan("controllers")
public class LoggingConfig {

public LoggingConfig() {}

@Bean
public ConsoleAppender consoleAppender() {
ConsoleAppender consoleAppender = new ConsoleAppender();
consoleAppender.setThreshold(Level.ALL);
PatternLayout patternLayout = new PatternLayout();
patternLayout.setConversionPattern("%d %-5p [%c{1}] %m %n");
consoleAppender.setLayout(patternLayout);
return consoleAppender;
}

}

// LoggingController

package controllers;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by david.king
*/
@RestController
public class LoggingController {
@Autowired
LoggingServiceInterface loggingService;

@RequestMapping(value = "/logging", produces = MediaType.APPLICATION_JSON_VALUE)
public String produceLogging() {
for (int i = 0; i < 5; i++) {
loggingService.performLogging();
}

String success = "Success";
return new Gson().toJson(success);
}

}

// LoggingServiceInterface

package controllers;

/**
* Created by david.king
*/
public interface LoggingServiceInterface {
public void performLogging();
}

// LoggingService

package controllers;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

/**
* Created by david.king
*/
@Service
public class LoggingService implements LoggingServiceInterface {
private static final Logger logger = Logger.getLogger(LoggingService.class);

public LoggingService() {}

@Override
public void performLogging() {
logger.info("I am performing some logging, you should see this message in the logs.");
}
}

LOG4J PROPERTIES

#define the console appender
log4j.appender.consoleAppender = org.apache.log4j.ConsoleAppender
log4j.appender.consoleAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x – %m%n

log4j.rootLogger = INFO, consoleAppender

JAXB Conversion Utility

  • Convert a JMS message to a JAXB Object
  • Convert a TextMessage to an Object
  • Convert a TextMessage to an InputStream

 


package com.verio.adapt.javacore.util;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
* Created by david.king
*/
public final class JaxbConversionUtil {

public static Object convertJMSMessageToJAXBObject(Class typeToConvertTo, Message jmsMessage) {
if (jmsMessage instanceof TextMessage) {
return convertTextMessageToObject(typeToConvertTo, jmsMessage);
}
return null;
}

private static Object convertTextMessageToObject(Class typeToConvertTo, Message jmsMessage) {
Object objToReturn = null;

try {
JAXBContext jaxbContext = JAXBContext.newInstance(typeToConvertTo);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
objToReturn = unmarshaller.unmarshal(convertTextMessageToInputStream(jmsMessage));
if (null == objToReturn) {
System.out.printf("[%s], %s", "XML Parsing Error", "The convertTextMessageToObject failed.");
}

return objToReturn;
} catch (JAXBException ex) {
ex.printStackTrace();
}
return null;
}

private static InputStream convertTextMessageToInputStream(Message jmsMessage) {
TextMessage textMessage = (TextMessage)jmsMessage;
try (InputStream inputStream = new ByteArrayInputStream(textMessage.getText().getBytes("UTF-8"))) {
return inputStream;
} catch (IOException | JMSException ex) {
ex.printStackTrace();
}
return null;
}
}

Hello World Restful Web Service Using Spring

Spring Framework provides all kinds of wonderful benefits to the modern developer. It has provided a way to build REST Web Services that is straightforward and productive. You only have to use what you need from Spring, its not an all or nothing framework.

In order to facilitate building our ‘Hello World’ service, we will first open IntelliJ IDEA 13 Community Edition and create a new project.

Create new project.

Select Maven as the project type and enter the project name as HelloWorldRestService as shown.

Enter project name.

Click the Next button and select the checkbox [] Create from archetype, then choose the maven-archetype-webapp, click next and finish. If asked, select to enable auto import for your maven settings.

Your project should look like the following.

Initial project view.

Replace your pom.xml file will the contents below.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

<groupId>HelloWorldRestService</groupId>
 <artifactId>HelloWorldRestService</artifactId>
 <version>1.0-SNAPSHOT</version>
 <packaging>war</packaging>
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <java.version>1.7</java.version>
 <maven.compiler.plugin>2.3.2</maven.compiler.plugin>
 <spring.version>4.0.0.RELEASE</spring.version>
 </properties>

<dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.11</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-web</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-jms</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-orm</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-oxm</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-test</artifactId>
 <version>${spring.version}</version>
 </dependency>

<dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.17</version>
 </dependency>

<dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-api</artifactId>
 <version>1.7.2</version>
 <type>jar</type>
 </dependency>

<dependency>
 <groupId>com.google.code.gson</groupId>
 <artifactId>gson</artifactId>
 <version>2.2.2</version>
 </dependency>
 </dependencies>

<build>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-compiler-plugin</artifactId>
 <version>${maven.compiler.plugin}</version>
 <configuration>
 <source>${java.version}</source>
 <target>${java.version}</target>
 <compilerArgument>
 -XDignore.symbol.file
 </compilerArgument>
 </configuration>
 </plugin>
 </plugins>
 </build>
</project>

Create Rest Controller

Create a new package named hello in /src/main/java. Create a new class named HelloRestController, then annotate the class with the @Controller annotation and enter the following code.

private final Logger logger = LoggerFactory.getLogger(HelloRestController.class);

@RequestMapping(value = "/helloworld", method = RequestMethod.GET)
 public @ResponseBody String displayTemplateJSON() throws Exception {
 logger.info("displayTemplateJSON() method invoked.");
 Map<String, Object> dataStructure = new HashMap<>();
 Map<String, Object> data = new HashMap<>();
 Gson gson = new Gson();

// build a simple data structure
 dataStructure.put("dataStructure", getStructure());
 logger.info("displayTemplateJSON(), building data structure.");

// convert Map to JSON
 String json = gson.toJson(dataStructure, Map.class);
 logger.info("displayTemplateJSON(), converting data structure to JSON.");

if (json != null) {
 logger.info("displayTemplateJSON(), returning data structure as JSON.");
 return json;
 }

return "\"{ \"No data foundl.\"}\"";
 }

 private Map<String, Object> getStructure() {
 Map<String, Object> data = new HashMap<>();
 data.put("Task", "Learn Spring Rest Web Services.");
 data.put("Company", "Example Inc.");

List<String> requestTypes = new ArrayList<>();
 requestTypes.add("RequestTypeOne");
 requestTypes.add("RequestTypeTwo");
 requestTypes.add("RequestTypeThree");
 requestTypes.add("RequestTypeFour");
 requestTypes.add("RequestTypeFive");
 requestTypes.add("RequestTypeSix");
 requestTypes.add("RequestTypeSeven");
 requestTypes.add("RequestTypeEight");
 data.put("RequestTypes", requestTypes);

logger.info("displayTemplateJSON(), data structure is: {}", data);
 return data;
 }

Configuration

You’re almost done. To ensure that Spring knows about your MVC Controller and outputs your logging, create a class named WebConfig, annotate it with @Configuration, @EnableWebMvc and @ComponentScan as shown.

intellij-webconfig

Next, create log4j.properties in /src/main/resources with the following content.

intellij-log4j

 

 

web.xml Configuration

A web.xml is required for this setup (note: there are ways to get rid of this as well, not covered in this article). Replace the contents of your web.xml with the following.


<?xml version="1.0" ?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">

<display-name>Web Application</display-name>
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
 <param-name>contextClass</param-name>
 <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>hello.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>myServlet</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Building and Deploying

Run maven clean and then install, deploy to your favorite Servlet container.

Invoke the rest service at: http://localhost:8080/HelloWorldRestService/helloworld

 

Enjoy.