Category Archives: Computer/Software Technologies

Using of JsonView with Apache CXF (JAX-RS API implementation).

By using JsonView, we need only one Json data view class for both input and output Json data.And in the output response , we can create dynamic response data
on the basic of type of operation in a method or the role of the user who is calling this method.
JsonView is a feature provided by Jackson library. Jar file which containing this feature is jackson-mapper-asl.jar. Class which should be used for JsonView is
org.codehaus.jackson.map.annotate.JsonView

Below is the maven artifact for downloading this:

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

 

We can use JsonView feature for JAX-RS based web service(REST Web Services).JsonView works with various JAX-RS  implementation like Apache CXF, Jeresy etc.In this article, we will use Apache CXF (version- 2.5.0). Below are the configuration for Apache CXF.

Add below configuration in web.xml :

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/cxf-servlet.xml</param-value>
</context-param>


<servlet>
<servlet-name>CXFServlet</servlet-name>
<display-name>CXF Servlet</display-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>

</servlet>

 

And add below configuration in cxf-servlet.xml file:

<jaxrs:server id="searchservice" address="/api">
<jaxrs:serviceBeans>
<ref bean="searchServiceImpl" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean id="jacksonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"></bean>
</jaxrs:providers>
</jaxrs:server>

 

Controller interface method declaration is annotated with @JsonView (ResultView.class).  In this API, GenericDataView class object will be used for both input and output.In input only two attribute(username and email) will be used.

Below is the controller interface in which API is defined.

@Api(value = "/searchservice", description = "searchservice REST API")
public interface SearchService{

@POST
@Path("/diagnostic_sessions/getSearchResult")
@Produces(MediaType.APPLICATION_JSON)
@JsonView(ResultView.class)
public GenericDataView getSearchResultForJsonView(@Description("Diagnostic Session ID") GenericDataView genericDataView)throws Exception;

}

 

Controller implementation will be:

@Component("searchServiceImpl")
public class SearchServiceImpl implements SearchService {

@Override
public GenericDataView getSearchResultForJsonView(GenericDataView genericDataView) throws Exception {
GenericDataView dataView= new GenericDataView();
dataView.setUsername(genericDataView.getUsername());
dataView.setEmail(genericDataView.getEmail());
dataView.setEmpCode("CTYOP890");
dataView.setAddress("Chicago, America");
dataView.setPhone("681432413");
return dataView;
}

}

}

 

Now lets see how @JsonView works.
Scenario-1: First lets define the type of views for the attributes in View Object.

public class Views {
static class ParamView { }
static class ResultView{ }

}

 

Our Data Model class for View object is:

public class GenericDataView {

@JsonView(ParamView.class)
String username;

@JsonView(ParamView.class)
String email;

@JsonView(ResultView.class)
String empCode;

@JsonView(ResultView.class)
String phone;

@JsonView(ResultView.class)
String address;
}

 

Now lets deploy the above REST API , and send the below json request:

{

"username": "ABCD",
"email": "abcd@xyz.com"

}

 

Output Json response from the above REST API  will be:


{
 "empCode": "CTYOP890",
 "phone": "681432413",
 "address": "Chicago, America"
}

 

In output only empCode,phone,address attributes will be displayed in Json output which are annotated with ResultView(Same view with which above REST API is annotated).

Scenario-2:Lets use below views(ParamView extends ResultView).

public class Views {
static class ParamView { }
static class ResultView extends ParamView { }
}

 

We extends ResultView from ParamView here,So with the same request ,in output all the attributes(annotated with @ParamView and @ResultView will be displayed)


{
 "username": "ABCD",
 "email": "abcd@xyz.com",
 "empCode": "CTYOP890",
 "phone": "681432413",
 "address": "Chicago, America"
}

 

So all the attributes username, email ,empCode,phone,address will be displayed in json output.

That is it about working of @JsonView with JAX-RS API implementation.Still if you face any issue, Please let me know at-  parry.ism@gmail.com

Insert Operations in to Multiple Tables By Using SimpleJdbcInsert Class Of Spring Framework

