Business, Code, JavaEE, SOA, Technical, WebServices

Current Technology Research

Languages – used to solve problems that work with user interaction and machine development.

Kotlin for Java and Android.

Swift for IOS and Mac.
Cloud Technologies and Platforms – Infrastructure, functions and platforms that provide integrated solutions for systems and applications high availability and deployments.

Amazon Web Services (AWS).

Google Firebase

Understanding Domain Driven Design – is an approach to software development for complex needs by connecting the implementation to an evolving model.

http://en.wikipedia.org/wiki/Domain-driven_design

http://dddsample.sourceforge.net/

http://www.domainlanguage.com/


Reactive Programming
– is a programming paradigm oriented around data flows and the propagation of change.

http://en.wikipedia.org/wiki/Reactive_programming

http://news.dice.com/2014/01/13/how-is-reactive-different-from-procedural-programming/

https://www.youtube.com/watch?v=jIsxcXBWthI


Concurrency in Java
– is a form of computing in which several computations are executing during overlapping time periods –concurrently – instead of sequentially (one completing before the next starts). This is a property of a system – this may be an individual program, a computer, or a network – and there is a separate execution point or “thread of control” for each computation (“process”).

http://en.wikipedia.org/wiki/Concurrent_programming

http://en.wikipedia.org/wiki/Concurrency_in_java

http://tutorials.jenkov.com/java-concurrency/index.html

Hexagonal Architecture – Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases.

As events arrive from the outside world at a port, a technology-specific adapter converts it into a usable procedure call or message and passes it to the application. The application is blissfully ignorant of the nature of the input device. When the application has something to send out, it sends it out through a port to an adapter, which creates the appropriate signals needed by the receiving technology (human or automated). The application has a semantically sound interaction with the adapters on all sides of it, without actually knowing the nature of the things on the other side of the adapters.

http://alistair.cockburn.us/Hexagonal+architecture

Software Company

http://asp-software.org/www/misv_resources/marketing-articles/how-to-make-a-million-dollars-in-software/

 

Code, JavaEE, SOA, Technical, WebServices

Read Remote File Contents

@Test
public void formatOutput() {
    final String routerJS =
            "static/master/router.js";
    readRemoteFileContents(routerJS);
}

private void readRemoteFileContents(final String fileToRead) {
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection)githubURL(fileToRead).openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Scanner scanner = null;
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        scanner = new Scanner(
                new StringReader(
                        reader.lines().collect(
                                Collectors.joining(System.getProperty("line.separator")))))
        .useDelimiter(System.getProperty("line.separator"));

        while(scanner.hasNext()) {
            System.out.printf("%s%n", scanner.next());
        }
    } catch (IOException e) {

    } finally {
        if (scanner != null) scanner.close();
        if (connection != null) connection.disconnect();
    }

}

private URL githubURL(final String fileToRead) throws MalformedURLException {
    final String baseGitHubFiles = "https://raw.githubusercontent.com/enterprisesaas/";
    final StringBuilder url = new StringBuilder(baseGitHubFiles).append(fileToRead);
    return new URL(url.toString());
}
Code, JavaEE, SOA, Technical, WebServices

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.

Code, JavaEE, SOA

Dynamic Method Invocation – Java Reflection

This code is the beginning of a basic CRUD pattern implementation, where the POJO (User) has a handler (UserHandler) that processes the required business logic related to the POJO. The basic type is the interface DynamicMethodInvoker that accepts a type T that is the return type for the method invocation. The default implementation of the DynamicMethodInvoker is the abstract class AbstractDynamicMethodInvoker. The handler (UserHandler) will subclass the AbstractDynamicMethodInvoker and implement an interface named CrudProcessor. CrudProcessor accepts two generic types, that is T, representing the POJO and R, representing the return type for the create, update and delete methods. The code follows:

DynamicMethodInvoker

/**
 * DynamicMethodInvoker
 * User: David King
 */
public interface DynamicMethodInvoker<R> {

/**
 * invokeMethod
 *
 * Invoke a method on the given objectInstance with a return type of R
 *
 * @param objectInstance
 * @param methodName
 * @param methodParameterTypes
 * @param methodParameterValues
 * @return
 */
 public R invokeMethod(Object objectInstance,
 String methodName,
 Class[] methodParameterTypes,
 Object[] methodParameterValues);

/**
 * invokeVoidMethod
 *
 * This method invocation does not have a return
 *
 * @param objectInstance
 * @param methodName
 * @param methodParameterTypes
 * @param methodParameterValues
 */
 public void invokeVoidMethod(Object objectInstance,
 String methodName,
 Class[] methodParameterTypes,
 Object[] methodParameterValues);
}

AbstractDynamicMethodInvoker

import metadata.CrudResponse;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * AbstractDynamicMethodInvoker
 * User: David King
 */
public abstract class AbstractDynamicMethodInvoker implements DynamicMethodInvoker<CrudResponse> {

@Override
 public CrudResponse invokeMethod(Object objectInstance, String methodName, Class[] methodParameterTypes, Object[] methodParameterValues) {
 CrudResponse response = new CrudResponse();
 Method methodToInvoke = null;

try {
 methodToInvoke = objectInstance.getClass().getMethod(methodName, methodParameterTypes);
 response = response.getClass().cast(methodToInvoke.invoke(objectInstance, methodParameterValues));

if (response.isErrorCondition()) {
 return response;
 }
 } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
 e.printStackTrace();
 }

return response;
 }

