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();
}

}
}



Friday, June 28, 2013

How to solve “Unable to load native-hadoop library” in Eclipse



How to solve “Unable to load native-hadoop library” in Eclipse


WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Running jobs via the hadoop cli command worked fine; this only happened when I tried to run jobs directly from Eclipse, in local mode. After doing a little investigation, I found that the reason behind this is a java property called java.library.path that did not include the correct path.
Running from the hadoop cli command, the java.library.path property was properly set to /opt/cloudera/parcels/CDH-4.2.0-1.cdh4.2.0.p0.10/lib/hadoop/lib/native (I am using the CDH 4.2.0 distribution of Hadoop). When the job was started from inside Eclipse, the java.library.path held it’s system default value:
native1
In order to correctly set this property you can configure Eclipse to load the Java Virtual Machine with this setting, or (and this is the better way) add the native library under the respective library from the Java Build Path. In order to do this, first right click on your project and open the Buid Path configuration screen:
native2
In this screen, find the hadoop-common library, expand the row and add the native library by pointing to the correct location:
native3

Monday, June 24, 2013

Log4j, java library that specializes in logging

Apache Logging Services Project

Log4j, java library that specializes in logging


Log4j is a Java library that specializes in logging. At the time of this writing, its home page is at http://logging.apache.org/log4j/1.2/index.html . The Java library itself is available for download at http://logging.apache.org/log4j/1.2/download.html .  At its most basic level, you can think of it as a replacement for System.out.println's in your code.

Steps to Integrate Log4j with your Java project

2. Add the jar to your project
3. Create a new file 'log4j.properties' in your  project 'src'  and add the contents as follows and save it :
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logs/testlog.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
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
4. Append one line code to integrate Log4j to the class, declare a variable say 'log' as type 'Logger'
 static Logger log = Logger.getLogger(ClassName.class.getName());
'ClassName' is the name of the class that you need to use Log4j for logging.
5. Now you can use 
 log.debug("This is debug message");
  log.info("This is info message");
  log.warn("This is warn message");
  log.fatal("This is fatal message");
  log.error("This is error message");
for debug ,info,warning,fatal and error logs instead of  System.out.println 
Thats It !
For example :


import org.apache.log4j.Logger;
public class Test {
  static Logger log = Logger.getLogger(Test.class.getName());
  public static void main(String[] args) {
   try {
   int i = 1;
   int b = 1 - 1;
   b = i / b;
  } catch (Exception e) {
   log.error("failed", e);
   e.printStackTrace();
  }
 }
}

Sunday, June 23, 2013

Sent Email using Java



Sent Email using Java and gmail



import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class Mail {

public static void main(String[] args) {

// Set up the SMTP server.
String to = "mailId";// Reciver Address.
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("yourEmailId", "password");// SenderID and Password.
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("SenderMailId"));// Sender Id.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject("Mail Subject");
message.setText("Mail Body");
// send message.
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);

}

}
}


Saturday, June 22, 2013

POST request to the server using Terminal (Linux)



POST request to the server using Terminal 



curl -d "parameter1=value1&parameter2=value2" page_url

  Example:
 
  page located at http://www.formpost.com/getthis/
 
        <form action="post.cgi" method="post">
        <input name=user size=10>
        <input name=pass type=password size=10>
        <input name=id type=hidden value="blablabla">
        <input name=ding value="submit">
        </form>
 
  We want to enter user 'foobar' with password '12345'.
 
  To post to this, you enter a curl command line like:
 
curl -d "user=foobar&pass=12345&id=blablabla&ding=submit" http://www.formpost.com/getthis/post.cgi

Saturday, June 15, 2013

Find and Kill a Process that is Using a Particular Port in Ubuntu



STOP TOMCAT SERVER USING TERMINAL

1- Find what application/process is using :
sudo netstat -lpn |grep :8080
and press Enter.
You will get an output similar to this one
tcp6       0      0 :::8080                 :::*                    LISTEN      6782/java
2- I have got the process Id, which is 6782, now this is the process that is using port 8080.
3- Kill the process, type:kill 6782
kill -9 6782
and now port 8080 is free.


Friday, June 14, 2013

EventSource's response has a charset ("iso-8859-1") that is not UTF-8. Aborting the connection Error

SERVER SENT EVENTS, HTML5 AND TOMCAT 7

If you test, you can understand that there is no problem while running the project with Tomcat 6.

Yes, the problem is with Tomcat 7. It supports charset : iso-8859-1 by default.
So, we need to fix this problem with describing that we are using character encoding(charset)  UTF-8.

Change the responce.setContentType as follows:

response.setContentType("text/event-stream, charset=UTF-8");


Thats it.

Tuesday, June 11, 2013

Where is .bashrc ?

Where is .bashrc ?

Don't forget it is a hidden file inside your home directory (you would not be the first to do a ls -l and thinking it is not there).


ls -la ~/ | more


There should be a .bashrc on the first page. If not just create it with
vi ~/.bashrc


and add in the lines you need to add into it.


Permissions of my .bash.rc are


-rw-r--r-- 1 discworld discworld 3330 Mar 10 16:03 .bashrc

(chmod 644 .bashrc to make it rw r r)