Java[jdk] download, installation and setting path

Java+download+install+setting+path...

Click here to download java installation document



Regular expressions java

Regular+expressions+java...

Java supports regular expressions through the classes in the java.util.regex package in the standard Java library. While there are some differences in advanced features supported by the Java regular expression library compared to PCRE, they both share a large part of the syntax and patterns and expressions can be used in Java and other languages.

In the examples below, be sure to import the following package at the top of the source file if you are trying out the code:

import java.util.regex.*;

Regular expression String patterns

In Java, regular strings can contain special characters (also known as escape sequences) which are characters that are preceeded by a backslash ( \ ) and identify a special piece of text like a newline ( \n ) or a tab character ( \t ). As a result, when writing regular expressions in Java code, you need to escape the backslash in each metacharacter to let the compiler know that it's not an errant escape sequence.

For example, take the pattern "There are \d dogs" . In Java, you would escape the backslash of the digit metacharacter by using the escape sequence \\ (effectively escaping the backslash with itself) to create the pattern "There are \\d dogs" .

This is only necessary when hard-coding patterns into Java code, as strings that are read in from user input or from files are read by character individually and escape sequences are not interpreted. This is a common approach to get around this problem, by either putting the patterns in a Properties or resource file so they can be easier to read and understand.

Other languages like C# or Python support the notion of raw strings, but Java has yet to add this useful feature into the core language.

Matching a string

Working with regular expressions in Java generally involves instantiating a Pattern, and matching it against some text. The simplest way to do this is to call the static method Pattern.matches(), which takes an input string and the regular expression to match it against, and simply returns whether the pattern matches the string.  

Method
boolean isMatch = Pattern.matches(String regex, String inputStr)

However, this does not give you any additional information such as where in the input string the pattern matches, or the groups that matched. So for most purposes, it is both more useful and also more efficient to compile a new Pattern and then use it to create a new Matcher for each input string that you are matching against, which will hold the results of the match.

Methods
Pattern ptrn = Pattern.compile(String regex) Matcher matcher = ptrn.matcher(String inputStr)
Example
// Lets use a regular expression to match a date string. Pattern ptrn = Pattern.compile("([a-zA-Z]+) (\\d+)"); Matcher matcher = ptrn.matcher("June 24"); if (matcher.matches()) { // Indeed, the expression "([a-zA-Z]+) (\d+)" matches the date string // To get the indices of the match, you can read the Matcher object's // start and end values. // This will print [0, 7], since it matches at the beginning and end of the // string System.out.println("Match at index [" + matcher.start() + ", " + matcher.end() + ")"); // To get the fully matched text, you can read the Matcher object's group // This will print "June 24" System.out.println("Match: " + matcher.group()); }

Capturing groups

Capturing groups in a regular expression is as straightforward as matching a string in the example above. After using a Pattern to match an input string, you can just iterate through the extracted groups in the returned Matcher .

Example
// Lets use a regular expression to capture data from a few date strings. String pattern = "([a-zA-Z]+) (\\d+)"; Pattern ptrn = Pattern.compile("([a-zA-Z]+) (\\d+)"); Matcher matcher = ptrn.matcher("June 24, August 9, Dec 12"); // This will print each of the matches and the index in the input string // where the match was found: // June 24 at index [0, 7) // August 9 at index [9, 17) // Dec 12 at index [19, 25) while (matcher.find()) { System.out.println(String.format("Match: %s at index [%d, %d]", matcher.group(), matcher.start(), matcher.end())); } // If we are iterating over the groups in the match again, first reset the // matcher to start at the beginning of the input string. matcher.reset(); // For each match, we can extract the captured information by reading the // captured groups. while (matcher.find()) { // This will print the number of captured groups in this match System.out.println(String.format("%d groups captured", matcher.groupCount())); // This will print the month and day of each match. Remember that the // first group is always the whole matched text, so the month starts at // index 1 instead. System.out.println("Month: " + matcher.group(1) + ", Day: " + matcher.group(2)); // Each group in the match also has a start and end index, which is the // index in the input string that the group was found. System.out.println(String.format("Month found at[%d, %d)", matcher.start(1), matcher.end(1))); }

Finding and replacing strings

Another common task is to find and replace a part of a string using regular expressions, for example, to replace all instances of an old email domain, or to swap the order of some text. You can do this in Java with the Matcher.replaceAll() and Matcher.replaceFirst() methods. Both these methods first reset the matcher to start at the beginning of the input string up to either the end of the string, or the end of the first match respectively.