When we want to insert data in table by using spring framework,We use usually use update() method from JdbcTemplate class.
 

public int insertSystemParameterDetail(String parameterName, String dcCode,
            String value) {
    String insertQuery = "insert into SYSTEM_PARAMETER_DETAIL (PARAMETER_NAME,CODE,VALUE) values(?,?,?)";
    int count = jdbcTemplate.update(insertQuery, new Object[] {
                parameterName, code, value });
        return count;

    }

 

Also we can use SimpleJdbcInsert class from spring for inserting the data in to table.SimpleJdbcInsert is having definitely
better capability then JdbcTemplate class for inserting data in to tables.

public int insertSystemParameterDetail(String parameterName, String dcCode,
String value) {
Map<String, Object> dcMasterMap = new HashMap<>();

dcMasterMap.put("PARAMETER_NAME", parameterName);
dcMasterMap.put("CODE", code);
dcMasterMap.put("VALUE", value);

SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate)
.withTableName("SYSTEM_PARAMETER_DETAIL");
int count = 0;

count = simpleJdbcInsert.execute(dcMasterMap);

return count;
}

Although making a  Java Data Access Object class for every table is a good practice in standard Java based enterprise application,There may be some situation in which you want to insert data in lot of tables and you may like to do less coding.In these situations, using of SimpleJdbcInsert can be a very good option.

 


public class GenericOperationDAOImpl implements GenericOperationDAO {

    private final Logger logger = Logger
            .getLogger(GenericOperationDAOImpl.class);
    private JdbcTemplate jdbcTemplate;

    public int genericInsert(Map<String, Object> genericMap, String tableName) {
        if (logger.isInfoEnabled()) {
            logger.info("Inserting Data into table : " + tableName);
        }
        SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate)
                .withTableName(tableName);
        int count = 0;

        count = simpleJdbcInsert.execute(genericMap);

        return count;

    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

}

 

 


public class GenericDBOperationalAPIImpl implements GenericDBOperationalAPI {

private final Logger logger = Logger.getLogger(GenericDBOperationalAPIImpl.class);

GenericOperationDAO genericOperationDAO;

public int genericInsert(Map<String, Object> genericMap,String tableName) {

if (logger.isInfoEnabled()) {
logger.info("Starting Insertion of Data into table : " + tableName);
}

genericOperationDAO.genericInsert(GenericMapUtils.getCarrierMap("1", "WL-ST"), "CARRIER");
genericOperationDAO.genericInsert(GenericMapUtils.getMasterMap("ABC", "UTC", "1", "Unregistered"),"MASTER");
genericOperationDAO.genericInsert(GenericMapUtils.getAttributeMap("DDS", "ABC"),"ATTRIBUTE");
genericOperationDAO.genericInsert(GenericMapUtils.getDeliveryAreaCodeMap("DAC"), "DELIVERY_AREA_CODE");

}

public void setGenericOperationDAO(GenericOperationDAO genericOperationDAO) {
                 this.genericOperationDAO = genericOperationDAO;
}

}

 

 

public class GenericMapUtils {

    public static final Map<String, Object> getCarrierMap(String proNumber,
            String carrierId) {
        Map<String, Object> carrierMap = new HashMap<>();

        carrierMap.put("PRO_NUMBER", proNumber);
        carrierMap.put("CARRIER_ID", carrierId);
        return carrierMap;
    }

    public static final Map<String, Object> getMasterMap(String code,
            String timeZone, String defaultSystemFlag, String description) {
        Map<String, Object> masterMap = new HashMap<>();

        masterMap.put("CODE",code);
        masterMap.put("TIMEZONE", timeZone);
        masterMap.put("DEFAULT_SYSTEM_FLAG", defaultSystemFlag);
        masterMap.put("DESCRIPTION", description);

        return masterMap;

    }

