Wednesday 12 September 2012

Eclipse local svn

just Right click on file

Select Compare With ---> Local history

:-) u have now local svn in eclipse





'Initializing Java Tooling' has encountered a problem in eclipse

go to the folder where your eclipse.exe or eclipse runnable file located.

and start eclipse with: eclipse -clean

Tuesday 11 September 2012

Run Class inside jar file

java -classpath <jar_file.jar> <class_in_jar_with_absolute_path>

Example:

t4acke4.jar Contents

com.example.XYZ1.class
com.example.XYZ2.class

com.example.test.PQR1.class
com.example.test.PQR2.class
com.example.test.PQR3.class

NOTE: Here com,example and test are folders or packages

Run PQR2 as:

java -classpath t4acke4.jar com.example.test.PQR2

Monday 10 September 2012

Run shellscript on Boot

Copy shellscript file to /etc/init.d/XYZ (XYZ is shellscript name)

vim /etc/init.d/XYZ and copy below two line on top of file
(Note: change value of 10 and 80 in below two lines to any random number it shoud not match with other file)

--------------------------------
#!/bin/sh
# chkconfig: 2345 10 80
--------------------------------
Then Execute below two commands:

1>chkconfig --add XYZ
2>chkconfig XYZ on



To check if added or not just execute below command
chkconfig --list | grep XYZ

Output :

XYZ 0:off 1:off 2:on 3:on 4:on 5:on 6:off 





If we wanted to turn XYZ off in run levels 3, 4, and 5, we'd use a command like this :

chkconfig --level 345 XYZ off

Create multiple objects in Java


Use of Interface in java.

Let's assume we have a Game Class and four subtypes of Game: Hockey, Cricket,Tennis,Football


public static List<Game> getInstances(Class<? extends Game> clazz, int counter)
{
    List games = new ArrayList<Game>();
    for(int i=0;i< counter; i++)
    {
        games.add(clazz.newInstance());
    }
    return games;
}

Now you can use this for creating games.

List<Hockey> hctf = Game.getInstances(Hockey.class,10);
List<Cricket> hctf = Game.getInstances(Cricket.class,10)
List<Tennis> hctf = Game.getInstances(Tennis.class,10)
List<Football> hctf = Game.getInstances(Football.class,10)

Testing your site's response time-PageSpeed,Check your site's performance


The speed of loading your site has a direct impact on the time visitors will spend on the site

Google came up with this great free project

https://developers.google.com/speed/pagespeed/insights

Content Assist (Ctrl + Space) Is Not Working in eclipse

                                   Ctrl + Space Is Not Working in eclipse


Select Preferences>Java>Editor>Content Assist



Select checkbox "Select Enable auto activation"

type .(dote) in "Auto activation triggers for java" show in image.

How to avoid javascript Error in eclipse


Select Window->Preference

Select Javascript -> validator

Select Error/Warings


Uncheck "Enable javascript semantic validation" checkbox
 

Select apply then Ok

How to get all parameters and value from URL in servlet



  Get all parameters and value from URL in Java :


public static void printRequestParameters(HttpServletRequest req) {

            Enumeration params = req.getParameterNames();
            while (params != null && params.hasMoreElements()) {
                String param = (String) params.nextElement();
                String value = req.getParameter(param);
                System.out.println(param+"="+value);
            }
}

Set JDK path in linux and create alise or shortcut in linux


How to set JDK path in linux:

STEP:1
Open kernel and paste :
vim /etc/bashrc

STEP:2
Copy following line and past at last in bashrc file.

export JAVA_HOME="/usr/src/jdk1.6.0_11"
export PATH="$JAVA_HOME/bin

STEP:3
Close all kernel and then Open.


How to create alise or shortcut in linux:

STEP:1
Open kernel and paste :
vim /etc/bashrc

STEP:2
Copy following line and past at first line in bashrc file.
alias desk='cd /root/Desktop'

STEP:3
Close all kernel and then Open.

Now, You just type desk on kernel and go to Desktop location.

Friday 7 September 2012

Convert XML to Json in java

                                          Convert XML to Json in java

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



