Tuesday, June 9, 2015

WebService -- SOAP CXF Endpoint Steps without any xml configuration


Intelij Steps :
Go to Project  à New à Maven à create from archtetype  à search for webapp and select maven-archeype-webapp
Give the groupid and artifact id as defined in below pom
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">
    <
parent>
        <
artifactId>test-endpoint</artifactId>
        <
groupId>com.sample.endpoint</groupId>
        <
version>1.0-SNAPSHOT</version>
    </
parent>
    <
modelVersion>4.0.0</modelVersion>

    <
artifactId>test-endpoint-service</artifactId>
    <
properties>
        <
spring.version>4.1.0.RELEASE</spring.version>
        <
spring.security.version>4.0.1.RELEASE</spring.security.version>
        <
hibernate.version>4.3.6.Final</hibernate.version>
        <
cxf.version>3.0.1</cxf.version>
        <
jackson.version>2.4.2</jackson.version>
    </
properties>

    <
dependencies>

        <
dependency>
            <
groupId>${parent.groupId}</groupId>
            <
artifactId>test-endpoint-client</artifactId>
            <
version>1.0-SNAPSHOT</version>
        </
dependency>

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

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




       
<!--CXF -->
       
<dependency>
            <
groupId>org.apache.cxf</groupId>
            <
artifactId>cxf-rt-frontend-jaxws</artifactId>
            <
version>${cxf.version}</version>
        </
dependency>
        <
dependency>
            <
groupId>org.apache.cxf</groupId>
            <
artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <
version>${cxf.version}</version>
        </
dependency>
        <
dependency>
            <
groupId>org.apache.cxf</groupId>
            <
artifactId>cxf-rt-transports-http</artifactId>
            <
version>${cxf.version}</version>
        </
dependency>
        <
dependency>
            <
groupId>org.apache.cxf</groupId>
            <
artifactId>cxf-rt-ws-security</artifactId>
            <
version>3.0.2</version>
        </
dependency>


       
<!-- Jackson Dependencies-->
       
<dependency>
            <
groupId>com.fasterxml.jackson.jaxrs</groupId>
            <
artifactId>jackson-jaxrs-json-provider</artifactId>
            <
version>${jackson.version}</version>
        </
dependency>

        <
dependency>
            <
groupId>com.fasterxml.jackson.core</groupId>
            <
artifactId>jackson-core</artifactId>
            <
version>${jackson.version}</version>
        </
dependency>

        <
dependency>
            <
groupId>com.fasterxml.jackson.core</groupId>
            <
artifactId>jackson-annotations</artifactId>
            <
version>${jackson.version}</version>
        </
dependency>

        <
dependency>
            <
groupId>com.fasterxml.jackson.core</groupId>
            <
artifactId>jackson-databind</artifactId>
            <
version>${jackson.version}</version>
        </
dependency>

        <
dependency>
            <
groupId>com.fasterxml.jackson.datatype</groupId>
            <
artifactId>jackson-datatype-hibernate4</artifactId>
            <
version>${jackson.version}</version>
        </
dependency>

       
<!--Spring -->
       
<dependency>
            <
groupId>org.springframework</groupId>
            <
artifactId>spring-web</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-core</artifactId>
            <
version>${spring.version}</version>
        </
dependency>
        <
dependency>
            <
groupId>org.springframework</groupId>
            <
artifactId>spring-context-support</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-jdbc</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-tx</artifactId>
            <
version>${spring.version}</version>
        </
dependency>
       
<!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-starter-web</artifactId>-->
        <!--<version>1.2.3.RELEASE</version>-->
        <!--</dependency>-->

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

       
<!-- Log4j -->
       
<dependency>
            <
groupId>org.apache.logging.log4j</groupId>
            <
artifactId>log4j-api</artifactId>
            <
version>2.2</version>
        </
dependency>
        <
dependency>
            <
groupId>org.apache.logging.log4j</groupId>
            <
artifactId>log4j-core</artifactId>
            <
version>2.2</version>
        </
dependency>
        <
dependency>
            <
groupId>org.apache.logging.log4j</groupId>
            <
artifactId>log4j-1.2-api</artifactId>
            <
version>2.2</version>
        </
