How to get IP address in Java

To get IP address of the current computer that’s running the Java application, uses InetAddress.getLocalHost() to initialize the InetAddress object and InetAddress.getHostAddress() to get the current IP address.

Full example.

package br.com.ziben;
 
import java.net.InetAddress;
import java.net.UnknownHostException;
 
public class app{
 
	public static void main(String[] args){
 
		InetAddress ip;
		try {
 			ip = InetAddress.getLocalHost();
			System.out.println("Current IP address : " + ip.getHostAddress());
 
		} catch (UnknownHostException e) {
 			e.printStackTrace();
 		}
 	}
 }

Output

Current IP address : 192.168.0.185

IP 192.168.0.185 is my computer’s IP address to run this example, let compare with Ubuntu’s ifconfig

ifconfig output…

eth0      Link encap:Ethernet  Endereço de HW b8:ac:6f:74:b7:51  
          inet end.: 192.168.0.185  Bcast:192.168.0.255  Masc:255.255.255.0
          endereço inet6: fe80::baac:6fff:fe74:b751/64 Escopo:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Métrica:1
          pacotes RX:19403 erros:0 descartados:0 excesso:0 quadro:0
          Pacotes TX:14705 erros:0 descartados:0 excesso:0 portadora:0
          colisões:0 txqueuelen:1000 
          RX bytes:10498710 (10.4 MB) TX bytes:2187781 (2.1 MB)
          IRQ:45 Endereço de E/S:0x2000  

Same, InetAddress.getHostAddress() is working as expected.

Application Authentication with JAX-WS

One of the common way to handle authentication in JAX-WS is client provides “username” and “password”, attached it in SOAP request header and send to server, server parse the SOAP document and retrieve the provided “username” and “password” from request header and do validation from database, or whatever method prefer.

In this article, we show you how to implement the above “application level authentication in JAX-WS”.

Ideas…

On the web service client site, just put your “username” and “password” into request header.

    Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
    req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
 
    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    headers.put("Username", Collections.singletonList("cazo"));
    headers.put("Password", Collections.singletonList("password"));
    req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

On the web service server site, get the request header parameters via WebServiceContext.

    @Resource
    WebServiceContext wsctx;
 
    @Override
    public String method() {
 
        MessageContext mctx = wsctx.getMessageContext();
 
	//get detail from request headers
        Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
        List userList = (List) http_headers.get("Username");
        List passList = (List) http_headers.get("Password");
 
    //...

That’s all, now, your deployed JAX-WS is supported application level authentication.

Authentication with JAX-WS Example

See a complete example.

1. WebService Server

Create a simple JAX-WS hello world example to handle the authentication in application level.

File : HelloWorld.java

package br.com.ziben.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();
 
}

HelloWorldImpl.java

package br.com.ziben.ws;
 
import java.util.List;
import java.util.Map;
 
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
 
//Service Implementation Bean
@WebService(endpointInterface = "br.com.ziben.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
 
    @Resource
    WebServiceContext wsctx;
 
    @Override
    public String getHelloWorldAsString() {
 
	MessageContext mctx = wsctx.getMessageContext();
 
	//get detail from request headers
        Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
        List userList = (List) http_headers.get("Username");
        List passList = (List) http_headers.get("Password");
 
        String username = "";
        String password = "";
 
        if(userList!=null){
        	//get username
        	username = userList.get(0).toString();
        }
 
        if(passList!=null){
        	//get password
        	password = passList.get(0).toString();
        }
 
        //Should validate username and password with database
        if (username.equals("cazo") && password.equals("password")){
        	return "Hello World JAX-WS - Valid User!";
        }else{
        	return "Unknown User!";
        }
 
    }
}

2. EndPoint Publisher

Create an endpoint publisher to deploy above web service at this URL : “http://localhost:9999/ws/hello”

File : HelloWorldPublisher.java

package br.com.ziben.endpoint;
 
