IT Certificaions

Google Cloud Platform

Wednesday, December 21, 2011

Get real client ip-address using java / getRemoteAddr() is giving 127.0.0.1 as client ip address in java


Getting real client ip-address using java (if Apache redirection is used...)
--------------------------------------------------------------------------
You can use ,
    String ipAddress=request.getHeader("X-Forwarded-For");
 if you have configured Apache redirection.
-------------------------------------------------------------------------

If you will use
     request.getRemoteAddr(), it may return 127.0.0.1 if apache redirection has been configured at your deployment server.



Tuesday, December 20, 2011

JDBC: Prepared Statement


Prepared Statement Demo using Java/MySQL
------------------------------------------------
package com.vicwalks.web.util;


import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


import com.mysql.jdbc.Connection;


public class PreparedStatementDemo {
 public static void main(String[] args) {
 System.out.println("===========Prepared statement demo===========\n");
 Connection con = null;
 PreparedStatement preparedStatement;
 try{
   Class.forName("com.mysql.jdbc.Driver");
   con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASENAME","userName","password");
   try{
      String sql = "SELECT * FROM employee WHERE salary >= ?";
      preparedStatement = con.prepareStatement(sql);
      preparedStatement.setInt(1,10000);
      ResultSet rs1 = preparedStatement.executeQuery();
      System.out.println("List of employee where salary >= 10000");
      System.out.println("empId" + "\t- " + "empName"+ "\t- " +"salary");
      System.out.println("=============================================\n");
      while (rs1.next()){
        String empId = rs1.getString(1);
        String empName = rs1.getString(2);
        int salary = rs1.getInt(3);
        System.out.println(empId + "\t- " + empName+ "\t- " +salary);
      }
 
      System.out.println("=============================================\n");
      
      preparedStatement.setInt(1,15000);
      ResultSet result2 = preparedStatement.executeQuery();
      System.out.println("List of employee where salary >= 15000");
      System.out.println("empId" + "\t- " + "empName"+ "\t- " +"salary");
      System.out.println("=============================================\n");
      while (result2.next()){
        String empId = result2.getString(1);
        String empName = result2.getString(2);
        int salary = result2.getInt(3);
        System.out.println(empId + "\t- " + empName+ "\t- " +salary);
      }
 
      System.out.println("=============================================\n");
 
 
     }
     catch (SQLException s){
          System.out.println("SQL statement is not executed!");
     }
  }
  catch (Exception e){
       e.printStackTrace();
  }
}
 }


where userName: MySql user name, for example : root
          Password: MySql password


Output

 ===========Prepared statement demo===========


List of employee where salary >= 10000
empId - empName - salary
=============================================


001 - Anuj Kumar - 12000
003 - Amit Kumar - 11000
005 - Ajay Bisht - 18000
=============================================


List of employee where salary >= 15000
empId - empName - salary
=============================================


005 - Ajay Bisht - 18000
=============================================

Monday, December 19, 2011


Get <td> element value inside a <table>

1) Using JQuery.....

$('#tableDivId tr').each(function() {
    var tdText = $(this).find("td:first").html();    
});

Here you are iterating all rows of a table according to given div id, and then you are fetching first <td> element data for current <tr>....


2) Without JQuery...............

function loadAllTDs(){
var table = document.getElementById('tableDivId'); 
var rows = table.getElementsByTagName('tr');
var cells, tdText;

for (var i = 0, j = rows.length; i < j; ++i) {
      cells = rows[i].getElementsByTagName('td');
      if (!cells.length) {
         continue;
      }
      tdText = cells[0].innerHTML;  // For 0th td for each tr of this table....
      alert(tdText);    
    }
}

Tuesday, December 13, 2011

Executing FQL Queries :: FacebookResponseStatusException


