Saturday, July 27, 2013

Start a program using Linux Commands from Java & get its Process ID

Get Process ID of Linux Process that started using Java (Runtime.getRuntime().exec(command))


Hi my friends, we know how to start a sub-program from java using Runtime.getRuntime().exec(command). But how to get process id ?

Here is the answer,


java.lang.Process class is abstract and that you actually get a concrete subclass depending on your platform. On Linux, you'll get a java.lang.UnixProcesswhich has a private field int pid.



Process proc = Runtime.getRuntime().exec(command);
Field f = proc.getClass().getDeclaredField("pid");
f.setAccessible(true);
System.out.println("Process ID : " + f.get(proc));


Example :


import java.lang.reflect.Field;

public class TestCMD {
 public static void main(String[] args) {
  String cmd = "echo HelloAll";
  int processId = execute(cmd);
  System.out.println("Process ID : " + processId);
 }

 private static int execute(String command) {
  int pid = 0;
  try {
   Process proc = Runtime.getRuntime().exec(command);
   Field f = proc.getClass().getDeclaredField("pid");
   f.setAccessible(true);
   pid = (int) f.get(proc);

  } catch (Exception e) {

   e.printStackTrace();
  }
  return pid;
 }
}

Thursday, July 25, 2013

SERVER SENT EVENTS

SERVER SENT EVENTS 



Server-sent events is a technology for where a browser gets automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C.

Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.



Web browser support for Server-Sent Events
Browser
Supported
Notes
NO
[3]
Yes
Starting with Firefox 6.0 [4]
Yes
[3]
Yes
Starting with Opera 11 [3]
Yes
Starting with Safari 5.0 [3]



SERVER SENT EVENTS IN SPRING MVC

Controller for mapping events

@Controller
@RequestMapping("sseTest.htm")
public class SseController {
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody String sendMessage(HttpServletResponse response) {
                Random r = new Random();
                response.setContentType("text/event-stream, charset=UTF-8");
                try {
                        Thread.sleep(10000);
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }   
                return "data:Testing 1,2,3" + r.nextInt() +"\n\n" + "retry: 100\n" ;
      }

}

Controller for mapping jsp page

@Controller
@RequestMapping("viewSSE.htm")
public class ViewSSEController {
 
@RequestMapping(method = RequestMethod.GET)
public String home(ModelMap model){
 
 return "viewSSE";
}
}


In view (viewSSE.jsp)

Wednesday, July 3, 2013

Handle IP and IP number in MySQL

Handle IP and IP number in MySQL




You can use int unsigned for storing IP address (like 127.0.0.1)  in MySQL.

But HOW ???

INET_ATON() and INET_NTOA() Functions in MySQL will help you....


SELECT INET_ATON('127.0.0.1');

+------------------------+
| INET_ATON('127.0.0.1') |
+------------------------+
|             2130706433 | 
+------------------------+
1 row in set (0.00 sec)


SELECT INET_NTOA('2130706433');

+-------------------------+
| INET_NTOA('2130706433') |
+-------------------------+
| 127.0.0.1               | 
+-------------------------+
1 row in set (0.02 sec)
Store the converted IP number as int unsigned in MySQL using INET_ATON() and get the exact IP addess by using INET_NTOA()

MySQL persistence connection settings (Change connection Time out values)

MySQL persistence connection settings


1. Start the DB server as 'root' user with  the comandline option and check the values of 'net_read_timeout' and 'wait_timeout'



The result may be like this :

mysql> SHOW SESSION VARIABLES LIKE 'net_read_timeout';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| net_read_timeout | 30    |
+------------------+-------+
1 row in set (0.00 sec)


mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
wait_timeout | 30    |
+------------------+-------+
1 row in set (0.00 sec)


2. Change the values as you need

Here i am setting 28800 instead of 30


mysql> SET SESSION net_read_timeout=28800;
Query OK, 0 rows affected (0.00 sec)

mysql> SET SESSION wait_timeout=28800;
Query OK, 0 rows affected (0.00 sec)

3. Now you can check the variable values updated or not..

mysql> SHOW SESSION VARIABLES LIKE 'net_read_timeout';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
net_read_timeout | 28800 |
+------------------+-------+
1 row in set (0.00 sec)

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
wait_timeout | 28800 |
+------------------+-------+
1 row in set (0.00 sec)

4. Now restart your mysql server

If you are using mysql on RedHat Linux (Fedora Core/Cent OS) then use following command:

/etc/init.d/mysqld restart

If you are using mysql on Debian / Ubuntu Linux then use following command:

/etc/init.d/mysql restart
Thats it  !

Tuesday, July 2, 2013

How to give IP instead of localhost - tomcat ?

How to give IP instead of localhost



The problem is in your server's 'server.xml' file. (in Apache installed directory) 

  <Connector port="8080" protocol="HTTP/1.1" 
      address="127.0.0.1"
               connectionTimeout="20000" 
               redirectPort="8443" />

change it as 

  <Connector port="8080" protocol="HTTP/1.1" 
      address="0.0.0.0"
               connectionTimeout="20000" 
               redirectPort="8443" />



Thats it !

Monday, July 1, 2013

Restlet Auth

Example For Restlet Auth 



1. Create a Restlet Server 

package server;

import org.restlet.Application;
import org.restlet.Component;
import org.restlet.data.Protocol;

public class TestServer extends Application {

public static void main(String[] args) throws Exception {
Component component = new Component();
component.getServers().add(Protocol.HTTP, 8182);
component.getDefaultHost().attach("/trace", Part3.class); 
component.start();
}

}

2. Create a Restlet Resource

package server;
import org.restlet.Request;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class RestletResource extends ServerResource {  
@Get
public Representation doPost(Representation entity) {
Request request = getRequest();
Check check = new Check();
String result = check.authCheck(request);
if(result.equals("success")){
return new StringRepresentation("Success : ", MediaType.TEXT_PLAIN);
}
else{
return new StringRepresentation("Fail : ", MediaType.TEXT_PLAIN);
}
}
}  

3. Create a Auth Check method

import org.restlet.Request;
import org.restlet.data.ChallengeResponse;

public class Check {
public String authCheck(Request request) {
String result;
ChallengeResponse challengeResponse = request.getChallengeResponse();
if (challengeResponse == null) {
throw new RuntimeException("not authenticated");
}
String userName = challengeResponse.getIdentifier();
System.out.println("Identifier :" + userName);
String password = new String(challengeResponse.getSecret());
System.out.println("Secret" + password);
                 /*
* Here you can check the username and password. I am considering 'Dev' and 'Dev123'
*/
if (userName.equals("dev") && password.equals("Dev123")) {
result = "success";
} else {
result = "fail";
}
return result;

}
}

4. Restlet Client

import org.restlet.data.ChallengeScheme;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;

public class TestClient {

public static void main(String[] args) throws Exception {
ClientResource resource = new ClientResource("http://localhost:8182/trace");
resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "dev", "Dev123");
// Send the first request with unsufficient authentication.
try {
System.out.println(resource.get(String.class));
} catch (ResourceException re) {
re.printStackTrace();
}

}
}