The replacement string can contain references to captured groups in the pattern (using the dollar sign $), or just a regular literal string.

Method
String replacedString = matcher.replaceAll(String inputStr)
String replacedString = matcher.replaceFirst(String inputStr)
Example
// Lets try and reverse the order of the day and month in a few date // strings. Notice how the replacement string also contains metacharacters // (the back references to the captured groups) so we use a verbatim // string for that as well. Pattern ptrn = Pattern.compile("([a-zA-Z]+) (\\d+)"); Matcher matcher = ptrn.matcher("June 24, August 9, Dec 12"); // This will reorder the string inline and print: // 24 of June, 9 of August, 12 of Dec // Remember that the first group is always the full matched text, so the // month and day indices start from 1 instead of zero. String replacedString = matcher.replaceAll("$2 of $1"); System.out.println(replacedString);

Pattern Flags

When compiling a Pattern , you will notice that you can pass in additional flags to change how input strings are matched. Most of the available flags are a convenience and can be written into the into the regular expression itself directly, but some can be useful in certain cases.

  • Pattern.CASE_INSENSITIVE makes the pattern case insensitive so that it matches strings of different capitalizations
  • Pattern.MULTILINE is necessary if your input string has newline characters (\n) and allows the start and end metacharacter (^ and $ respectively) to match at the beginning and end of each line instead of at the beginning and end of the whole input string
  • Pattern.DOTALL allows the dot metacharacter (.) to match new line characters as well
  • Pattern.LITERAL makes the pattern literal, in the sense that the escaped characters are matched as-is. For example, the pattern "\d" will match a backslash followed by a 'd' character as opposed to a digit character

Links

For more information about using regular expressions in Java, please visit the following links:

JAX WS Spring Integration Example

JAX+WS+Spring+Integration+Example ...

Click here to download eclipse supported ZIP file



This is index.jsp JSP file and it is used display the output for the application.




<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<head>
</head>
<body>
<table align='center'>
<tr>
<td>Hello world example...</td>

</tr>
<tr>
<td><a href="./hello">click here</a></td>
</tr>
</table>
</body>


This is HelloWorldBo.java file having the source code to execute business logic.



 

    
package com.cv.webservice.bo;

public interface HelloWorldBo{

  String getHelloWorld();
  
}


This is HelloWorldBoImpl.java file having the source code to execute business logic.



 

    
package com.cv.webservice.bo.impl;

import com.cv.webservice.bo.HelloWorldBo;

public class HelloWorldBoImpl implements HelloWorldBo{

  public String getHelloWorld(){
    return "JAX-WS + Spring!";
  }
  
}


This is HelloWorldWS.java file having the source code to execute business logic.



 

    
package com.cv.webservice;

import javax.jws.WebMethod;
import javax.jws.WebService;

import com.cv.webservice.bo.HelloWorldBo;

@WebService
public class HelloWorldWS{

  //DI via Spring
  HelloWorldBo helloWorldBo;

  @WebMethod(exclude=true)
  public void setHelloWorldBo(HelloWorldBo helloWorldBo) {
    this.helloWorldBo = helloWorldBo;
  }

  @WebMethod(operationName="getHelloWorld")
  public String getHelloWorld() {
    
    return helloWorldBo.getHelloWorld();
    
  }
 
}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<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">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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mkyong.common</groupId> <artifactId>JAXWSSpringIntegrationExample</artifactId> <packaging>war</packaging> <version>1.0</version> <name>JAXWSSpringIntegrationExample Maven Webapp</name> <url>http://maven.apache.org</url> <repositories> <repository> <id>java.net</id> <url>http://download.java.net/maven/2</url> </repository> </repositories> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> </dependency> <dependency> <groupId>com.sun.xml.ws</groupId> <artifactId>jaxws-rt</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>org.jvnet.jax-ws-commons.spring</groupId> <artifactId>jaxws-spring</artifactId> <version>1.8</version> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <groupId>com.sun.xml.stream.buffer</groupId> <artifactId>streambuffer</artifactId> <groupId>org.jvnet.staxex</groupId> <artifactId>stax-ex</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>JAXWSSpringIntegrationExample</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>JAXWSSpringIntegrationExample</finalName> </build> </project>


This is applicationContext.xml spring configuration file and these entries are used in the application.



 
<?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:ws="http://jax-ws.dev.java.net/spring/core"
xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://jax-ws.dev.java.net/spring/core
http://jax-ws.dev.java.net/spring/core.xsd
http://jax-ws.dev.java.net/spring/servlet
http://jax-ws.dev.java.net/spring/servlet.xsd">

