How to convert a JKS Keystore to a PKCS12 (.p12) format


To convert a JKS (.jks) keystore to a PKCS12 (.p12) keystore, run the following command:

Note: This command is supported on JDK / JRE keytool versions 1.6 and greater.

keytool -importkeystore -srckeystore <jks_file_name.jks> -destkeystore <pk12_file_name.p12> -srcstoretype JKS -deststoretype PKCS12 -deststorepass <password>

To verify the content of .p12 (e.g. pk12_file_name.p12), run the following command:
keytool -list -v -keystore <“pk12_file_name.p12”> -storetype <password>

Create Web service using wsgen in command line


Generally bottom up approach, where the service implementation is done first and wsdl will be generated next, is not a suggested way of implementing a web service. In some cases where the service implementation class is already exists in the application and wants to expose it as web service then it is acceptable to go with bottom up approach.

In this post, I would like to show how the web service can be developed in bottom up approach using the wsgen command.

The wsgen tool reads an existing web service implementation class and generates the required JAX–WS portable artifacts for web service development and deployment. The wsgen tool can be used for bottoms-up approach, where you are starting from a service endpoint implementation rather than a wsdl. The generated JAX-WS artifacts can be used by both service and client implementations.

Below is the sample service class created – HellowWorldService.java

package in.malliktalksjava.service;

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

@WebService(name=”HellowWorldService”,
targetNamespace=”http://malliktalksjava.in&#8221;,
wsdlLocation=”http://localhost:8085/HellowWorldService?wsdl&#8221;)
public class HellowWorldService{

@WebMethod
public void printHelloMessage(){
System.out.println(“Printing hello message”);
};

@WebMethod
public String getThankyouMessage(){
System.out.println(“Printing thank you message”);

return null;
};

}

Compile the java classes using below command:

javac -d . in/malliktalksjava/service/*.java

Once the compilation is successful, use the below wsgen command to generate the artifacts:

wsgen -verbose -keep -cp . in.malliktalksjava.service.HellowWorldService

Once click on the enter button, below are the artifacts generated in jaxws folder:

in\malliktalksjava\service\jaxws\GetThankyouMessage.java
in\malliktalksjava\service\jaxws\GetThankyouMessageResponse.java
in\malliktalksjava\service\jaxws\PrintHelloMessage.java
in\malliktalksjava\service\jaxws\PrintHelloMessageResponse.java

If it is required to generate the wsdl file along with the artifacts, we need to use the below command:

wsgen -verbose -keep -cp . -wsdl in.malliktalksjava.service.HellowWorldService

Below are the list of options available in wsgen command:

wsgenoptions

 

Differences between wsimport and wsgen


wsimport:

  • The wsimport tool reads a WSDL and generates all the required artifacts for web service development, deployment, and invocation.
  • It supports the top-down approach to developing JAX-WS Web services, where you are starting from a wsdl.
  • wsimport tool generated JAX-WS portable artifacts include Service Endpoint Interface (SEI), Service, Exception class mapped from wsdl:fault (if any), JAXB generated value types (mapped java classes from schema types) etc. These artifacts can be packaged in a WAR file with the WSDL and schema documents along with the endpoint implementation to be deployed.

Ex Command :

wsimport http://localhost:8090/MyJaxWSService?wsdl

wsgen:
The wsgen tool reads an existing web service implementation class and generates the required JAX–WS portable artifacts for web service development and deployment. The wsgen tool can be used for bottoms-up approach, where you are starting from a service endpoint implementation rather than a wsdl.

Ex Command :

wsgen -verbose -keep -cp . in.malliktalksjava.service.HellowWorldService
  • wsgen and wsimport generate request and response wrapper bean classes and the JAXB classes. However, wsgen generates the JAXB classes and put them in a jaxws folder and wsimport does not put those classes in any folder instead they will be placed in the current directory.
  • JAX-WS artifacts generated can be used by both service implementation and client implementation.
  • Using wsgen you can also generate the wsdl based on webservice implementation class.

Create web service in Bottom Up approach using command line


Create Service Interface MyJaxWSSEI.java

package in.malliktalksjava.ws;

import in.malliktalksjava.ws.pojo.*;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.WebParam.Mode;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.jws.soap.SOAPBinding.Use;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

@WebService(name = “MyJaxWSHello”,
targetNamespace = “http://malliktalksjava.in&#8221;,
wsdlLocation = “http://malliktalksjava.in/MyJaxWS?wsdl&#8221;)
@SOAPBinding(style=Style.RPC, use=Use.LITERAL)
public interface MyJaxWSSEI {

@WebMethod(operationName=”getJXWsRes”)
@RequestWrapper(targetNamespace=”http://malliktalksjava.in/ws/types&#8221;,
className=”java.lang.String”)
@ResponseWrapper(targetNamespace=”http://malliktalksjava.in/ws/types&#8221;,
className=”in.malliktalksjava.ws.JXRes”)
@WebResult(targetNamespace=”http://malliktalksjava.in/ws/types&#8221;,
name=”JXWsRes”)
public JXRes getJXWsRes(
@WebParam(targetNamespace=”http://malliktalksjava.in/ws/types&#8221;,
name=”name”,
mode=Mode.IN)
String name
);

}

 

Create Implementation class for the above interface – MyJaxWSSEIImpl.java

package in.malliktalksjava.ws;

import in.malliktalksjava.ws.pojo.*;
import javax.jws.WebService;

@WebService(endpointInterface=”in.malliktalksjava.ws.MyJaxWSSEI”,
targetNamespace=”http://malliktalksjava.in&#8221;,
portName=”MyJaxWSSEIPort”,
serviceName=”MyJaxWSHelloService”)
public class MyJaxWSSEIImpl implements MyJaxWSSEI {

/**
* Default Constructor
*/
public MyJaxWSSEIImpl() {

}

/* (non-Javadoc)
* @see in.malliktalksjava.ws.MyJaxWSSEI#getJXWsRes(java.lang.String)
*/
@Override
public JXRes getJXWsRes(String name) {
JXRes jxRes = new JXRes();
jxRes.setMessage(“Hello”);
jxRes.setName(name);
return jxRes;
}

}