@Override
 public void invokeVoidMethod(Object objectInstance, String methodName, Class[] methodParameterTypes, Object[] methodParameterValues) {
 Method methodToInvoke = null;

try {
 methodToInvoke = objectInstance.getClass().getMethod(methodName, methodParameterTypes);
 methodToInvoke.invoke(objectInstance, methodParameterValues);
 } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
 e.printStackTrace();
 }
 }
}

CrudProcessor


import java.util.Collection;

/**
 * CrudProcessor
 * User: David King
 */
public interface CrudProcessor<T, R> {
 public R create(T t);
 public R update(T t);
 public R delete(T t);
 public T view(String id);
 public Collection<T> viewAll(int limitCount);
}

User


import java.io.Serializable;
import java.util.UUID;

/**
 * User
 * User: David King
 */
public class User implements Serializable {
 private String id;
 private String firstName;
 private String lastName;
 private String email;

public User() {
 setId(UUID.randomUUID().toString());
 }

public User(String id, String firstName, String lastName, String email) {
 this.id = id;
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }

public String getId() {
 return id;
 }

public void setId(String id) {
 if (null != id) {
 this.id = id;
 }
 }

public String getFirstName() {
 return firstName;
 }

public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

public String getLastName() {
 return lastName;
 }

public void setLastName(String lastName) {
 this.lastName = lastName;
 }

public String getEmail() {
 return email;
 }

public void setEmail(String email) {
 this.email = email;
 }

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

User user = (User) o;

if (!email.equals(user.email)) return false;
 if (!firstName.equals(user.firstName)) return false;
 if (!id.equals(user.id)) return false;
 if (!lastName.equals(user.lastName)) return false;

return true;
 }

@Override
 public int hashCode() {
 int result = id.hashCode();
 result = 31 * result + firstName.hashCode();
 result = 31 * result + lastName.hashCode();
 result = 31 * result + email.hashCode();
 return result;
 }

@Override
 public String toString() {
 return "User{" +
 "id='" + id + '\'' +
 ", firstName='" + firstName + '\'' +
 ", lastName='" + lastName + '\'' +
 ", email='" + email + '\'' +
 '}';
 }
}

UserHandler


&nbsp;

import metadata.CrudProcessor;
import metadata.CrudResponse;
import model.User;

import java.util.Collection;

/**
 * UserHandler
 * User: David King
 */
public class UserHandler extends AbstractDynamicMethodInvoker
 implements CrudProcessor<User, CrudResponse> {

public UserHandler() {}
 @Override
 public CrudResponse create(User user) {
 CrudResponse response = new CrudResponse();
 response.setErrorCondition(Boolean.FALSE);
 response.setResult("Success");
 return response;
 }

@Override
 public CrudResponse update(User user) {
 CrudResponse response = new CrudResponse();
 response.setErrorCondition(Boolean.FALSE);
 response.setResult("Success");
 return response;
 }

@Override
 public CrudResponse delete(User user) {
 CrudResponse response = new CrudResponse();
 response.setErrorCondition(Boolean.FALSE);
 response.setResult("Success");
 return response;
 }

@Override
 public User view(String id) {
 return null;
 }

@Override
 public Collection<User> viewAll(int limitCount) {
 return null;
 }
}

DynamicInvocationTest (Junit)


&nbsp;

import metadata.CrudResponse;
import model.User;
import org.junit.Test;

/**
 * DynamicInvocationTest
 * User: David King
 */
public class DynamicInvocationTest {

@Test
 public void testDynamicMethodInvocation() {
 User user = new User();
 user.setFirstName("David");
 user.setLastName("King");
 user.setEmail("david.king@somehost.com");
 AbstractDynamicMethodInvoker abstractDynamicMethodInvoker = new UserHandler();
 CrudResponse response = abstractDynamicMethodInvoker.invokeMethod(
 abstractDynamicMethodInvoker,
 "create",
 new Class[] { User.class },
 new Object[] {user});
 System.out.printf("TestDynamicMethodInvocation: %s%n", response);
 }
}

Code, JavaEE, SOA, WebServices

Messaging Lifecycle Design

Goals:

  1. Abstract away common details for processing data exchanged using Messaging Oriented Middleware.
  2. Start with the common items and drill-down into the details.
  3. Support exchanging various types of text data, e.g., JSON, XML, YML, CSV
  4. Declare a lifecycle interface with the common items defined to be implemented by an abstract class which will them be subclassed by detail classes.

MessagingLifecycle <interface>

import javax.jms.Message;
import java.io.InputStream;
import java.util.Map;

public interface MessagingLifecycle {

/**
 * loadProductMetaData
 *
 * Loads ALL meta data connected to the given object instance
 * @return
 */
 public Map<String, Object> loadProductMetaData();

/**
 * convertMessageToInputStream
 *
 * Converts the given message to an InputStream
 * @param message
 * @return
 */
 public InputStream convertMessageToInputStream(Message message);

/**
 * performXSLTransformations
 *
 * Allows a product's given XML to be massaged using XPath
 * @param inputStream
 * @return
 */
 public InputStream performXSLTransformations(InputStream inputStream);

/**
 * convertInputStreamToXMLForRequestType
 *
 * Convert the inputStream into a JAXB object instance
 * @param inputStream
 * @param typeToConvertTo
 * @return
 */
 public Object convertInputStreamToXMLForRequestType(InputStream inputStream, Class typeToConvertTo);

}