<wss:binding url="/hello">
<wss:service>
<ws:service bean="#helloWs" />
</wss:service>
</wss:binding>

<!-- Web service methods -->
<bean id="helloWs" class="com.cv.webservice.HelloWorldWS">
<property name="helloWorldBo" ref="HelloWorldBo" />
</bean>

<bean id="HelloWorldBo" class="com.cv.webservice.bo.impl.HelloWorldBoImpl" />

</beans>


This is web.xml deployment descriptor file and it describes how the web application should be deployed.



	
<web-app id="WebApp_ID" version="2.4" 
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring + JAX-WS</display-name>

<servlet>
<servlet-name>jaxws-servlet</servlet-name>
<servlet-class>
com.sun.xml.ws.transport.http.servlet.WSSpringServlet
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>jaxws-servlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

<!-- Register Spring Listener -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

</web-app>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

JAX WS security deploy tomcat example

Click here to download eclipse supported ZIP file



This is input.properties properties file and these properties are used in the application.




portNumber=9090




This is index.jsp JSP file and it is used display the output for the application.




<jsp:forward page="/initServlet"></jsp:forward>


This is InitServlet.java file having the source code to execute business logic.



 

    
package com.cv.servlet.init;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class InitServlet
 
 @author Chandra Vardhan
 *
 */