import javax.xml.ws.Endpoint;
import br.com.ziben.ws.HelloWorldImpl;
 
//Endpoint publisher
public class HelloWorldPublisher{
 
    public static void main(String[] args) {
	   Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl());
    }
 
}

3. WebService Client

Create a web service client to send “username” and “password” for authentication.

File : HelloWorldClient.java

package br.com.ziben.client;
 
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.MessageContext;
 
import br.com.ziben.ws.HelloWorld;
 
public class HelloWorldClient{
 
	private static final String WS_URL = "http://localhost:9999/ws/hello?wsdl";
 
	public static void main(String[] args) throws Exception {
 
	URL url = new URL(WS_URL);
        QName qname = new QName("http://ws.ziben.com.br/", "HelloWorldImplService");
 
        Service service = Service.create(url, qname);
        HelloWorld hello = service.getPort(HelloWorld.class);
 
        /*******************UserName & Password ******************************/
        Map<String, Object> req_ctx = ((BindingProvider)hello).getRequestContext();
        req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
 
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("Username", Collections.singletonList("cazo"));
        headers.put("Password", Collections.singletonList("password"));
        req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
        /**********************************************************************/
 
        System.out.println(hello.getHelloWorldAsString());
 
    }
}

Output

Hello World JAX-WS - Valid User!

4. Tracing SOAP Traffic

From top to bottom, showing how SOAP envelope flows between client and server.

1. Client send request, the username “cazo” and password “password” are included in the SOAP envelope.

POST /ws/hello?wsdl HTTP/1.1
Password: password
Username: cazo
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0_13
Host: localhost:8888
Connection: keep-alive
Content-Length: 178
 
<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:getHelloWorldAsString xmlns:ns2="http://ws.ziben.com.br/"/>
		</S:Body>
	</S:Envelope>

2. Server send back a normal response.

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml; charset=utf-8
 
<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:getHelloWorldAsStringResponse xmlns:ns2="http://ws.ziben.com.br/">
				<return>Hello World JAX-WS - Valid User!</return>
			</ns2:getHelloWorldAsStringResponse>
		</S:Body>
	</S:Envelope>

Done.

Java HTTPS client – HttpsURLConnection example

Here’s a simple Java HTTPS client to demonstrate the use of HttpsURLConnection class to print a https URL content and certificate detail.

Access https URL : https://www.google.com/

package br.com.ziben.client;
 
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.io.*;
 
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
 
public class HttpsClient{
 
   public static void main(String[] args)
   {
        new HttpsClient().testIt();
   }
 
   private void testIt(){
 
      String https_url = "https://www.google.com/";
      URL url;
      try {
	     url = new URL(https_url);
	     HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
 
	     //dump all cert info
	     print_https_cert(con);
 
	     //dump all the content
	     print_content(con);
 
      } catch (MalformedURLException e) {
	     e.printStackTrace();
      } catch (IOException e) {
	     e.printStackTrace();
      }
 
   }
 
   private void print_https_cert(HttpsURLConnection con){
 
    if(con!=null){
 
      try {
 
	System.out.println("Response Code : " + con.getResponseCode());
	System.out.println("Cipher Suite : " + con.getCipherSuite());
	System.out.println("\n");
 
	Certificate[] certs = con.getServerCertificates();
	for(Certificate cert : certs){
	   System.out.println("Cert Type : " + cert.getType());
	   System.out.println("Cert Hash Code : " + cert.hashCode());
	   System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
	   System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
	   System.out.println("\n");
	}
 
	} catch (SSLPeerUnverifiedException e) {
		e.printStackTrace();
	} catch (IOException e){
		e.printStackTrace();
	}
     }
   }
 
   private void print_content(HttpsURLConnection con){
	if(con!=null){
 
	try {
 
	   System.out.println("****** Content of the URL ********");			
	   BufferedReader br = 
		new BufferedReader(
			new InputStreamReader(con.getInputStream()));
	   String input;
 
	   while ((input = br.readLine()) != null){
	      System.out.println(input);
	   }
	   br.close();
 
	} catch (IOException e) {
	   e.printStackTrace();
	}
       }
   }
}