com.restfb.exception.FacebookResponseStatusException: Received Facebook error response (code 601): Parser error: SELECT * is not supported.  Please manually list the columns you are interested in.
com.restfb.BaseFacebookClient$DefaultLegacyFacebookExceptionMapper.exceptionForTypeAndMessage(BaseFacebookClient.java:147)
com.restfb.BaseFacebookClient.throwLegacyFacebookResponseStatusExceptionIfNecessary(BaseFacebookClient.java:208)
com.restfb.DefaultFacebookClient.throwFacebookResponseStatusExceptionIfNecessary(DefaultFacebookClient.java:523)
com.restfb.DefaultFacebookClient.makeRequestAndProcessResponse(DefaultFacebookClient.java:485)
com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:445)
com.restfb.DefaultFacebookClient.executeQuery(DefaultFacebookClient.java:366)
com.vicwalks.web.util.SocialMediaUtil.findFacebookFriendsUsingRest(SocialMediaUtil.java:84)
com.vicwalks.web.action.FacebookConnectAction.execute(FacebookConnectAction.java:87)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)



Solution: You can use SELECT * FROM ... here to fetch User class data on the basis of id.

Please use the column name that you want to fetch, see User class:

id,  name,  about, bio, birthday, email, firstName, lastName, gender, location  etc........


String query = "SELECT uid, name FROM user WHERE uid=220439 or uid=7901103";
List<FqlUser> users = facebookClient.executeQuery(query, FqlUser.class);


System.out.println("Users: " + users);

...

// Be aware that FQL fields don't always map to Graph API Object fields.

public class FqlUser {
  @Facebook
  String uid;
  
  @Facebook
  String name;


  @Override
  public String toString() {
    return String.format("%s (%s)", name, uid);
  }
}

===> For more, visit the RESTFB API

get facebook friends using restfb

If you are using restfb (Facebook graph API and old REST API client wriiten in Java), and you want to access all friend list after Oauth authentication, you can use following method,



public List<ArrayList> findFacebookFriendsUsingRest(String facebookAccessToken){
  List<ArrayList> myFacebookFriendList= new ArrayList();
  final FacebookClient facebookClient;
  facebookClient = new DefaultFacebookClient(facebookAccessToken);
  User user = facebookClient.fetchObject("me", User.class);
  String userName = user.getFirstName();
  if (userName == null){
  userName = user.getLastName();
  }
  String userEmail = user.getEmail();
  com.restfb.Connection<User> myFriends = facebookClient.fetchConnection("me/friends", User.class);
  System.out.println("Count of my friends: " + myFriends.getData().size());
  for(User friend: myFriends.getData()){
  System.out.println("Friends id and name: "+friend.getId()+" , "+friend.getName());
    myFacebookFriendList.add(friend.getName());
  }
  System.out.println("All Friends : "+myFacebookFriendList);
}




Wednesday, December 7, 2011

Android: MapActivity can not be resolved in android

For Eclipse users:

Please click on Project --> properties-->Resources-->Android--> Select Google api instead of Android

Now click on Ok.

Check again, Project--> properties--> Java build path, see the Libraries tab, expand Google APIs, and see if there is map.jar and android.jar are available or not. They must be.

Now clean your project and then run your project.


Tuesday, December 6, 2011

Android: where to run keytool command in android

Keytool command can be run at your dos command prompt, if JRE has been set in your  classpath variable.

For example, if you want to get the MD5 Fingerprint of the SDK Debug Certificate for android,

just run the following command...


C:\Documents and Settings\user\.android>  keytool -list -alias androiddebugkey  
                                                                -keystore debug.keystore -storepass android -keypass android


where C:\Documents and Settings\user\.android> is the path which consist the debug.keystore that has to be certified.





Android: MapActivity is not found

MapActivity is a special sub-class of  android.app.Activity. 


If you are using eclipse id, then click on AVD Manager and then it will show you the list of installed as well as un-installed packages. Select Google api packages and click on install. Then you will not this problem. if it is still set java build path


Now if this problem still occurs, see your build path... http://knowledge-serve.blogspot.com/2011/12/android-mapactivity-can-not-be-resolved.html 

Wednesday, November 30, 2011

multiple checkboxes with same id


Handling multiple checkboxes with same id's


If suppose you have defined more than one checkboxes with sdame id's, then it will treat it as an array of names.

<form name="CheckBoxForm">