public class InitServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(InitServlet.class);

  private static final long serialVersionUID = 1L;

  /**
   @see HttpServlet#HttpServlet()
   */
  public InitServlet() {
    super();

  }

  /**
   @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doGet(--) of InitServlet class... ");

    response.setContentType("text/html");

    String contextPath = this.getClass().getClassLoader().getResource("/").getPath();
  
    if(contextPath != null) {
      contextPath = contextPath.substring(0, contextPath.lastIndexOf(".metadata")-1);
      if(contextPath.startsWith("\\")) {
        contextPath = contextPath.substring(1, contextPath.length());
      }
      contextPath = contextPath+request.getContextPath();
    }
    
    File file = new File(contextPath+"//input.properties");
    if (file != null && !file.exists()) {
      file.createNewFile();
    }
    LOGGER.info("created at :: "+file.getAbsolutePath());
    final PrintWriter pw = new PrintWriter(new FileOutputStream(file));
    pw.print("portNumber=" + request.getServerPort());
    PrintWriter out = response.getWriter();
    out.print("Successfully deployed...");
    pw.close();
    out.close();
  }

  /**
   @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {
    LOGGER.info("Entered into doPost(--) of InitServlet class... ");
    doGet(request, response);
  }

}


This is WsClient.java file having the source code to execute business logic.



 

    
package com.cv.webservice.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import org.apache.log4j.Logger;

import com.cv.webservice.ws.HelloWorld;

public class WsClient {
  
  private static final Logger LOGGER = Logger
      .getLogger(WsClient.class);
  private static String WS_URL = "/JAXWSSecurityDeployTomcat/hello?wsdl";

  static {
    Properties properties = readFile();
    setValues(properties);
  }

  private static void setValues(Properties properties) {

    if (properties != null) {
      String port = properties.getProperty("portNumber");
      WS_URL = "http://localhost:" + port + WS_URL;
    }
  }

  private static Properties readFile() {

    File file = new File(System.getProperty("user.dir")
        "/input.properties");
    Properties prop = new Properties();
    if (file != null && file.exists()) {
      InputStream input = null;
      try {
        input = new FileInputStream(file);
        // load a properties file
        prop.load(input);
      catch (Exception e) {
        e.printStackTrace();
      }
    else {
      prop.setProperty("portNumber""8080");
    }
    return prop;
  }

  public static void main(String[] argsthrows Exception {

    URL url = new URL(WS_URL);

    QName qname = new QName("http://ws.webservice.cv.com/",
        "HelloWorldImplService");

    Service service = Service.create(url, qname);

    HelloWorld hello = service.getPort(HelloWorld.class);

    LOGGER.info(hello.getHelloWorldAsString());

  }

}


This is WsPublisher.java file having the source code to execute business logic.



 

    
package com.cv.webservice.endpoint;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import javax.xml.ws.Endpoint;

import org.apache.log4j.Logger;

import com.cv.webservice.ws.HelloWorldImpl;

//Endpoint publisher
public class WsPublisher {
  private static final Logger LOGGER = Logger.getLogger(WsPublisher.class);
  private static String WS_URL = "/JAXWSSecurityDeployTomcat/hello";

  static {
    Properties properties = readFile();
    setValues(properties);
  }

  public static void main(String[] args) {

    Endpoint.publish(WS_URL, new HelloWorldImpl());
    LOGGER.info("Server is URL is : : " + WS_URL);
    LOGGER.info("Server is published!");

  }

  private static void setValues(Properties properties) {

    if (properties != null) {
      String port = properties.getProperty("portNumber");
      WS_URL = "http://localhost:" + port + WS_URL;
    }
  }

  private static Properties readFile() {

    File file = new File(System.getProperty("user.dir")
        "/input.properties");
    Properties prop = new Properties();
    if (file != null && file.exists()) {
      InputStream input = null;
      try {
        input = new FileInputStream(file);
        // load a properties file
        prop.load(input);
      catch (Exception e) {
        e.printStackTrace();
      }
    else {
      prop.setProperty("portNumber""8080");
    }
    return prop;
  }

}


This is HelloWorld.java file having the source code to execute business logic.



 

    
package com.cv.webservice.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld {

  @WebMethod
  String getHelloWorldAsString();

}




This is HelloWorldImpl.java file having the source code to execute business logic.



 

    
package com.cv.webservice.ws;

import javax.jws.WebService;

//Service Implementation Bean

@WebService(endpointInterface = "com.cv.webservice.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld {

  public String getHelloWorldAsString() {
    return "Hello World JAX-WS";
  }
}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<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">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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.webservice</groupId> <artifactId>JAXWSSecurityDeployTomcat</artifactId> <packaging>war</packaging> <version>1.0</version> <name>JAXWSContainerAuthentication Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> </dependency> <dependency> <groupId>com.sun.xml.ws</groupId> <artifactId>jaxws-rt</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>org.jvnet.jax-ws-commons.spring</groupId> <artifactId>jaxws-spring</artifactId> <version>1.8</version> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <groupId>com.sun.xml.stream.buffer</groupId> <artifactId>streambuffer</artifactId> <groupId>org.jvnet.staxex</groupId> <artifactId>stax-ex</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>JAXWSSecurityDeployTomcat</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>JAXWSSecurityDeployTomcat</finalName> </build> </project>


This is sun-jaxws.xml spring configuration file and these entries are used in the application.



 
<?xml version="1.0" encoding="UTF-8"?>
<endpoints
xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint
name="HelloWorld"
implementation="com.cv.webservice.ws.HelloWorldImpl"
url-pattern="/hello"/>
</endpoints>


This is web.xml deployment descriptor file and it describes how the web application should be deployed.



	
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>com.cv.servlet.init.InitServlet</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>initServlet</servlet-name>
<url-pattern>/initServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Jax WS RPC style example

Click here to download eclipse supported ZIP file



This is index.jsp JSP file and it is used display the output for the application.




<jsp:forward page="/initServlet"></jsp:forward>


This is InitServlet.java file having the source code to execute business logic.



 

    
package com.cv.servlet.init;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class InitServlet
 
 @author Chandra Vardhan
 *
 */

public class InitServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(InitServlet.class);

  private static final long serialVersionUID = 1L;

  /**
   @see HttpServlet#HttpServlet()
   */
  public InitServlet() {
    super();

  }

  /**
   @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doGet(--) of InitServlet class... ");

    response.setContentType("text/html");

    String contextPath = this.getClass().getClassLoader().getResource("/").getPath();
  
    if(contextPath != null) {
      contextPath = contextPath.substring(0, contextPath.lastIndexOf(".metadata")-1);
      if(contextPath.startsWith("\\")) {
        contextPath = contextPath.substring(1, contextPath.length());
      }
      contextPath = contextPath+request.getContextPath();
    }
    
    File file = new File(contextPath+"//input.properties");
    if (file != null && !file.exists()) {
      file.createNewFile();
    }
    LOGGER.info("created at :: "+file.getAbsolutePath());
    final PrintWriter pw = new PrintWriter(new FileOutputStream(file));
    pw.print("portNumber=" + request.getServerPort());
    PrintWriter out = response.getWriter();
    out.print("Successfully deployed...");
    pw.close();
    out.close();
  }

  /**
   @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {
    LOGGER.info("Entered into doPost(--) of InitServlet class... ");
    doGet(request, response);
  }

}


This is HelloWorldClient.java file having the source code to execute business logic.



 

    
package com.cv.webservice.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import org.apache.log4j.Logger;

import com.cv.webservice.HelloWorld;


/**
 @author Chandra Vardhan
 *
 */