dependency>
        <
dependency>
            <
groupId>org.apache.logging.log4j</groupId>
            <
artifactId>log4j-slf4j-impl</artifactId>
            <
version>2.2</version>
        </
dependency>

       
<!--Test Dependencies -->

       
<dependency>
            <
groupId>org.springframework.data</groupId>
            <
artifactId>spring-data-jpa</artifactId>
            <
version>1.7.0.RELEASE</version>
        </
dependency>
        <
dependency>
            <
groupId>org.springframework</groupId>
            <
artifactId>spring-test</artifactId>
            <
version>3.2.3.RELEASE</version>
            <
scope>test</scope>
        </
dependency>
        <
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>
        <
dependency>
            <
groupId>com.h2database</groupId>
            <
artifactId>h2</artifactId>
            <
version>1.4.182</version>
            <
scope>test</scope>
        </
dependency>
        <
dependency>
            <
groupId>junit</groupId>
            <
artifactId>junit</artifactId>
            <
version>4.11</version>
            <
scope>test</scope>
        </
dependency>
        <
dependency>
            <
groupId>org.mockito</groupId>
            <
artifactId>mockito-all</artifactId>
            <
version>1.9.5</version>
            <
scope>test</scope>
        </
dependency>

    </
dependencies>
    <
build>
        <
plugins>

            <
plugin>
                <
artifactId>maven-war-plugin</artifactId>
                <
configuration>
                    <
archive>
                        <
manifest>
                            <
addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                            <
addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                        </
manifest>
                    </
archive>
                    <
failOnMissingWebXml>false</failOnMissingWebXml>
                </
configuration>
            </
plugin>

            <
plugin>
                <
artifactId>maven-compiler-plugin</artifactId>


            </
plugin>
            <
plugin>
                <
groupId>org.codehaus.mojo</groupId>
                <
artifactId>cobertura-maven-plugin</artifactId>
                <
version>2.6</version>
            </
plugin>


            <
plugin>
                <
groupId>org.eclipse.jetty</groupId>
                <
artifactId>jetty-maven-plugin</artifactId>
                <
version>9.2.0.M1</version>
                <
configuration>
                    <
httpConnector>
                        <
port>8044</port>
                    </
httpConnector>
                    <
webApp>
                        <
contextPath>/${build.finalName}</contextPath>
                    </
webApp>

                   
<!--Configure external jetty config -->
                   
<jettyConfig>${jetty.env}</jettyConfig>
                </
configuration>

                <
dependencies>
                   
<!--You need this if you want to do JSP for the view -->
                   
<dependency>
                        <
groupId>org.eclipse.jetty</groupId>
                        <
artifactId>jetty-jsp</artifactId>
                        <
version>9.2.0.M1</version>
                    </
dependency>

                    <
dependency>
                        <
groupId>com.oracle</groupId>
                        <
artifactId>ojdbc6</artifactId>
                        <
version>11.2.0</version>
                    </
dependency>

                    <
dependency>
                        <
groupId>com.mchange</groupId>
                        <
artifactId>c3p0</artifactId>
                       
<!--0.9.2.1 has a bug that throws an NPE in spring -->
                        
<version>0.9.5-pre8</version>
                    </
dependency>
                </
dependencies>
            </
plugin>



        </
plugins>
    </
build>

</
project>


2.) Create a package – com.sample.endpoint
Create a package context under the above package and following classes under under it - 
               ApplicationConfig, ApplicationInitializer, CxfEndPointConfig
 
//****************************************************************************//
package com.sample.endpoint.context;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.ImportResource;

/**
 * Created by sjain on 6/8/2015.
 */

@ComponentScan(basePackages = {"com.sample.endpoint"})
@EnableAspectJAutoProxy

public class ApplicationConfig {
}
 
 
//****************************************************************************//
 
package com.sample.endpoint.context;

import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
/**
 * Created by sjain on 6/8/2015.
 */