<input type="Checkbox" name="myCheckbox" id="myCheckbox"  />
<input type="Checkbox" name="myCheckbox" id="myCheckbox"  />
<input type="Checkbox" name="myCheckbox" id="myCheckbox"  />
<input type="Checkbox" name="myCheckbox" id="myCheckbox"  />
<input type="" onclick="testCheckboxes()" />
</form>


Now according to HTML, id must be unique. So here it will treat them like an array. So if you want to access them, do as
given here,


function testCheckboxes(){
var myCheckboxArray= new Array();
var total=document.getElementsByName('myCheckbox').length;
for(var i=0;i<total;i++){
 alert(document.getElementsByName('myCheckbox')[i].checked);
 if(document.getElementsByName('checkbox')[i].checked == true){
 myCheckboxArray[myCheckboxArray.length]="Checked";
 }
    }

}

Tuesday, November 29, 2011

Email address validation at client and server side



Email validation at client side(Java Script)
---------------------------------------------
function validateEmailAddress(emailAddress) { 
    var expression = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;


    return expression.test(email);
}

This function will return true if it is a valid email address otherwise false if it is invalid email address.
----------------------------------------------



Email validation at server side using Java

-----------------------------------------------
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailAddressValidator{

 private Pattern pattern;
 private Matcher matcher;

 private static final String EMAIL_ADDRESS_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

 public EmailAddressValidator(){
 pattern = Pattern.compile(EMAIL_ADDRESS_PATTERN);
 }

 public boolean validate(final String emailId){ 
 matcher = pattern.matcher(emailId);
 return matcher.matches();

 }
 public static void main(String [] arg){
 String emailId="abc@yahoo.com";  
 EmailAddressValidator validatorObj=new EmailAddressValidator();
 System.out.println("-validate email address:"+emailId+": ---is it proper email:"+validatorObj.validate(emailId));
         
 emailId="abc @";
 System.out.println("-validate email address:"+emailId+": ---is it proper email:"+validatorObj.validate(emailId));
 
 }
}
--------------------------------------------
At server side you can use this class as a utility class and use wherever you want.

Monday, November 28, 2011

Scrolable div in CSS/html


Scrolable DIV:

overflow: auto   => It will create a scrollbar - horizontal, vertical or both only if the content in the block
                    requires it.

overflow: scroll => It will will insert horizontal and vertical scrollbars. They will become active and shown
                    only if the content requires it.

overflow: visible => It will cause the content of the block to expand outside of it and be visible at the same time.

overflow: hidden =>  This forces the block to only show content that fits in the block. Remainng content will
                                  be  clipped and not visible to you. There will be no scrollbars.
For ex:
<div class="scrolableDiv"....></div>

where in CSS class:
.scrolableDiv{  
height:180px;
    overflow:scroll; 
    margin-left: 170px;
    margin-top: -100px;
    width: 600px; 
}

Accessing parent window form from child window in html


Accessing parent window form from child window in html

window.parent.document.parentFormName.submit();

Here parentFormName is the name of Form of parent window that you want to submit from child window.
Ex, <form name="parentFormName".....>


Accessing parent window's form input parameters to child window,

var userName= window.parent.document.getElementById('userName').value;

Here userName is the id element of input field on parent form.
Ex.
    <form name="parentFormName".....>
<input type="text" id="userName" />
</form>
---------------------------------------------------------------------------------------------------------------

Thursday, November 24, 2011

Get contact list from Gmail account using java

You can get all contacts exists in your gmail account using this program...

First you will need the jar file gdata (library files for fetching data from google)...
---------------------------------------------------------------------------------
public static  List<ContactDTO> getAllGmailContacts(String gmailId,String password)
throws ServiceException, IOException {
    
InstrumentDTO contactDTO;
String name;
List<ContactDTO> myGmailContactList= new ArrayList<ContactDTO>();

ContactsService myService = new ContactsService("Find_Contacts_On_Gmail");
myService.setUserCredentials(gmailId, password);


    URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/"+gmailId+"/full");


   
    ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);  
   
    for (int i = 0; i < resultFeed.getEntries().size(); i++) {
       ContactEntry entry = resultFeed.getEntries().get(i);
       System.out.println("\t" + entry.getTitle().getPlainText());
       name=entry.getTitle().getPlainText();
  
       for (Email email : entry.getEmailAddresses()) {  
  
    System.out.println("Friend Name:"+name+" and emailAddress:"+email.getAddress());


         if(name != null && name.trim().length()>0){
           contactDTO=new InstrumentDTO(name, email.getAddress());
         }else{
           contactDTO=new InstrumentDTO(email.getAddress(), email.getAddress());
         }
         myGmailContactList.add(contactDTO);
       }
       LogManager.info(this, resultFeed.getTitle().getPlainText()+" list size (Gmail contact list):"+myGmailContactList.size());  
   }
    return myGmailContactList;
}