Output…

Response Code : 200
Cipher Suite : SSL_RSA_WITH_RC4_128_SHA
 
Cert Type : X.509
Cert Hash Code : 7810131
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509
 
Cert Type : X.509
Cert Hash Code : 6042770
Cert Public Key Algorithm : RSA
Cert Public Key Format : X.509
 
****** Content of the URL ********
<!doctype html><html><head><meta http-equiv="content-type" ......

That’s it!

How to validate URL in Java

A short example to show the use of apache.commons.validator.UrlValidator class to validate an URL in Java.

import org.apache.commons.validator.UrlValidator;
 
public class ValidateUrlExample{
 
	public static void main(String[] args) {
 
	    UrlValidator urlValidator = new UrlValidator();
 
	    // valid URL
	    if (urlValidator.isValid("http://www.ziben.com.br")) {
	       System.out.println("url is valid");
	    } else {
	       System.out.println("url is invalid");
	    }
 
	    // invalid URL
	    if (urlValidator.isValid("http://invalidURL^$&%$&^")) {
	        System.out.println("url is valid");
	    } else {
	        System.out.println("url is invalid");
	    }
 
	}
}

Output

url is valid
url is invalid

Reference

  1. http://commons.apache.org/validator/apidocs/org/apache/commons/validator/UrlValidator.html

Microsoft won’t stop .Net on Android

Oracle’s patent and copyright lawsuit against Google for its use of Java in Android won’t be repeated by Microsoft if .Net is used on the Linux-based mobile operating system instead.

Director of the open source technology centre at Microsoft Tom Hanrahan said the Community Promise allows projects like Mono to fully support its technology.

“The type of action Oracle is taking against Google over Java is not going to happen,” Hanrahan said.

Microsoft’s Community Promise has made the .Net runtime and C# specifications available to Miguel de Icaza and the Mono project developers.

“If a .Net port to Android was through Mono it would fall under that agreement,” he said.

Hanrahan is visiting Australia for Microsoft’s annual Tech.Ed conference.

Novell has already developed MonoTouch for Apple’s iOS-based devices like the iPhone and iPad, and a Mono port to Android, dubbed “MonoDroid”, is on the roadmap, due for a preview release in Q3 this year.

“Mono for Android will have an entirely different set of APIs, at most you would be able to reuse business logic, but any user interface and device specific code will have to be rewritten,” according to the Mono developers.

Oracle’s complaint against Google centres around its development of the Dalvik virtual machine that can run applications written in Java.

Dalvik is not an officially sanctioned Java runtime environment, however Sun did initially praise Google for supporting Java on Android.

Potential conflict between Sun and Google over Dalvik was also predicted back in 2007, but did not eventuate until Oracle acquired Sun.

With Java use in Android under fire, Microsoft is unlikely to disrupt any port of C# to the mobile platform, however, Microsoft’s Community Promise has been criticised by the Free Software Foundation for not going far enough to protect open source implementations from patent litigation, which is at the heart of the Oracle-Google case.

“The Community Promise does not give you any rights to exercise the patented claims. It only says that Microsoft will not sue you over claims in patents that it owns or controls,” according to the Free Software Foundation.

“If Microsoft sells one of those patents, there’s nothing stopping the buyer from suing everyone who uses the software.”

Mono developer Miguel de Icaza is not concerned about legal challenges by Microsoft over .Net implementations and wrote on his blog that Google could switch from Java.

“Google could settle current damages with Oracle, and switch to the better designed, more pleasant to use, and more open .Net platform,” de Icaza wrote.

Rodney Gedda is Editor of TechWorld Australia. Follow Rodney on Twitter at @rodneygedda. Rodney’s e-mail address is rodney_gedda@idg.com.au. Follow TechWorld Australia on Twitter at @Techworld_AU.

References