Create Required Model object JXRes.java

package in.malliktalksjava.ws.pojo;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class JXRes {
protected String message;
protected String name;
/**
*
*/
public JXRes() {
super();
}
/**
* @return the id
*/
public String getMessage() {
return message;
}
/**
* @param id the id to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}

}

Create Main Class JXResTest.java

package in.malliktalksjava.ws.main;

import javax.xml.ws.Endpoint;
import in.malliktalksjava.ws.*;

public class JXResTest {
public static void main(String[] args ){
Endpoint.publish(“http://localhost:8080/MyJaxWSService&#8221;, new MyJaxWSSEIImpl());
}
}

 

Compile Java Classes in command prompt:

compileclass

Run the class

runmainclass

Verify the service : http://localhost:8080/MyJaxWSService?wsdl

wsdl

 

Difference between ClassNotFoundException and NoClassDefFoundError


1. java.lang.ClassNotFoundException :  This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.

2. java.lang.NoClassDefFoundError :  This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason – now we’re trying to use the class again (and thus need to load it, since it failed last time), but we’re not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

Difference between HttpSession’s getSession(), getSession(true) and getSession(false) methods


  • getSession() : Returns the current session associated with this request, or if the request does not have a session, creates one.
  • getSession(true) : Returns the current HttpSession associated with this request, if there is no current session, returns a new session
  • getSession(false) : Returns the current HttpSession associated with this request, if there is no current session, returns null.

How to read a URL using Java?


  • Below program consists of steps to read data from the URL
package in.malliktalksjava;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
* @author malliktalksjava
*
*/
public class URLConnectionReader {

public static void main(String[] args) throws Exception {

URL oracle = new URL("http://malliktalksjava.in/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}

Example Program: Search Word in Folder files and print output


To Search a word in in list of files available in Folder, you need to find the list of files first and then scan each and every for required word. Below is the sample program to find the a given word Java in D:\\test folder of files.

package in.javatutorials;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.MatchResult;

/**
 * Search for the files in a folder and prints all file details.
 */
public class WordCrawlerInFolder {

private static String directoryPath = "D://test";
private static String searchWord = "Java";

public WordCrawlerInFolder() {
super();
}

public static void main(String[] args) {
   WordCrawlerInFolder crawler = new WordCrawlerInFolder();
    File directory = new File(directoryPath);

    if (directory == null || !directory.exists()) {
           System.out.println("Directory doesn't exists!!!");
           return;
    }
    crawler.directoryCrawler(directory, searchWord);
}

/**
* Gets all the file and directories and prints accordingly
* @param directory
* Directory path where it should search
*/
public void directoryCrawler(File directory, String searchWord) {

// Get List of files in folder and print
File[] filesAndDirs = directory.listFiles();

// Print the root directory name
//System.out.println("-" + directory.getName());

// Iterate the list of files, if it is identified as not a file call
// directoryCrawler method to list all the files in that directory.
for (File file : filesAndDirs) {

if (file.isFile()) {
searchWord(file, searchWord);
//System.out.println(" |-" + file.getName());
} else {
directoryCrawler(file, searchWord);
}
}
}

/**
* Search for word in a given file.
* @param file
* @param searchWord
*/
private void searchWord(File file, String searchWord){
Scanner scanFile;
try {
scanFile = new Scanner(file);
while (null != scanFile.findWithinHorizon("(?i)\\b"+searchWord+"\\b", 0)) {
MatchResult mr = scanFile.match();
System.out.printf("Word found : %s at index %d to %d.%n", mr.group(),
mr.start(), mr.end());
}
scanFile.close();
} catch (FileNotFoundException e) {
System.err.println("Search File Not Found !!!!! ");
e.printStackTrace();
}
}
}

We have used some escape characters in above class searchWord() method, below is the notation for the same.

  1. (?i) turn on the case-insensitive switch
  2. \b means a word boundary
  3. java is the string searched for
  4. \b a word boundary again.

If search term contain special characters, it would be suggested to use \Q and \E around the string, as it quotes all characters in between. Make sure the input doesn’t contain \E itself.

Other Useful Links:

Javac/Java searching algorithm for other classes

Example program to reverse a Number in Java

How to find count of duplicates in a List

Threads Interview questions in Java

Example Java Program to Search Files in a Folder


Below Java Program lists the file names and directory names available in given folder. To do this implementation , we can get the files list in a folder using File class available in Java API. Iterate the files one by one and write the file name on to console.

If it is identified as a directory instead of a file, then iterate the process as mentioned in directoryCrawler() method in the below class.

package in.javatutorials;

import java.io.File;

/**
* @author malliktalksjava
*
* Search for the files in a folder and prints all file details.
*
*/
public class FolderCrawler {

private static String directoryPath = “D://test”;

/**
* Creating constructor
*/
public FolderCrawler() {
super();
}

/**
* main method
*
* @param ags
*/
public static void main(String[] args) {
FolderCrawler crawler = new FolderCrawler();

File directory = new File(directoryPath);

if (directory == null || !directory.exists()) {
System.out.println(“Directory doesn’t exists!!!”);
return;
}

crawler.directoryCrawler(directory);
}

/**
* Gets all the file and directories and prints accordingly
*
* @param directory
* Directory path where it should search
*/
public void directoryCrawler(File directory) {

// Get List of files in folder and print
File[] filesAndDirs = directory.listFiles();

// Print the root directory name
System.out.println(“-” + directory.getName());

// Iterate the list of files, if it is identified as not a file call
// directoryCrawler method to list all the files in that directory.
for (File file : filesAndDirs) {

if (file.isFile()) {
System.out.println(” |-” + file.getName());
} else {
directoryCrawler(file);

}
}// end of for

}// End of directory Crawler
}

 

Other Useful Links:

Javac/Java searching algorithm for other classes

Example program to reverse a Number in Java

How to find count of duplicates in a List

Threads Interview questions in Java