-------------------------------

public class ContactDTO {


private String key;
private String value;

public ContactDTO() {

}
public ContactDTO(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}

public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ContactDTO [key=").append(key).append(", value=")
.append(value).append("]");
return builder.toString();
}


}

-------------------------------------------------------------

Iterate this ContactDTO list on jsp using following code.....


<table>
   <s:if test="myGmailContactList!=null">
       <tr bgcolor="red" bordercolor="RED">
           <td>Friend Name</td>
           <td>Email Address</td>
       </tr>
       <s:iterator value="myGmailContactList" >
         <tr><td><s:property value="key" /></td>
             <td><s:property value="value" /></td>
         </tr>
       </s:iterator>
   </s:if>
  </table> 
-----------------------------------------------------------------




For complete code send mail to us..............

Wednesday, November 23, 2011

Set Alarm watch using Swing

Here you can set the alarm using swing, see the code here
------------------------------------------------------------
package example.alarm;


import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.swing.*;

class AlarmDemo extends Thread{
private JLabel timeLabel;
public AlarmDemo(JLabel label){
   this.timeLabel=label;}
   
    public void run(){
      while(true){
         Date d=new Date();
         int h=d.getHours();
         String time="PM";
         if (h>23){h-=24; time="AM";}
         timeLabel.setText(""+h+":"+d.getMinutes()+":"+d.getSeconds()+"  "+time);
         try{Thread.sleep(1000);}
 catch(Exception e){}
      }
         }

}


class Timer implements Runnable{
private JLabel timeLabel;
private JLabel alarmTime;
public Timer(JLabel label){
   this.timeLabel=label;}
   
    public void run(){
      while(true){
         Date d=new Date();
         timeLabel.setText(d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
         
         System.out.println("current time:"+timeLabel.getText()+" And alarmed time:"+alarmTime.getText());
         if(timeLabel.getText().equals(alarmTime.getText())){
         JOptionPane.showMessageDialog(null,"Please walk up: The time is :"+timeLabel.getText());
         }
         try{Thread.sleep(1000);}
 catch(Exception e){}
      }
     }

public void setAlarmTime(JLabel alarmTime) {
this.alarmTime = alarmTime;
}

public JLabel getAlarmTime() {
return alarmTime;
}

}

class CounterSeconds implements ActionListener {
    private int counter;
    private JFrame timerFrame=new JFrame();
    private JLabel label1=new JLabel("              ");
    private JLabel label2=new JLabel("              ");
    private JLabel label4=new JLabel("              ");
    private JLabel label5=new JLabel("ALARM");   
    private JLabel hour=new JLabel("HH:");
    private JLabel minute=new JLabel("MM:");
    private JLabel second=new JLabel("SS:");
    private JLabel alarmTimeLabel=new JLabel("            ");
    private JTextField alarmDateNew=new JTextField(8);
    private JTextField hh=new JTextField(5);
    private JTextField mm=new JTextField(5);
    private JTextField ss=new JTextField(5);
    private Font fnt=new Font("TimesNewRoman",Font.BOLD,16);
    private JButton b1=new JButton("STOP");
    private JButton b2=new JButton("RESTART");
    private JButton alarmButton=new JButton("set alarm");
    final JComponent[] inputs;
    public static final String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
    public static String dt;
    public static String currentDate;
    public static String currentTime;
    JTextField alarmDate ;
JTextField alarmTime ;
    static Thread t5;
    static Thread t6;
    AlarmDemo t1;
    