    public static final Map<String, Object> getAttributeMap(
            String attributeName, String code) {

        Map<String, Object> attributeMap = new HashMap<>();

        attributeMap.put("ATTRIBUTE_NAME", attributeName);
        attributeMap.put("CODE", code);
        attributeMap.put("ATTRIBUTE_TYPE", "attT");
        attributeMap.put("ATTRIBUTE_ID", 32);
        return attributeMap;
    }

    
    public static final Map<String, Object> getDeliveryAreaCodeMap(
            String deliveryArea) {

        Map<String, Object> deliveryAreaCodeMap = new HashMap<>();

        deliveryAreaCodeMap.put("DELIVERY_AREA_CODE", deliveryAreaCode);

        return deliveryAreaCodeMap;
    }
}

 

and spring xml configuration is:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/oxm
     http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="genericDBOperationalAPI" class="com.svg.move.api.GenericDBOperationalAPIImpl">
<property name="genericOperationDAO" ref="genericOperationDAO" />
</bean>

<bean id="genericOperationDAO" class="com.svg.move.dao.GenericOperationDAOImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:Oracle" />
<property name="username" value="abc" />
<property name="password" value="abc" />
</bean>

</beans>

That is it,So by using SimpleJdbcInsert we can insert in to multiple tables with less and clean coding.This approach is very useful as well in writing junits which involves multiple tables insertion.

JdbcTemplate deprecated method queryForLong() and queryForInt() in Spring 4 and in spring 3.2.x

 sunflower   Since the jdbcTemplate.queryForInt() and jdbcTemplate.queryForLong() are deprecated in new version of spring(i think,After3.2.x,they are deprecated).We will have to use  jdbcTemplate.queryForObject() for the purpose .We should take care following coding practice otherwise  unwanted exceptions can come.

1.When we will use jdbcTemplate.queryForInt() for getting some int value in a query like:

Existing use of queryForInt() for getting int value:

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
int value = jdbcTemplate.queryForInt(sql, new Object[] {orderId, orderType});

return value
}

Or

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
return jdbcTemplate.queryForInt(sql, new Object[] {orderId, orderType});

}

 

Now because queryForInt() is deprecated,we will use queryForObject() for getting int value:

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
int value = jdbcTemplate.queryForObject(sql, new Object[] {orderId, orderType }, Integer.class);

return value
}

Or

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
return jdbcTemplate.queryForObject(sql, new Object[] {orderId, orderType }, Integer.class);

}

Now in the above code, if queryForObject return null value.It can not be assigned to primitive type int value .

So null pointer exception will come.To handle this , we should change our method like:

 

public int getLineNumber(String orderId, String orderType) {
String sql = "SELECT MAX(order_line_no) FROM ORDER WHERE order_id = ? and order_type = ?";
Integer value = jdbcTemplate.queryForObject(sql, new Object[] {orderId, orderType }, Integer.class);

return ((value == null) ? 0 : value.intValue());
}

This will ensure no exception if null is returned in the query.Similar changes can be applied to get an long value.

Quartz 2 (2.2.1) Scheduler integration with Spring 4 (4.0.5.RELEASE) and Maven build tool.

Coffe_Cup     Assumption is that you are having a maven project.Let divide whole task (Quartz 2.2.1 integration with Spring 4.0.5.RELEASE) in to 4 step process 

1. Add Spring 4.0.5.RELEASE and quartz 2.2.1 dependency in pom.xml file:
2.Creating a task class(in which our method is present which we want to schedule to run periodically)
3.Creating a job class(this will initiate task class and call the method in it)
4.Configuration in spring xml file(spring-quartz.xml)


 

1. Add Spring 4.0.5.RELEASE and quartz 2.2.1 dependency in pom.xml file:
 
<properties>
<spring.version>4.0.5.RELEASE</spring.version>
</properties>

<!-- Spring dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</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-context-support</artifactId>
<version>${spring.version}</version>
</dependency>

And quartz dependency are:

