Friday, 7 September 2012

How to Convert POJO TO Json String

                       Convert POJO tO Json String


Download Jar: https://www.box.com/s/vm59rumsblk4p25kim8f


Create Pojo  class in  your project  :

/**
* @author t4ecke4
*/
public class Person {

private String name;
private Integer age;

public String getName() { return this.name; }
public void setName( String name ) { this.name = name; }

public Integer getAge() { return this.age; }
public void setAge( Integer age ) { this.age = age; }

}


Create Main method as show below:



import org.json.JSONObject;

public class PojoToJson {

/**
* @author t4ecke4
*/
public static void main(String[] args) {
Person person = new Person();
person.setName( "Person Name" );
person.setAge( 666 );

JSONObject jsonObj = new JSONObject( person );
System.out.println( jsonObj );

}

}

When you execute  this project  output is:

Output: {"age":666,"name":"Person Name","class":"class Person"}

log4j configuration in java

                                          log4j integration in java


Reference : http://logging.apache.org/log4j/2.x/

Download Code: https://www.box.com/s/1o9mntoqokk793hy28sx

log4j.xml


create log4j.xml in your source (src) folder:
(Not in any package)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss,SSS}[%5p]%t:%C:%6L- %m%n"/>
</layout>
</appender>
<appender name="grp" class="org.apache.log4j.RollingFileAppender">
<param name="threshold" value="ALL"/>
<param name="File" value="test.log"/>
<param name="MaxFileSize" value="10MB"/>
<param name="MaxBackupIndex" value="10"/>
<param name="Encoding" value="UTF-8" />
<param name="Append" value="true"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss,SSS 'UTC'Z}[%5p]%-25c{5}:%L- %m%n"/>
</layout>
</appender>


<logger name="com.t4acke4.logger">
<level value="ALL" />
</logger>


<root>
<level value="ALL"/>
<appender-ref ref="grp"/>
</root>

</log4j:configuration>



Create com.t4acke4.logger package in your project and create LoggerIntegration.java file in package and past following code :
package com.t4acke4.logger;

import org.apache.log4j.Logger;

public class LoggerIntegration {

private static Logger log = Logger.getLogger(LoggerIntegration.class);
/**
* @auther t4acke4
*/
public static void main(String[] args) {

log.debug("ohhh logger is done...");
}

}

when you run your project create test.log file in your project .

Thursday, 6 September 2012

Convert Hashmap to Json in Java

                      Convert Hashmap to Json in Java

Download Jar :
https://www.box.com/s/r2jq0r0ado5tth9k1bef

Download Link:
https://www.box.com/s/94j60nz6lz3yoboicn4y
 

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;

/**
* @auther t4acke4
*/
public class HashmapToJson {
/**
* @param args
* @throws JSONException
*/
public static void main(String[] args) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "Jay");
map.put("age", "21");
map.put("city", "Ahmedabad");

HashMap<String, Object> map1 = new HashMap<String, Object>();
map1.put("map", map);
map1.put("sex", "male");

convertMapToJson(map1);
}
/*
* convert Map to Json
*/
public static void convertMapToJson(Map map)throws JSONException{

JSONObject obj = new JSONObject();
JSONObject main = new JSONObject();
Set set = map.keySet();

Iterator iter = set.iterator();

while (iter.hasNext()) {
String key = (String) iter.next();
obj.accumulate(key, map.get(key));
}
main.accumulate("data",obj);

System.out.println("JSON : "+main.toString());
}

}

Convert List to Json in java

                          Convert ArrayList to Json in java


Download Jar :
https://www.box.com/s/r2jq0r0ado5tth9k1bef

Download Link:
https://www.box.com/s/edb4kd7n3oqmnveg0lei
 

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class ListToJson {
public static void main(String[] args) throws JSONException {
List<String> list = new ArrayList<String> ();
list.add("Jay");
list.add("Hiren");
list.add("Jignesh");

convertListToJson(list);
}

public static void convertListToJson(List<String> list) throws JSONException{

int size = list.size();

JSONArray obj = new JSONArray();
JSONObject main = new JSONObject();

for(int i=0 ; i<size ; i++){
obj.put(i);
}
main.accumulate("data", obj);

System.out.println(main.toString());

}
}

Tuesday, 4 September 2012

Restlet Webservices Hello World

Restlet Webservices Hello World:


Download Code:
https://www.box.com/s/88ttn0jod0hhr9727e3b

STEP 1: CREATE Java Project with name helloWorld
STEP 2: Create Packages(same name as given below)

1> com.rest.api
2> com.rest.app
3> com.rest.db
4> com.rest.resource
STEP 3: Creat class helloWorld.java in com.rest.api package

package com.rest.api;

import java.io.Serializable;

public class helloWorld implements Comparable<helloWorld>, Serializable {

private static final long serialVersionUID = 1l;

protected String result = "";

public String getResult() {
return result;
}

public void setResult(String result) {
this.result = result;
}

public String toString() {
return result;
}

@Override
public int compareTo(helloWorld o) {
// TODO Auto-generated method stub
return 0;
}

}
STEP 4: Create class WebServiceApplicationOpenSER.java in com.rest.app package

package com.rest.app;

import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Restlet;
import org.restlet.Router;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.StringRepresentation;

import com.rest.resource.helloWorldResource;