    CounterSeconds(){
           Date date= new Date();
                currentDate=date.getDay()+"-"+date.getMonth()+"-"+date.getYear();
                currentTime=date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
                alarmDate = new JTextField(currentDate);
             alarmTime = new JTextField(currentTime);
     
              inputs = new JComponent[] {
                     new JLabel("Date(DD-MM-YYYY)::"),
                     alarmDate,
                     new JLabel("Time(HH:MM:SS)::"),
                     alarmTime,
     
             };
           counter=0;
                Container c=timerFrame.getContentPane();
          label1.setFont(fnt); label2.setFont(fnt);
          label4.setFont(fnt);
          alarmTimeLabel.setFont(fnt);
          label1.setText("Counter:  "+0);
          timerFrame.setLayout(new FlowLayout());
timerFrame.setSize(160,180);
c.add(label1);   c.add(label2);
c.add(label4);
c.add(b1);c.add(b2);
c.add(alarmButton);
c.add(label5);
c.add(alarmDateNew);
c.add(hour);c.add(hh);
c.add(minute);c.add(mm);
c.add(second);c.add(ss);
c.add(alarmTimeLabel);
b1.addActionListener(this);b2.addActionListener(this);
alarmButton.addActionListener(this);
timerFrame.setVisible(true); }
    
    public void actionPerformed(ActionEvent e){
   Object target=e.getSource();
   if(target==b1){t5.suspend();
                  t1.suspend();}
   if(target==b2){t5.resume();}
   if(target==alarmButton){
  JOptionPane.showMessageDialog(null, inputs, "Set Alarm", JOptionPane.PLAIN_MESSAGE);
  alarmDateNew.setText(alarmDate.getText());
  alarmTimeLabel.setText(alarmTime.getText());
String [] time=alarmTime.getText().split(":");
hh.setText(time[0]);
mm.setText(time[1]);
ss.setText(time[2]);
try {
// new TimeDemo().run();
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println("Here is exception:"+e1.getMessage());
e1.printStackTrace();
}
 }
 
    }
    public static String DateTime(){
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        return sdf.format(cal.getTime());
    }
    
     public JLabel readLabel2(){return label2;}
     public JLabel readLabel3(){return label4;}
     public JLabel readLabel4(){return alarmTimeLabel;}
     
      public void display(){
while(counter <100)
       { counter++;
label1.setFont(fnt);
label1.setText("Counter:  "+counter);
// System.out.println("Current time:"+this.readLabel2());
          try{Thread.sleep(1000);}
catch(Exception e){}
 }
         }
      
      public void start_thread(){
          Timer t=new Timer (this.readLabel2());
          t1=new AlarmDemo (this.readLabel3());         
          t.setAlarmTime(this.readLabel4());          
          t5=new Thread(t);
          t1.start();
          t5.start();          
          
      }

      public static void main(String[] args) {
                     CounterSeconds c=new CounterSeconds();
                     c.start_thread();

                c.display();
      }
 }

Tuesday, November 22, 2011

Sarkari Jobs , Public Sector Jobs , IT Jobs , Pharma Jobs , Defence Jobs: Fresher-Hiring-201-Passed-out

Sarkari Jobs , Public Sector Jobs , IT Jobs , Pharma Jobs , Defence Jobs: Fresher-Hiring-201-Passed-out: Hiring Fresher Hiring Fresher - BE\Btech(2011 passed out), Preferable _ ERP Knowledge, Contact at jobs@3leads.com \ sudha@3leads.com

CSS problems: Add a vertical line on a page

You can add a line separator using div ....

.line_seperator{   
    border-left: 2px solid #B1B1B1;
    height: 150px;
    margin-left: 150px;
    margin-top: -35px;
    width: 2px;
}
Here border-left: will add a line.. Even you can use border-right, border-top and border-bottom and then you can arrange your the width of your div.

Monday, November 21, 2011

Swing-Java: Get current date and time using swing

Here is the example where you can get current time and date using frame in swing


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;




public class DateTimeDemo extends JFrame implements ActionListener{
   public static final String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
   public static String dt;
  
   JTextField dateField= new JTextField(20);
   JButton jb=new JButton("Submit");