public class HelloWorldClient {
  private static final Logger LOGGER = Logger
      .getLogger(HelloWorldClient.class);

  private static String WS_URL = "/JaxWSRPCStyle/hello?wsdl";

  static {
    Properties properties = readFile();
    setValues(properties);
  }

  private static void setValues(Properties properties) {

    if (properties != null) {
      String port = properties.getProperty("portNumber");
      WS_URL = "http://localhost:" + port + WS_URL;
    }
  }

  private static Properties readFile() {

    File file = new File(System.getProperty("user.dir")
        "/input.properties");
    Properties prop = new Properties();
    if (file != null && file.exists()) {
      InputStream input = null;
      try {
        input = new FileInputStream(file);
        // load a properties file
        prop.load(input);
      catch (Exception e) {
        e.printStackTrace();
      }
    else {
      prop.setProperty("portNumber""8080");
    }
    return prop;
  }

  public static void main(String[] argsthrows Exception {

    URL url = new URL(WS_URL);

    // 1st argument service URI, refer to wsdl document above
    // 2nd argument is service name, refer to wsdl document above
    QName qname = new QName("http://webservice.cv.com/",
        "HelloWorldImplService");
    Service service = Service.create(url, qname);
    HelloWorld hello = service.getPort(HelloWorld.class);
    System.out.println(hello
        .getHelloWorldAsString("Web services RPC Example..."));
    LOGGER.info(hello
        .getHelloWorldAsString("Entered in HelloWorldImpl.getHelloWorldAsString(String)"));
  }
}


This is HelloWorldClient2.java file having the source code to execute business logic.



 

    
/**
 
 */
package com.cv.webservice.client;

import com.cv.webservice.HelloWorld;
import com.cv.webservice.HelloWorldImplService;


/**
 @author Chandra Vardhan
 *
 */
public class HelloWorldClient2 {
  
  /**
   
   */
  public HelloWorldClient2() {
  }

  /**
   @param args
   */
  public static void main(String[] args) {
    HelloWorldImplService hw = new HelloWorldImplService();
    HelloWorld helloWorldImplPort = hw.getHelloWorldImplPort();
    String helloWorldAsString = helloWorldImplPort.getHelloWorldAsString("hello");
    System.out.println(helloWorldAsString);      
    
  }

}


This is HelloWorldPublisher.java file having the source code to execute business logic.



 

    
package com.cv.webservice.endpoint;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import javax.xml.ws.Endpoint;

import org.apache.log4j.Logger;

import com.cv.webservice.HelloWorldImpl;

/**
 @author Chandra Vardhan
 *
 */
//Endpoint publisher  
public class HelloWorldPublisher {

  
  
  private static final Logger LOGGER = Logger.getLogger(HelloWorldPublisher.class);
  private static String WS_URL = "/JaxWSRPCStyle/hello";

  static {
    Properties properties = readFile();
    setValues(properties);
  }

  public static void main(String[] args) {

    Endpoint.publish(WS_URL, new HelloWorldImpl());
    
    LOGGER.info("Server is URL is : : " + WS_URL);

  }

  private static void setValues(Properties properties) {

    if (properties != null) {
      String port = properties.getProperty("portNumber");
      WS_URL = "http://localhost:" + port + WS_URL;
    }
  }

  private static Properties readFile() {

    File file = new File(System.getProperty("user.dir")
        "/input.properties");
    Properties prop = new Properties();
    if (file != null && file.exists()) {
      InputStream input = null;
      try {
        input = new FileInputStream(file);
        // load a properties file
        prop.load(input);
      catch (Exception e) {
        e.printStackTrace();
      }
    else {
      prop.setProperty("portNumber""8080");
    }
    return prop;
  }
}


This is HelloWorld.java file having the source code to execute business logic.



 

    

package com.cv.webservice;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Action;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 
 */

/**
 @author Chandra Vardhan
 *
 */
@WebService(name = "HelloWorld", targetNamespace = "http://webservice.cv.com/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWorld {


    /**
     
     @param arg0
     @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(partName = "return")
    @Action(input = "http://webservice.cv.com/HelloWorld/getHelloWorldAsStringRequest", output = "http://webservice.cv.com/HelloWorld/getHelloWorldAsStringResponse")
    public String getHelloWorldAsString(
        @WebParam(name = "arg0", partName = "arg0")
        String arg0);

}


This is HelloWorldImpl.java file having the source code to execute business logic.



 

    
package com.cv.webservice;

import javax.jws.WebService;

import org.apache.log4j.Logger;

/**
 @author Chandra Vardhan
 *
 */
// Service Implementation
@WebService(endpointInterface = "com.cv.webservice.HelloWorld")
public class HelloWorldImpl implements HelloWorld {

  private static final Logger LOGGER = Logger.getLogger(HelloWorldImpl.class);
  
  public String getHelloWorldAsString(String name) {
    LOGGER.info("Entered in HelloWorldImpl.getHelloWorldAsString(String)");
    return "Hello World IMPL JAX-WS " + name;
  }
}


This is HelloWorldImplService.java file having the service/business logic to call the DAO layer and get the information from database.



 

    
package com.cv.webservice;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 
 */

/**
 @author Chandra Vardhan
 *
 */
@WebServiceClient(name = "HelloWorldImplService", targetNamespace = "http://webservice.cv.com/")
public class HelloWorldImplService extends Service {

  private final static URL HELLOWORLDIMPLSERVICE_WSDL_LOCATION;
  private final static WebServiceException HELLOWORLDIMPLSERVICE_EXCEPTION;
  private final static QName HELLOWORLDIMPLSERVICE_QNAME = new QName(
      "http://webservice.cv.com/""HelloWorldImplService");

  static {
    URL url = null;
    WebServiceException e = null;
    try {
      url = new URL("http://localhost:8089/Jax-ws-RPC-style/hello?wsdl");
    catch (MalformedURLException ex) {
      e = new WebServiceException(ex);
    }
    HELLOWORLDIMPLSERVICE_WSDL_LOCATION = url;
    HELLOWORLDIMPLSERVICE_EXCEPTION = e;
  }

  public HelloWorldImplService() {
    super(__getWsdlLocation(), HELLOWORLDIMPLSERVICE_QNAME);
  }

  public HelloWorldImplService(WebServiceFeature... features) {
    super(__getWsdlLocation(), HELLOWORLDIMPLSERVICE_QNAME, features);
  }

  public HelloWorldImplService(URL wsdlLocation) {
    super(wsdlLocation, HELLOWORLDIMPLSERVICE_QNAME);
  }

  public HelloWorldImplService(URL wsdlLocation,
      WebServiceFeature... features) {
    super(wsdlLocation, HELLOWORLDIMPLSERVICE_QNAME, features);
  }

  public HelloWorldImplService(URL wsdlLocation, QName serviceName) {
    super(wsdlLocation, serviceName);
  }

  public HelloWorldImplService(URL wsdlLocation, QName serviceName,
      WebServiceFeature... features) {
    super(wsdlLocation, serviceName, features);
  }

  /**
   
   @return returns HelloWorld
   */
  @WebEndpoint(name = "HelloWorldImplPort")
  public HelloWorld getHelloWorldImplPort() {
    return super.getPort(new QName("http://webservice.cv.com/",
        "HelloWorldImplPort"), HelloWorld.class);
  }

  /**
   
   @param features
   *            A list of {@link javax.xml.ws.WebServiceFeature} to configure
   *            on the proxy. Supported features not in the
   *            <code>features</code> parameter will have their default
   *            values.
   @return returns HelloWorld
   */
  @WebEndpoint(name = "HelloWorldImplPort")
  public HelloWorld getHelloWorldImplPort(WebServiceFeature... features) {
    return super.getPort(new QName("http://webservice.cv.com/",
        "HelloWorldImplPort"), HelloWorld.class, features);
  }

  private static URL __getWsdlLocation() {
    if (HELLOWORLDIMPLSERVICE_EXCEPTION != null) {
      throw HELLOWORLDIMPLSERVICE_EXCEPTION;
    }
    return HELLOWORLDIMPLSERVICE_WSDL_LOCATION;
  }

}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<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>com.cv.webservice.soap</groupId> <artifactId>JaxWSRPCStyle</artifactId> <version>1.0</version> <packaging>war</packaging> <name>JaxWSRPCStyle</name> <properties> <springframework.version>4.1.6.RELEASE</springframework.version> <springsecurity.version>4.0.1.RELEASE</springsecurity.version> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>JaxWSRPCStyle</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>JaxWSRPCStyle</finalName> </build> </project>


This is web.xml deployment descriptor file and it describes how the web application should be deployed.



	
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>com.cv.servlet.init.InitServlet</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>initServlet</servlet-name>
<url-pattern>/initServlet</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n