public class ApplicationInitializer implements WebApplicationInitializer {


//    protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
//
//
//        //Init Spring application
//        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
//        rootContext.register(ApplicationConfig.class);
//        servletContext.addListener(new ContextLoaderListener(rootContext));
//
//        //Register Servlets
//        ServletRegistration.Dynamic cxfServlet = servletContext.addServlet("CXFServlet", new CXFServlet());
//        cxfServlet.setLoadOnStartup(1);
//        cxfServlet.addMapping("/*");
//    }



   
public void onStartup(ServletContext servletContext) throws ServletException {
       
//Init Spring application
        
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ApplicationConfig.
class);
        servletContext.addListener(
new ContextLoaderListener(rootContext));

       
//Register Servlets
       
ServletRegistration.Dynamic cxfServlet = servletContext.addServlet("CXFServlet", new CXFServlet());
         cxfServlet.setLoadOnStartup(
1);
        cxfServlet.addMapping(
"/*");
    }
}
 
 
//****************************************************************************//
package com.sample.endpoint.context;

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.sample.endpoint.service.SampleSOAPEndPoint;
import org.apache.cxf.Bus;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
import org.opensaml.xml.encryption.Public;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import javax.xml.ws.Endpoint;

/**
 * Created by sjain on 6/8/2015.
 */

@Configuration
@ImportResource
("classpath:META-INF/cxf/cxf.xml")
public class CxfEndPointConfig {

   
private static String ENDPOINT_PATH_SOAP_ACCOUNTs= "soap/test/account";

   
@Bean
   
public Endpoint jaxwsTestEndPoint(Bus cxfBus,SampleSOAPEndPoint sampleSOAPEndPoint){

        EndpointImpl endpoint =
new EndpointImpl(cxfBus,sampleSOAPEndPoint);
        endpoint.publish(
ENDPOINT_PATH_SOAP_ACCOUNTs);
       
return endpoint;
    }


}


//****************************************************************************//

3.)  Create a package service under above com.sample.endpoint package and class “SampleSOAPendPointImpl” class
//****************************************************************************//


package com.sample.endpoint.service;



import com.sample.endpoint.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by sjain on 6/8/2015.
 */


@WebService(name = "TestAccountDataService", targetNamespace = "http://www.charter.com/test/account")
@Service("testAccountEndpoint")
public class SampleSOAPEndPointImpl implements SampleSOAPEndPoint {


   
@Override
   
public List<Account> getAllAccounts(@WebParam(name = "AccountType") String accountType,@WebParam(name = "AccountId") int accountId) {
        List<Account> accounts =
new ArrayList<Account>();

        Account account =
new Account(1,"savings");
        Account account1 =
new Account(2,"checking");
        Account account2 =
new Account(accountId,accountType);
        accounts.add(account);
        accounts.add(account1);
        accounts.add(account2);

       
return accounts;
}    }

//****************************************************************************//


Steps to Build the project :
1.)      Do a maven clean and maven install
Steps to run the project
You can use jetty webserver to run it , as it is already defined in the pom,
·          select the run debug configuration
·          And select maven from + sign to run the project
·          Browse the working directory of the project
·          Command line write – jetty:run
·          Ok and execute
Now go to browser and run the below urls’

http://localhost:8044/test-endpoint-service-1.0-SNAPSHOT/soap/wss/test/account?wsdl

Wednesday, June 3, 2015

Spring Security Annotations


@Resource :

If you want to use a Spring bean in some other child application or class
you can create a bean with a name and use annotation @Resource to use the defintion

@Bean(name = "user")
Public String HelloWorld(){
String str="Hello;
return str;

}

Now you can use this bean with name user and it would return a String Hello

@Resource(name="user"))
    String str;


Difference between @Qualifier and @Resource

@Autowired can be used alone . If it is used alone , it will be wired by type . So problems arises if more than one bean of the same type are declared in the container as @Autowired does not know which beans to use to inject. As a result , use @Qualifier together with @Autowired to clarify which beans to be actually wired by specifying the bean name (wired by name)
@Resource is wired by name too . So if @Autowired is used together with @Qualifier , it is the same as the @Resource.
The difference are that @Autowired and @Qualifier are the spring annotation while @Resource is the standard java annotation (from JSR-250) . Besides , @Resource only supports for fields and setter injection while @Autowired supports fields , setter ,constructors and multi-argument methods injection.
It is suggested to use @Resource for fields and setter injection. Stick with @Qualifier and@Autowired for constructor or a multi-argument method injection