   public DateTimeDemo() {
     super("Current date and time demo");
     JLabel label1 = new JLabel(" Your current time: ");
     
   
       


     JPanel contentPane = new JPanel(new FlowLayout());
     contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
     contentPane.add(label1);
     contentPane.add(dateField);
     contentPane.add(jb);
     
     jb.addActionListener(this);


     getContentPane().add(contentPane);
   }


  public void actionPerformed(ActionEvent e) {


     String date = DateTime();
     dateField.setText(date);
     
     JOptionPane.showMessageDialog(null,"Current date and time: "+date+"!");
       
   }




   public static void main(String[] argv) {
         DateTimeDemo f = new DateTimeDemo();
         f.setSize(300,200);
         f.setLocation(200,200);
         f.setDefaultCloseOperation( EXIT_ON_CLOSE );
         f.setVisible(true);
   }


   public static String DateTime(){
     Calendar cal = Calendar.getInstance();
     SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
     return sdf.format(cal.getTime());
   }



 }

Monday, November 14, 2011

Remove table row using JQuery


If you are using JQuery and you have created a table and you want to delete it's row dynamically then you can use following code.


$(document).ready(function() {
    $("#DemoTable tr").click(function() {
            $(this).remove();
        });
});

Here DemoTable is the html Id attribute. So when you will click on the div containing particular row, it will be deleted.
For example if you are using table like..

<table id="DemoTable" >
<tr> 
   <td  width="25%"> </td>
   <td  width="75%"> </td>
</tr>
<tr> 
   <td  width="25%"> </td>
   <td  width="75%"> </td>
</tr>
</table>

Thursday, November 10, 2011

Create pdf with image using java


import java.io.FileNotFoundException;
import java.io.FileOutputStream;


import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;


public class GeneratePDFWithImageDemo {
  public static void main(String[] args) {
         new GeneratePDFWithImageDemo().createPDF();
  }


  public void createPDF(){
 Document document = new Document();
      try {
        PdfWriter.getInstance(document, 
        new FileOutputStream("C://Test.pdf"));
        document.open();
        PdfPTable table = new PdfPTable(1); //1 column.    
        Image image = Image.getInstance("C://Image/MyImage.jpg");
   image.scaleToFit(800f, 600f);
        image.scaleAbsolute(800f,600f);   // Give the size of image you want to print on pdf
PdfPCell nestedImgCell=new PdfPCell(image);
table.addCell(nestedImgCell);
        document.add(table);
        document.close ();
      }catch (FileNotFoundException e) {
           e.printStackTrace();
      } catch (DocumentException e) {
           e.printStackTrace();
      }catch (Exception e) {
           e.printStackTrace();
      }
      System.out.println("======== PDF Created Successfully =========);
   }
}

Wednesday, November 9, 2011

Information-Window: Basic Java Syntax and Rules

Information-Window: Basic Java Syntax and Rules: Basic Java Syntax If we talk about the Java syntax, Than a basic will cover a Object name referring to an instance with a dot o...

Tuesday, November 8, 2011


If you want to change the div background then use,

document.getElementById("divIdName").style.background='#D6DE26';

Similarly, you can change div's text color dynamically using as
 document.getElementById("DivIdName").style.color='#00AEEF';


Thursday, November 3, 2011

Hibernate property value Exception


org.hibernate.PropertyValueException: not-null property references a null or transient value: com.example.server.beans.User.createdOn
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:72)
at org.hibernate.event.def.DefaultFlushEntityEventListener.scheduleUpdate(DefaultFlushEntityEventListener.java:270)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:128)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at com.example.persistence.dao.impl.HibernateBaseDAO.saveObject(HibernateBaseDAO.java:88)
at com.example.persistence.dao.impl.RegisterUserDAO.saveRegisteredUser(RegisterUserDAO.java:21)
at com.example.web.service.impl.UserService.updateUserProfile(UserService.java:196)
at com.example.web.action.UserProfileAction.execute(UserProfileAction.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:306)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
......
......
......
......
Explanation: Please check the values you are sending to update table (all not null field mapped from table to hbm file must not get null values)