...

TEASER

by user

on
Category: Documents
58

views

Report

Comments

Description

Transcript

TEASER
TEASER
Developing Java Applications
Copyright © 2014 Hakin9 Media Sp. z o.o. SK
Table of Contents
Java Media Framework
by Buddhima Wijeweera
Sometimes is necessary of using media thru Java applications, this varies from simply integrating
an audio player to streaming video. Still it’s not common to add an audio or a video player with
Java, simply with the help of an IDE. Therefore, you’ll need to get the help of a 3ed party library
to complete that purpose. One solution for this problem is to use Java Media Framework.
An Object Oriented Model for Robust Multi-threaded Programming
by William la Forge
This article is about JActor2 a multi-threaded OO programming model, inspired by Alan Kay’s early
thoughts on Objects. JActor2 is based on asynchronous 2-way messaging with assured responses. The
net result being code that is both simpler and more robust, and hence easier to maintain.
Introduction to Google’s Guava Library
by Hubert Klein Ikkink
In this article author wanted to show how we can achieve functional-like programming with
Google Guava. The author introduces functions and predicates that can be used to map and filter
collections in Java.
Developing, Deploying and Consuming a Web Services Using Netbeans IDE
by Rajeev Hathi
This article will walk you through the steps of creating, deploying, testing and consuming a
simple Hello World JAX-WS Web service as part of a code-first approach using the popular Java
based Netbeans IDE.
Introduction to Spring 4 By Using Spring Boot
by Timothy Spann
In this article Timothy Spann will lead you through a fresh Spring version and a fresh Spring Tool
to assist in rapidly developing Spring 4 REST Applications. You will see how easy it is to develop a
RESTful Spring 4 application that connects to a MongoDB database using the excellent new tool, Spring
Boot. It will be a quick overview, but you will find a lot of referenced information to continue with.
How to Secure Apache Tomcat
by Ioannis Kostaras
Web Security is a multi-layered topic that must cover the operating system, the network, the web
server, the supporting DBMS, and the web application itself. This article provides useful steps
to secure the third aforementioned layer and more specifically the Apache Tomcat installation
on Ubuntu (and Linux in general) operating system. Which files to protect, what kind of users to
create and how to enable SSL are some of the topics covered.
3
07
15
30
43
50
60
Developing Java Applications
74
Preserving Domain Objects Across Layers
by Paul Wells
In this article, Paul Wells and his team present an example of how to configure Jackson with
Spring OAP and Spring Data JPA in order to eliminate the need to translate domain classes to
these bridging classes – leaving the encapsulation intact and leaving us free to concentrate on
building an optimal domain object model.
86
Java and Smart Cards
by Soma Ghosh
In today’s world, it is a dire necessity to make any user oriented application to be available on a
smart card or a mobile device. Hence, a need arises for an open, safe, inter-operable environment
to develop and deploy these applications. Java card API has the answer.
Part I: Cloud Computing – An Overview
by Sujatha Perepa, Bhargav Perepa
The continuous evolution of cloud computing and its successful result oriented implementations
led to an enthusiastic participation from vendors, open source consortiums, standards bodies
and businesses. In part I of this paper, authors will focus on Cloud Computing overview and its
concepts. In Part II (next issue), authors plan to explore the realm of cloud computing from the
IBM perspective and how IBM is participating and contributing to the Cloud’s open architecture
initiative.
Collaborative Development for Faster Solutions
by Leticia Adriana Simental Rodríguez and Victor Adrian Sosa Herrera
91
100
In this article, Leticia and Victor want to show how Collaboration team with IBM Rational
Developer Application and IBM Rational Team Concert can optimize the time that takes a
development team requires to reproduce and fix an application problem.
advertisement
Developing Java Applications
Dear Readers!
I
haven’t published anything for a while. Despite this, I didn’t forgot how pleasant is to carefully prepare
each article or letter for you, and to cooperate with wonderful authors whose experience is vast and dates
sometimes back to the beginning of computers and programming era. And all of this with the awareness,
that your eyes will watch a high quality magazine.
This time we have a lot of great articles that for sure will attract your attention for sure and cause that you
come back many times to read it again. So I would first encourage you dear reader drive your attention to the
article Rajeev Hathi’s article: “Developing, deploying and consuming a Web Service using Netbeans IDE”
is pretty easy to follow for anyone, even though it is an advanced topic. The writing ability of this author
makes that the subject seem very simple. Next, if you are a developer, I would like to attract your interest
with the article “Introduction to Google’s Guava library” article written by Hubert Klein Ikkink. I also can
suggest a very good article written by Sujatha and Bhargav Perepa about introduction to Cloud Computing.
Their article will be the first of a series of three articles which promise additional in-depth discussion on this
timely subject. I encourage you to collect all three parts of the article whose next two parts will be published
in upcoming releases. Please stay tuned! If you also value a good read then I can suggest a really good article
written by Buddhima Wijeweera who will tell you more how to use Java Media Framework.
Of course I would like to write about every article we have in this release but it would be better if you dear
reader examine them by yourself and even if it is possible wire us a comment. I encourage you to share with us
your feelings and suggestions about our articles by sending an mail to [email protected].
Java Magazine Team
5
Editor in Chief: Karol Ruczajewski
[email protected]
Editorial Advisory Board: Laszlo Acs, Armando Estanol, Osvaldo
Tulini, Jim Powell, Mbella Ekoume, Jose Antonio Gordillo,
Jonathan Segura Castro, Jeremy Sechler.
Special thanks to our Beta testers and Proofreaders who helped
us with this issue. Our magazine would not exist without your
assistance and expertise.
Publisher: Paweł Marciniak
[ GEEKED AT BIRTH ]
Managing Director: Ewa Dudzic
Production Director: Andrzej Kuca
[email protected]
Art. Director: Ireneusz Pogroszewski
[email protected]
DTP: Ireneusz Pogroszewski
Marketing Director: Ewa Dudzic
Publisher: Software Media SK
02-676 Warsaw, Poland
Postepu 17D
Whilst every effort has been made to ensure the highest quality
of the magazine, the editors make no warranty, expressed
or implied, concerning the results of the content’s usage.
All trademarks presented in the magazine were used for
informative purposes only.
All rights to trademarks presented in the magazine are reserved
by the companies which own them.
DISCLAIMER!
The techniques described in our magazine may be used
in private, local networks only. The editors hold no
responsibility for the misuse of the techniques presented
or any data loss.
You can talk the talk.
Can you walk the walk?
[ IT’S IN YOUR DNA ]
LEARN:
Advancing Computer Science
Artificial Life Programming
Digital Media
Digital Video
Enterprise Software Development
Game Art and Animation
Game Design
Game Programming
Human-Computer Interaction
Network Engineering
Network Security
Open Source Technologies
Robotics and Embedded Systems
Serious Game and Simulation
Strategic Technology Development
Technology Forensics
Technology Product Design
Technology Studies
Virtual Modeling and Design
Web and Social Media Technologies
www.uat.edu > 877.UAT.GEEK
Please see www.uat.edu/fastfacts for the latest information about
degree program performance, placement and costs.
Developing Java Applications
Preserving Domain Objects Across Layers
by Paul Wells
In this article we present an example of how to configure Jackson with Spring OAP and
Spring Data JPA in order to eliminate the need to translate domain classes to these bridging
classes – leaving the encapsulation intact and leaving us free to concentrate on building an
optimal domain object model.
What you will learn...
• You will learn how to create a Hello World Spring MVC web application configured to accept and return Json data
across a REST API while storing the data in a MySQL database.
What you should know...
• You will need some familiarity with Java, XML, Json, SQL and Maven.
In a Spring MVC webserver there are two areas which often lead the programmer to abandon the solid OO
principal of encapsulation. One is the need to martial objects to and from the client as Json and the other is
to load and save objects in a relational database. In the former case, a Data Transfer Object (DTO) is used
as a bridge between the Java domain and Json in the controller layer. In the latter case, a Data Access Object
(DAO) is used as a bridge between the Java domain and the relational database in the repository layer.
Hence, the encapsulation is blown at two points: when domain objects are translated field-by-field to DTOs
– because DTOs are what the marshalling tools appear to require – and similarly when domain objects are
translated field-by-field to DAOs – because DAOs are what the ORM tools appear to require.
Domain Objects and Layers
Layers of abstraction give structure and clarity to a software architecture. You can tell at a glance what
sort of thing should be happening in, say, the data access layer or the service layer without needing to pick
through the code line by line. Without using layering you, the programmer, give yourself a much tougher job
tracking down defects, implementing new stories and bringing new team members up to speed.
“...putting behaviour into the domain objects should not contradict the solid approach of using layering to
separate domain logic from such things as persistence and presentation responsibilities.” Martin Fowler
In this article we will build a minimalist Spring MVC application with a REST API. To keep things brief
we will not be building a client application nor writing any unit tests or integration tests and everything
can be installed and run locally. Our server will have a controller layer, a service layer and a repository
layer. There will be a single business object and we will implement just one method of the API. We also
won’t be doing anything fancy with transactions.
The point of this bare-bones example is to show how, with the right libraries and configuration, behaviourmodelling domain objects can be preserved across architectural layers without the need for DTOs and
DAOs. Once you have this example working you’ll find your project can move quickly as you add more
methods to your API and add more domain classes.
Tools we will need
• A database: MySQL
• An IDE: Eclipse
• A build tool: Maven
• A REST client: Chrome
7
Developing Java Applications
Setting up the tools is not within the scope of this article as these topics are covered extensively by other
sources. For simplicity it is best to install each on your local machine.
Setup the project
In Eclipse create a new Java project and setup the package and folder structure as shown in Figure 1.
Figure 1. Project Layout in Eclipse
The pom, web.xml and dispatcher-config.xml are listed below in full.
Listing 1. DiyStore/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/XMLSchemainstance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/
maven-v4_0_0.xsd”>
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>DiyStore</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>DiyStore Maven Webapp</name>
<properties>
<mysql.connector>5.1.25</mysql.connector>
<hibernate.version>4.2.3.Final</hibernate.version>
<spring.version>3.2.3.RELEASE</spring.version>
<spring.data.version>1.3.2.RELEASE</spring.data.version>
<jackson.version>1.9.12</jackson.version>
</properties>
<dependencies>
<!-- DataBase libs -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
8
Developing Java Applications
<version>1.4</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.version}</version>
<exclusions>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- CGLIB is required to process @Configuration classes -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.0</version>
</dependency>
<!-- Other -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- CNVR resources -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
9
Developing Java Applications
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<finalName>DiyStore</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Listing 2. /src/main/webapp/WEB-INF/web.xml
<?xml version=”1.0” encoding=”UTF-8”?>
<web-app xmlns=”http://java.sun.com/xml/ns/javaee” xmlns:web=”http://java.sun.com/xml/
ns/javaee/web-app_2_5.xsd” 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/webapp_3_0.xsd” version=”3.0”>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Listing 3. /src/main/webapp/WEB-INF/spring/dispatcher-config.xml
<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans” xmlns:aop=”http://www.
springframework.org/schema/aop” xmlns:context=”http://www.springframework.org/schema/context”
xmlns:tx=”http://www.springframework.org/schema/tx” xmlns:xsi=”http://www.w3.org/2001/
XMLSchema-instance” xsi:schemaLocation=”
http://www.springframework.org/schema/
beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.
10
Developing Java Applications
springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/
spring-context-2.5.xsd”>
<!-- Say where to find our components -->
<context:component-scan base-package=”com.agilej.example.diy” />
</beans>
Run mvn eclipse:eclipse and refresh the project in Eclipse. This will pull in the dependency libraries and
add them to the Eclipse build path for a clean build in the IDE. The pom declares the full set of dependency
libraries required to make our application DTO-free and DAO-free. Web.xml is a standard for all Spring
MVC applications, essentially telling the web container to chill-out and let Spring handle everything.
Dispatcher-config.xml contains a single vital piece of information which narrows down the search for our
component which we are about to add next.
Create the database
Create a database called “diy” and in that database create a single table as follows:
create table items (
id int(6) NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
make varchar(20) NOT NULL, PRIMARY KEY (id));
In this example we are letting the database look after the generation of unique object ID numbers.
Create the model entity class
Next we need a corresponding Java class. This class will have multiple roles, but it must, nonetheless match
its database table. Create the com.agilej.example.diy.model.Item class. The field names and types of the class
must match the column types in the table.
Note that in this example we show only getter and setter methods. In its full role as a domain class it would
have a richer set of methods which implement the business behaviour and maintain the internal integrity of
the object.
Listing 4. com.agilej.example.diy.model.Item
package com.agilej.example.diy.model;
import
import
import
import
javax.persistence.Entity;
javax.persistence.GeneratedValue;
javax.persistence.Id;
javax.persistence.Table;
@Entity
@Table(name = “items”)
public class Item
{
@Id
@GeneratedValue
private Integer id;
private String name;
private String make;
11
Developing Java Applications
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getMake()
{
return make;
}
public void setMake(String make)
{
this.make = make;
}
}
Create the Spring configuration
We use a Java class to configure Spring which explains the presence of the cglib dependency in the pom.
Create com.agilej.example.diy.init.WebAppConfig as listed below. Note that this configuration class does the
following things for us:
• Sets the hibernate dialect
• Declares the transaction manager
• Locates the database
• Tells the JPA where to look for entity classes
As we are working locally, we are accessing the database by its default credentials. Obviously we would
change these to something stronger before deployment of the finished project.
Listing 5. com.agilej.example.diy.init.WebAppConfig
package com.agilej.example.diy.init;
import java.util.Locale;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.ejb.HibernatePersistence;
12
Developing Java Applications
import
import
import
import
import
import
import
import
import
import
import
import
import
import
org.springframework.context.annotation.Bean;
org.springframework.context.annotation.ComponentScan;
org.springframework.context.annotation.Configuration;
org.springframework.data.jpa.repository.config.EnableJpaRepositories;
org.springframework.jdbc.datasource.DriverManagerDataSource;
org.springframework.orm.jpa.JpaTransactionManager;
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
org.springframework.transaction.annotation.EnableTransactionManagement;
org.springframework.web.accept.ContentNegotiationManager;
org.springframework.web.servlet.View;
org.springframework.web.servlet.ViewResolver;
org.springframework.web.servlet.config.annotation.EnableWebMvc;
org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
org.springframework.web.servlet.view.json.MappingJacksonJsonView;
@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan(“com.agilej.example.diy”)
@EnableJpaRepositories(“com.agilej.example.diy.repository”)
public class WebAppConfig extends WebMvcConfigurerAdapter
{
/** Say how to access the database */
@Bean
public DataSource dataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource
.setDriverClassName(“com.mysql.jdbc.Driver”);
dataSource
.setUrl(“jdbc:mysql://localhost:3306/diy?useUnicode=true&characterEncoding=U
TF-8”);
dataSource.setUsername(“root”);
dataSource.setPassword(“”);
return dataSource;
}
/** Say where to find the entity classes and how to map them to the database */
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new
LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean
.setDataSource(dataSource());
entityManagerFactoryBean
.setPersistenceProviderClass(HibernatePersistence.class);
entityManagerFactoryBean
.setPackagesToScan(“com.agilej.example.diy.model”);
entityManagerFactoryBean
.setJpaProperties(getHibernateProperties());
return entityManagerFactoryBean;
}
private Properties getHibernateProperties()
{
Properties hibernateProperties = new Properties();
hibernateProperties
.put(“hibernate.dialect”,
13
Developing Java Applications
}
“org.hibernate.dialect.MySQL5InnoDBDialect”);
hibernateProperties.put(“hibernate.show_sql”,
“true”);
return hibernateProperties;
/** Provide a transaction manager */
@Bean
public JpaTransactionManager transactionManager()
{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager
.setEntityManagerFactory(entityManagerFactory()
.getObject());
return transactionManager;
}
}
/** Say that entities should be transported as Json */
@Bean
public ViewResolver contentNegotiatingViewResolver(
ContentNegotiationManager manager)
{
return new ViewResolver()
{
public View resolveViewName(String viewName,
Locale locale) throws Exception
{
MappingJacksonJsonView view = new MappingJacksonJsonView();
view.setPrettyPrint(true);
return view;
}
};
}
Create the JPA repository
One of the roles of the entity we created in step 3 is a Data Access Object (DAO) – an in-Java representation
of a row in a database table. Now we need something which lets us perform CRUD interactions with the
database using these entity objects. The something we need is a JPA Repository interface.
@EnableJpaRepositories(“com.agilej.example.musicalinstruments.repository”)
declares where JPA should look for repository interfaces.
in the WebAppConfig class
Listing 6. com.agilej.example.diy.repository.ItemRepository
package com.agilej.example.diy.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.agilej.example.diy.model.Item;
public interface ItemRepository extends JpaRepository<Item, Integer>
{
}
Note that this interface supplies template parameters to its superinterface stating which type of entity this
repository deals with and the type of its primary key. Note also that there are no methods declared on
14
Developing Java Applications
ItemRepository. CRUD operations we get for free. Detailed find operations can be defined by adding additional
methods which follow a naming convention – custom find operations are outside the scope of this article.
Create the service
The service layer is where we worry about the real business logic. A service makes use of entities and
repositories to manipulate the data and orchestrate business-level actions. Create the service interface against
business requirements (will be injected into the controller and only has dependencies to the entity package).
The service layer in our example doesn’t do anything more than forward the call to create on to the repository
layer. Note that this is the service for the DiyStore and not the ItemService. A single service would most likely
contain methods which make use of several repositories and possibly make calls to other services.
Listing 7. com.agilej.example.disy.service.DiyStoreService
package com.agilej.example.diy.service;
import com.agilej.example.diy.model.Item;
public interface DiyStoreService
{
public Item create(Item newItem);
}
Implement the interface
• Add @Service
• Add @Transactional
• Autowire the repository
• Implement the methods
Listing 8. com.agilej.example.disy.service.DiyStoreServiceImpl
package com.agilej.example.diy.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.agilej.example.diy.model.Item;
import com.agilej.example.diy.repository.ItemRepository;
@Service
@Transactional(rollbackFor = Exception.class)
public class DiyStoreServiceImpl implements DiyStoreService
{
@Autowired
private ItemRepository itemRepository;
}
@Override
public Item create(Item newItem)
{
return itemRepository.save(newItem);
}
15
Developing Java Applications
Create the controller
Thanks to Spring MVC a REST API is a simple thing to implement. The controller worries about handling API
calls and farming the requests out to services. The marshalling is handled automatically by Jackson. So now,
at last, we see the entity classes serving as both DAOs and DTOs.
Listing 9. com.agilej.example.diy.controller.DiyStoreController
package com.agilej.example.diy.controller;
import
import
import
import
import
import
import
org.springframework.beans.factory.annotation.Autowired;
org.springframework.http.MediaType;
org.springframework.stereotype.Controller;
org.springframework.web.bind.annotation.RequestBody;
org.springframework.web.bind.annotation.RequestMapping;
org.springframework.web.bind.annotation.RequestMethod;
org.springframework.web.bind.annotation.ResponseBody;
import com.agilej.example.diy.model.Item;
import com.agilej.example.diy.service.DiyStoreService;
@Controller
@RequestMapping(value = “/store”)
public class DiyStoreController
{
@Autowired
private DiyStoreService diyStoreService;
}
@RequestMapping(value = “/create”,
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Item createSmartphone(@RequestBody Item item)
{
return diyStoreService.create(item);
}
Try it out
• Build it on the command line with maven
• Deploy it with the Tomcat manager (found at http://localhost:8080/manager/html)
• Test it with the chrome REST client and check that the response code is 200
• Check that a record is added to the database
16
Developing Java Applications
Figure 2. Testing our web app with the Advanced REST client
Listing 10. Checking the database
mysql> select * from Items;
+----+--------+---------+
| id | name
| make
|
+----+--------+---------+
| 1 | hammer | Stanley |
+----+--------+---------+
1 row in set (0.00 sec)
Conclusions
With this approach we can use the same class for DTO and DAO roles. This conforms to Domain Driven
Design’s use of the same name for the same entity wherever it appears. We have avoided three antipatterns.
Firstly, there is no scope for any mismatch between DAO field names and database table column names.
Secondly, we avoid tedious calling of getters and setters property by property just to convert between DTOs,
domain objects and DAOs. Thirdly, we prevent the anaemic DTO and DAO types from dominating the
architecture resulting in the domain object behaviour tending to get pushed onto the services.
17
Developing Java Applications
Jackson and AOP make the marshalling invisible. The antipattern we avoid is server side code littered with
interpretation of raw Json, which once it takes hold can leak from controller to service layers.
Spring JPA gives us ORM CRUD operations for free, with the DAO layer being wholly declarative.
The antipattern is a bloated DAO layer of boilerplate code in a fat DAO layer whose sole purpose is to
communicate with the database assembling Hibernate Query Language (HQL) and/or SQL. Furthermore,
this trait of dropping query statements into the code can also spread to the service layer.
Of course, it would be too much to expect that in all cases there is a one-to-one mapping between domain
classes, DAOs and DTOs. But a lot of the time there is, and for all those cases the domain classes alone now
have it covered.
On the Web
•
•
•
•
•
•
•
•
https://code.google.com/p/gbif-providertoolkit/wiki/TomcatInstallationMacOSX
http://www.mkyong.com/spring-mvc/spring-mvc-hello-world-example/
http://martinfowler.com/bliki/AnemicDomainModel.html
http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/index.html
http://www.mkyong.com/spring-mvc/spring-3-rest-hello-world-example/
http://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/
https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc
Domain Driven Design, Evans
About the Author
Paul Wells: has 20 years of software engineering experience mainly engaged as a Java consultant across
a wide mix of industries in and around London and Cambridge in the UK. In recent years he has devoted
his attention to developing a UML reverse engineering product called AgileJ which helps programmers
get up to speed with the architecture when joining a new project.
advertisement
Developing Java Applications
Java and Smart Cards
by Soma Ghosh
In today’s world, it is a dire necessity to make any user oriented application to be available
on a smart card or a mobile device. Hence, a need arises for an open, safe, inter-operable
environment to develop and deploy these applications. Java card API has the answer.
What should you know…
• reader should have functional knowledge in Java.
What you will learn…
• how to access a Smart card information from Java application as well as incorporate compact, interoperable and
platform independent utilities inside Smart card.
Smart card is a card with a memory and/or microprocessor chip that contains a self-contained information
and logic. A microprocessor chip can edit information on the card while as a memory chip contains only a
pre-defined operation and information. In all cases, the card operations are self-contained and do not access a
remote database during transaction.
Smart cards fall into the following categories depending on their contents and usages:
Integrated Circuit (IC) Microprocessor Cards
These cards come with a microprocessor to manipulate data in its memory storage. Due to this capability
as well as built-in security, IC Microprocessor cards are used for holding currency, securely accessing a
network and preventing fraud in cellphones.
• Data Capacity: 8Kb
• Microprocessor: 8-bit
IC Memory Cards
These cards do not have a microprocessor, hence depends on a card reader application to perform its task.
IC Memory cards are mainly used as pre-paid phone cards.
• Data Capacity: 1 Kb
• Microprocessor: None.
Optical Memory Cards
• Data Capacity: 4.9 Mb
• Microprocessor: None
How Java adapts to smart card?
While Java Card can leverage most of the benefits of Java technology, e.g. portability, the runtime
environment has to be modified for its execution in smart card environment:
19
Developing Java Applications
Applet Security
In Java standard edition, a basic applet is not allowed to access files and native libraries on the machine for
security purposes. In Java card API, this has to be changed. Java card API allows creation of special applets
that can access native files and resources on the card.
Resource constraint
The Java Virtual Machine and the core libraries have been compacted to work in the resource constraint
environment of Smart cards.
User authentication
Java Card has classes that can manage Smart card features like PINs and passwords.
Firewall
Java Card provides isolation features that allow applications from several vendors to co-exist without
compromising security.
What is Java card API?
The Java Card API provides the necessary classes and libraries as well as the specifications for Java applets to
access native services in a Smart card environment. The Java Card API has two editions – Classic and Connected.
The Classic Edition of the Java Card specification is applicable to all currently deployed Smart cards.
The Connected Edition of the Java Card specification is a step ahead in which Java Card has been extended
to support a Web application model, with servlets running on the card, and TCP/IP as basic protocol.
The Virtual Machine and Runtime Environment in Java Connected Edition support multithreading,
hierarchical class loaders and permissions in order to support a Web application model. The Connected
Edition also runs on high-end secure microcontrollers, typically based on a 32-bit processor and supporting a
high-speed communication interface like USB.
The basics of Java Card applet
In this section, we will discuss how a Java Card applet can be identified, its life cycle and how it
communicates securely with a card reader.
Identifying Java Card Applet
A user readable string identifies a normal Java application whereas a Java applet and package containing the
applet are identified by a sequence of bytes, called Application Identifier (AID.) An AID is 5-16 bytes in length.
The first 5 bytes are called National registered application provider (RID) and assigned by ISO. The remaining
bytes are called Proprietary application identifier extension (PIX), as indicated by the name, are proprietary.
A Java card applet will have the same RID as the containing package while their PIX will differ by the last bit.
Java Applet Execution Framework
A Java Card Applet must extend the javacard.framework.Applet class . This parent class contains methods,
which are called when the Card Reader terminal sends commands to the Java Card Runtime environment
(JCRE). Some of the methods are as below:
20
Developing Java Applications
• install – The method is used to create an instance of the Applet.
• register – This method is used to register the newly created instance of Applet with the JCRE.
• select – This method notifies that the current Applet has been selected.
• process – This method is called to process commands from the Card reader device to JCRE and send back
responses.
• deselect – This method notifies the current Applet that another Applet has been selected.
Java Card Applet Life cycle
The life cycle of a Java card applet can be described as follows (Refer Figure 1):
• An instance of Applet is created.
• The newly created instance is registered with JCRE.
• JCRE get a SELECT Command with AID information.
• If there is a currently active Applet, it is deselected and performs some cleanup functions before
becoming inactive.
• Applet identified by AID is selected.
• It processes all subsequent commands and sends response back.
• Another SELECT Command comes in with a different AID and current Applet is deselected and
becomes inactive.
Figure 1. Life Cycle of a Java Card Applet
21
Developing Java Applications
Request/Response between CAD and JCRE
The communication between the JCRE and the Card Acceptance Device (CAD) is essentially a request and
response type. The request comprises of a series of commands called Command Application Protocol Data
Unit (APDU) whereas the responses are called Response APDU, exchanged alternately between the JCRE
and the CAD. A command APDU contains a Mandatory Header and an optional body.
The Mandatory part consists of:
• Indicator of structure and format of the command and response APDUs.
• Instruction.
• Instruction parameters.
The optional part consists of:
• Size of the data field
• Data field.
• Expected size of the response APDU.
A response APDU consists of an optional data field and a mandatory trailer. The mandatory trailer indicates
a status of the command processing.
Conclusion
In this article, we have learnt how Java Card API helps create platform independent secured applications
for a smart card. Also, we discussed the life cycle of a Java card applet and the interface between Java Card
applet and a Card Reading device. In subsequent articles, we will develop a Java card applet that can act as a
cafeteria card.
A great future lies ahead in Java Card API when the JCRE can be fully integrated with a web application
model, enabling us to access smart card features from the click of a mouse.
About the Author
Soma Ghosh has been working as a Senior Software engineer in various large companies for the
past fifteen years, applying Java Standard and Enterprise editions in Telecommunications, Retail &
Distribution, Workforce and Healthcare domains, thus enhancing and improving customer experience as
well as business process.
22
U P D AT E
NOW WITH
STIG
AUDITING
IN SOME CASES
nipper studio
HAS VIRTUALLY
REMOVED
the
NEED FOR a
MANUAL AUDIT
CISCO SYSTEMS INC.
Titania’s award winning Nipper Studio configuration
auditing tool is helping security consultants and enduser organizations worldwide improve their network
security. Its reports are more detailed than those typically
produced by scanners, enabling you to maintain a higher
level of vulnerability analysis in the intervals between
penetration tests.
Now used in over 45 countries, Nipper Studio provides a
thorough, fast & cost effective way to securely audit over
100 different types of network device. The NSA, FBI, DoD
& U.S. Treasury already use it, so why not try it for free at
www.titania.com
www.titania.com
Fly UP