To externalize Properties
PropertiesFactoryBean -- to store the info from a property file on a classpath/filesystem which has credentials.

PropertyPlaceholderConfigurer --  It pulls values from a properties file into bean definitions.

Friday, May 15, 2015

Srping Security -To integrate Spring Security in a Web Project


Sumary:
Spring Security gives you a feature to intercept any URL authorize and authenticate.
Load a Security configuration to context ,intercept the url through Filter and it shall lead you to a default login page

11.)    Include below dependency to your pom – org.springframework.security and org.springframework.security

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

<
dependency>
    <
groupId>org.springframework.security</groupId>
    <
artifactId> org.springframework.security </artifactId>
    <
version>4.0.1.RELEASE</version>
</
dependency>

22.)    Create a spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"

                           xmlns:beans="http://www.springframework.org/schema/beans"

                           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-4.0.xsd

   http://www.springframework.org/schema/security

   http://www.springframework.org/schema/security/spring-security-4.0.xsd">



<http auto-config="true" use-expressions="true">

    <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />

</http>



<authentication-manager>

    <authentication-provider>

        <user-service>

            <user name="user" password="user" authorities="ROLE_USER" />

        </user-service>

    </authentication-provider>

</authentication-manager>



</beans:bean
 
33.)    Put below Spring Filter to web.xml –
<!-- Spring Security -->

<filter>

   <filter-name>springSecurityFilterChain</filter-name>

   <filter-class>org.springframework.web.filter.DelegatingFilterProxy

   </filter-class>

</filter>



<filter-mapping>

   <filter-name>springSecurityFilterChain</filter-name>

   <url-pattern>/*</url-pattern>

</filter-mapping>


44.)    Import Spring security in the ApplicationContext file 
.
@ImportResource({"/com/sapan/context/spring-security.xml"})  
 
Or  load the context through web.xml

<!-- Loads Spring Security config file -->
        <context-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>
                       /WEB-INF/spring-security.xml
                </param-value>
        </context-param>




http://localhost:8081/ --will lead you to the below default login page, 

Note : you may create yyour own custom login page too
For any Queries write to - jsapan4@gmail.com











Wednesday, May 6, 2015

Unit Testing – ( Junit --( http://junit.org/ ) & Mockito -- (http://site.mockito.org/#why) )

Unit Testing – ( Junit  --(  http://junit.org/  ) & Mockito  -- (http://site.mockito.org/#why) )

JUnit is a framework for writing and running  Unit tests
Mockito allows to create mocks (test doubles) which can replace real collaborators of a class, thus making it possible to implement some test cases.

JUnit and Mockito are often used together. JUnit is used to create the structure of test, while Mockito allow to specify some details of tests within the framework imposed by JUnit. 

I’d be covering an example of Mockito with Junit, (pre-requisite—Junit basics)
Junit Theory:
@Test – Designate a test
@Before/@After – blocks execute before/After
@setup—setup methods executes before a test methods
@tear – executes after test methods

Mockito Theory:
@Mock / mock() – This creates a dummy object , in short mock up an object if you don’t want to fetch any potential value out of it or methods returning null or zero on each call
Ex- Below class will always be mocked
@Repository
public class OrderDao {
    public Order getOrder(int irderId){
        throw new UnsupportedOperationException("Fail is not mocked!");
    }
}
@InjectMocks – Creates an instance
@Spy/ spy() – Used to mock object which fetch some real value
Ex—
@Service
public class PriceService {
    public int getActualPrice(Item item){
        throw new UnsupportedOperationException("Fail is not mocked!");
    }

    public int calculatePriceForOrder(Order order){
        int orderPrice = 0;
        for (Item item : order.getItems()){
            orderPrice += getActualPrice(item);
        }
        return orderPrice;
    }
}


MockitoAnnotations.initMocks(this)) --to initialize annotated fields. Without this call, these objects would be null. Common mistake with this approach is to forget this invocation.
If you have Any Annotated class – like Autowired , above method has to be called otherwise these objects would be null


I'd be covering example in my next blog

for any queries , please contact - jsapan4@gmail.com