public class WebServiceApplicationOpenSER extends Application {

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


// Create a component
Component component = new Component();
// PVN: Changed default port so we can run this service on the
// same machine as the default web service
component.getServers().add(Protocol.HTTP, 8100);
component.getClients().add(Protocol.FILE);

WebServiceApplicationOpenSER application = new WebServiceApplicationOpenSER();

// Disable the logger for the web service
component.getLogService().setEnabled(false);

System.out.println("hello world start");

component.getDefaultHost().attach(application);
// Attach the application to the component and start it
component.start();
}

@Override
public Restlet createRoot() {

Router router = new Router(getContext());

// The helloWorld resource
router.attach("/hello",helloWorldResource.class);

Restlet mainpage = new Restlet() {
@Override
public void handle(Request request, Response response) {
StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append("<html>");
stringBuilder
.append("<head><title>Application Login Openser Sample Page</title></head>");
stringBuilder.append("<body bgcolor=white>");

stringBuilder.append("<table border=\"0\">");
stringBuilder.append("<tr>");
stringBuilder.append("<td>");
stringBuilder.append("<h1>Login Openser Web Service - REST</h1>");
stringBuilder.append("</td>");
stringBuilder.append("</tr>");
stringBuilder.append("</table>");
stringBuilder.append("</body>");
stringBuilder.append("</html>");
response.setEntity(new StringRepresentation(stringBuilder
.toString(), MediaType.TEXT_HTML));
}
};
router.attach("", mainpage);
return router;
}

}
STEP 5: Create class helloWorldDAO.java in com.rest.db package

package com.rest.db;

import com.rest.api.helloWorld;

public class helloWorldDAO {

//create all database related code here
//u can create select delete update and insert query also

public helloWorld find(){

helloWorld hw = null;
try{
hw = new helloWorld();

hw.setResult("Hello Darling");
}catch(Exception e){
e.printStackTrace();
}
return hw;
}
}
STEP 6: Create class helloWorldResource.java in com.rest.resource package


package com.rest.resource;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import com.rest.api.helloWorld;
import com.rest.db.helloWorldDAO;

public class helloWorldResource extends Resource{

private helloWorld _hw = null;

public helloWorldResource(Context context, Request request, Response response){
super( context, request, response );
String id = null;

id = (String) getRequest().getAttributes().get("id");

_hw = find();

getVariants().add(new Variant(MediaType.TEXT_PLAIN));
}

private helloWorld find(){
try{

helloWorldDAO dao = new helloWorldDAO();
return dao.find();

}catch (Exception e ){
return null;
}
}


@Override
public Representation represent(Variant variant) throws ResourceException {
Representation result = null;
if (_hw == null) {
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);

result = new StringRepresentation("Error in Display");

return result;
}else{
result = new StringRepresentation(_hw.toString());
}
return result;
}


}
STEP 7: Create jar file

-----> select File -----> Export -----> select Java -----> select Runnable JAR file -----> NEXT -----> select helloWorld project in Launch Configuration ----->
Give Export Destination With File name helloWorld.jar-----> Select Library Handling: Package Required libraries into generated JAR -----> Finish
STEP 8: Extract jar file (in current folder)
STEP 9: EXPORT CLASSPATH (as par below image)

NOTE: In place of /root/Desktop/ give your jar file path

CLASSPATH=$JAVA_HOME/lib/rt.jar
CLASSPATH=$CLASSPATH:/root/Desktop/helloWorld.jar
CLASSPATH=$CLASSPATH:/root/Desktop/helloWorld/com.noelios.restlet.ext.servlet_2.5.jar
CLASSPATH=$CLASSPATH:/root/Desktop/helloWorld/com.noelios.restlet.ext.simple_3.1.jar
CLASSPATH=$CLASSPATH:/root/Desktop/helloWorld/com.noelios.restlet.jar
CLASSPATH=$CLASSPATH:/root/Desktop/helloWorld/org.restlet.ext.fileupload_1.2.jar
CLASSPATH=$CLASSPATH:/root/Desktop/helloWorld/org.restlet.ext.json_2.0.jar
CLASSPATH=$CLASSPATH:/root/Desktop/helloWorld/org.restlet.jar
CLASSPATH=$CLASSPATH:/root/Desktop/helloWorld/org.simpleframework.jar

java -classpath $CLASSPATH com.rest.app.WebServiceApplicationOpenSER

Expected output: hello world start
STEP 10: HOW TO RUN(type this command in your command prompt)

GET curl -X GET http://localhost:8100/hello

Expected output: Hello Darling

Monday, 3 September 2012

How to execute shell script using java


Execute shell script using  Java :


Reference API :
 http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html

Download Link:
https://www.box.com/s/0gkhha9zgblmr31caa3s
 
import java.io.File;

public class ExecuteShellScript {

// execute shell script from java

public static void main(String[] args) {

File wd = new File("/root/Desktop/");
System.out.println("Working Directory: " +wd);
Process proc = null;

try {

proc = Runtime.getRuntime().exec("sh shell.sh", null, wd);
System.out.println("Process : "+proc);

}
catch (Exception e) {
e.printStackTrace();
}

}

}

How To Get All Selected Checkbox Values

NOTE: You can get all selected checkbox values on button click using this function just add the functioni on buttonclick event.
function getSelectedCheckboxValue(){

var messageList = [];

var checkboxId = new Array();
var checkboxIdValue = new Array();

var unescapevalue = "";



$("input[type='checkbox']:checked").each(

function() {
checkboxId[i] = $(this).val();
checkboxIdValue[i] = $(this).attr('id');
unescapevalue = unescape(checkboxId[i])+"||||||";
i++;
messageList.push(unescapevalue);
}
);



alert("messageList: "+messageList);

}

//here in message list array u can get value of checkbox which are selected.