<!-- Quartz framework -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>

 
Download above dependency in your ..../username/.m2/respository/* location by running mvn eclipse:eclipse or mvn install.
2.Creating a task class(in which our method is present which we want to schedule to run periodically)mentioned below:
package com.devil.space.quartz;

import java.util.List;
import org.apache.log4j.Logger;
import com.devil.space.exception.WebServiceUploadException;
import com.devil.space.model.Transaction;
import com.devil.space.service.TransactionProcessService;
import com.devil.space.xmlservice.XMLUploadService;

/*****************************************************************************
* Class used for processing<code>Transaction</code> records for
xml uploading.
*
*
******************************************************************************
public class TransactionRecordsProcessTask {
Logger logger = Logger.getLogger(TransactionRecordsProcessTask.class);
private XMLUploadService xmlUploadService;
private TransactionProcessService transactionProcessService;

public void processRecords() {

if (logger.isInfoEnabled()) {
logger.info("In TransactionRecordsProcessTask.Transaction records processing started");
}

try {
List<Transaction> transactionRecordForXMLUpload = transactionProcessService
.processTransactionRecords();

for (Transaction transaction : transactionRecordForXMLUpload) {
xmlUploadService.uploadTransactionRecord(transaction);
}
} catch (XMLUploadException e) {
logger.warn("error processing TransactionRecordsQuartzJob", e);
} catch (Throwable t) {
logger.warn("uncatchable error:", t);
}
}

public XMLUploadService getXmlUploadService() {
return xmlUploadService;
}

public void setXmlUploadService(XMLUploadService xmlUploadService) {
this.xmlUploadService = xmlUploadService;
}

public TransactionProcessService getTransactionProcessService() {
return transactionProcessService;
}

public void setTransactionProcessService(TransactionProcessService transactionProcessService) {
this.transactionProcessService = transactionProcessService;
}

}

 

3. Creating a job class(this will initiate task class and call the method in it)

 

package com.devil.space.quartz;

import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class TransactionRecordsQuartzJob extends QuartzJobBean {
Logger logger = Logger.getLogger(TransactionRecordsQuartzJob.class);
TransactionRecordsProcessTask transactionRecordsProcessTask;

public void executeInternal(JobExecutionContext context)
throws JobExecutionException {
if (logger.isInfoEnabled()) {
logger.info("In TransactionRecordsQuartzJob - executing its JOB on "
+ new Date()
+ " by "
+ context.getTrigger().getDescription());
}

transactionRecordsProcessTask.processRecords();
}

public TransactionRecordsProcessTask getTransactionRecordsProcessTask() {
return transactionRecordsProcessTask;
}

public void setTransactionRecordsProcessTask(TransactionRecordsProcessTask transactionRecordsProcessTask) {
this.transactionRecordsProcessTask = transactionRecordsProcessTask;
}

}

 

4.Configuration in spring xml file(spring-quartz.xml) Create a xml file for spring-quartz configuration and put down the below content in it.

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
>

<!-- Simple Trigger, run every 5 seconds -->
<bean id="simpleTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">

<property name="jobDetail" ref="transactionRecordJob" />
<property name="repeatInterval" value="5000" />
<property name="startDelay" value="1000" />

</bean>

<bean id="transactionRecordJob"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="transactionRecordsProcessTask" />
<property name="targetMethod" value="processRecords" />
</bean>

<bean id="transactionRecordsProcessTask" class="com.devil.space.quartz.TransactionRecordsProcessTask">
<property name="xmlUploadService" ref="xmlUploadService" />
<property name="transactionProcessService" ref="transactionProcessService" />

</bean>

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="autoStartup" value="true" />
<property name="jobDetails">
<list>
<ref bean="transactionRecordJob" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="simpleTrigger" />
</list>
</property>

</bean>

<bean id="xmlUploadService" class="com.devil.space.xmlservice.XMLUploadServiceImpl">
</bean>

<bean id="transactionProcessService" class="com.devil.space.service.TransactionProcessServiceImpl">
</bean>

</beans>

 

That is it.Now create a war file of the project by mvn install and deploy the application in a application server (Say apache-tomcat-7.0.29).Quartz will start working as expected.


					

How to install Weblogic 12C Server Instance as an window service on Window7

m1975414Its very important sometimes to set up a software application as an window service on Window Platform.Window service enable  a software application to start working

as soon as Machine is turned on so that no manual or human interaction is required to start that application whenever machine is turned on.In this article i will show how

to install weblogic 12 c server as an window service on  Window 7 platform.After installing weblogic 12c server on the machine,Perform the following steps to make it as

an window service.

(1.)  After installing the web logic 12c  server ,Its installation directory will be in C drive. Path will be like C:\Oracle\Middleware .Its Tree structure would be like:

windowService1

(2.) Go to the C:\Oracle\Middleware\wlserver_12.1\server\bin.Create a file createSvc.cmd.Add the below content in this file:

echo off

SETLOCAL

set DOMAIN_NAME=base_domain

set USERDOMAIN_HOME=C:\Oracle\Middleware\user_projects\domains\base_domain

set SERVER_NAME=AdminServer

set PRODUCTION_MODE=true

set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_09

set JRE_HOME=C:\Program Files\Java\jre7

set HOST=127.0.0.1

set PORT=7001

 

set

_JAVA_OPTIONS=-Dweblogic.Stdout=”C:\Oracle\Middleware\user_projects\domains\base_domain_

_stdout.txt” -Dweblogic.Stderr=”C:\Oracle\Middleware\user_projects\domains\base_domain_

stderr.txt”

set JAVA_VENDOR=”sun”

set JAVA_VM=-server

set MEM_ARGS=-Xms512m -Xmx1024m -XX:MaxPermSize=512m

call “C:\Oracle\Middleware\wlserver_12.1\server\bin\installSvc.cmd”

ENDLOCAL

Details of the above script is:

SETLOCAL :-This is a batch command that begins the localization of environment variables in a batch file.

DOMAIN_NAME=domain-name

where domain-name is the name of your WebLogic Server domain.

USERDOMAIN_HOME=absolute-pathname

where absolute-pathname is the absolute pathname of the Administration Server’s root directory (the directory that contains the domain’s configuration file).

SERVER_NAME=server-name

where server-name is the name of an existing server instance that you want set up as a Windows service.

PRODUCTION_MODE=[true]

When the PRODUCTION_MODE variable is set to true, the server instance starts in production mode.

JAVA_HOME  – Location of the version of Java used to start WebLogic Server. This variable must point to the root directory of a   JDK installation and will be set for you by the installer.

JRE_HOME—Location of system java run time environment

HOST – IP address of the Weblogic Server.

PORT – Port number where the WebLogic Server is listening for requests.

JAVA_OPTIONS – Java command-line options for running the server. (These  will be tagged on to the end of the JAVA_VM and MEM_ARGS).

JAVA_VENDOR– Java vendor name which is used for running weblogic server.

JAVA_VM   – The java arg specifying the VM to run.  (i.e. -server,  -client, etc.).

MEM_ARGS  – The variable to override the standard memory arguments passed to java

(3.)  Add the WebLogic server bin directory (C:\Oracle\Middleware\wlserver_12.1\server\bin)to the system path variable (PATH).

(4.)  Execute createSvc.cmd script from same folder C:\Oracle\Middleware\wlserver_12.1\server\bin

(5.) This should create service with name of ” wlsvc base_domain_AdminServer ” in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Servicesas below:

windowService2

(6.) Right Click on Computer and then click on manage.Now go to Services and Applications->Services. “wlsvc base_domain_AdminServer service” is listed there as shown below:

windowService3

Now start the service by clicking on start button.

How to remove server instance as a windows service:

(1.) Create a script called removeSvc.cmd and copy the following lines. Make sure adminServer name and domain name values are correctly set. And execute from the same place

(C:\Oracle\Middleware\wlserver_12.1\server\bin) where you created window service before.

echo off

SETLOCAL

set DOMAIN_NAME=base_domain

set SERVER_NAME=AdminServer

call “C:\Oracle\Middleware\wlserver_12.1\server\bin\uninstallSvc.cmd”

ENDLOCAL

How to debug the Window Service:

If there are some issue in running this window service.We can debug it as well.

Go to theC:\Oracle\Middleware\wlserver_12.1\server\bin directory and run below command:

wlsvc   –debug  “wlsvc base_domain_AdminServer

(Reference:http://docs.oracle.com)