import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class xmlToJson {

/**
* @param args
*/
public static void main(String[] args) {

try {

JSONObject jsonObj = null;

jsonObj = XML.toJSONObject("<root><priority value =\"debug\"/><appender-ref ref=\"Log\"/><appender-ref ref=\"stdout\" /> </root>");

String json = jsonObj.toString();

System.out.println("t4acke4 Response is: "+json);

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

}

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.

Friday 31 August 2012

Read xls or excel file from server and parse xls or excel file


CHANGE THIS BOLD URL WITH YOUR FILE ADDRESS WITH SERVER ADDRESS AND THEN JUST COPY PASTE THE CODE TO JAVA FILE.


NOTE : U MUST HAVE TO ADD JAR FILE TO YOUR PROJECT CLASS PATH FROM THIS http://jexcelapi.sourceforge.net/  DOWN LOAD JAR FILE FROM HERE IF JAR IS NOT AVAILABLE ON THIS URL THEN SEARCH JXL JAR AND DOWNLOAD IT.

import java.io.IOException; import jxl.Cell; import jxl.CellType; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import java.net.URLConnection; public class ReadExcel { public void read() throws IOException { java.net.URL url = new java.net.URL("http://www.XYZ.org/alphaguru.xls"); URLConnection conn = url.openConnection(); conn.setRequestProperty("Connection","Keep-Alive"); conn.setConnectTimeout(10000); System.out.println("value of sTring is:"+conn.getInputStream().toString()); Workbook w; try { w = Workbook.getWorkbook(conn.getInputStream()); // Get the first sheet Sheet sheet = w.getSheet(0); // Loop over first 10 column and lines for (int j = 0; j < sheet.getColumns(); j++) { for (int i = 0; i < sheet.getRows(); i++) { Cell cell = sheet.getCell(j, i); if (cell.getType() == CellType.LABEL) { System.out.println("I got a label "+ cell.getContents()); } if (cell.getType() == CellType.NUMBER) { System.out.println("I got a number "+ cell.getContents()); } } } } catch (BiffException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { ReadExcel test = new ReadExcel(); test.read(); } }

Difference between Hibernate createCriteria, createQuery, createSQLQuery function

To create query in the Hibernate ORM framework, there is three different types. The following are the three ways to create query instance: - session.createQuery() - session.createSQLQuery() - session.createCriteria() look into the details of each category in detail. session.createQuery() The method createQuery() creates Query object using the HQL syntax. Fro example Query query = session.createQuery("from Student s where s.name like 'k%'"); session.createSQLQuery() The method createSQLQuery() creates Query object using the native SQL syntax. Fro example Query query = session.createQuery("Select * from Student"); session.createCriteria() The method createCriteria() creates Criteria object for setting the query parameters. This is more useful feature for those who don't want to write the query in hand. You can specify any type of complicated syntax using the Criteria API. Criteria criteria = session.createCriteria(Student.class);

Thursday 30 August 2012

com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException

Problem

Connection refused :
com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused
 
 ...
 
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
 at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
 at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
 at java.lang.Thread.run(Thread.java:679)

Solution

- Check your port number.
- Start your service.

java.lang.ClassCastException: java.util.Collections$SynchronizedMap

Problem

private static HashMap<String, Long> orderProcessmap = null;
orderProcessmap =  Collections.synchronizedMap((new HashMap<String, Long>()));
java.lang.ClassCastException: java.util.Collections$SynchronizedMap cannot be cast to java.util.HashMap
 at .......org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
 at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
 at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
 at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5015)
 at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5302)
 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
 at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)
 at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)
 at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
 at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:962)
 at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1603)
 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
 at java.util.concurrent.FutureTask.run(FutureTask.java:166)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
 at java.lang.Thread.run(Thread.java:679)

Solution

private static Map<String, Long> map = null;
map =  Collections.synchronizedMap((new HashMap<String, Long>()));

Wednesday 29 August 2012

Java.Lang.ClassNotFoundException : Javassist.Util.Proxy.MethodFilter

Problem

Using Hibernate 3.6.3, but hits this javassist not found error, see below for error stacks :
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter
 ...
 at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
 ... 16 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter
 at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
 at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
 ... 21 more

Solution

javassist.jar is missing,