Monday 24 September 2012

Date and Time Conversion using java

Convert one Date format to Another Date format using java.
 
 
 
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class ConversionExamplesDate {

  // Convert from String to date
  private void stringToDate() {
    
    try {
      Date date1;
      date1 = new SimpleDateFormat("MM/dd/yy").parse("05/18/05");
      System.out.println(date1);
      Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse("05/18/2007");
      System.out.println(date2);
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }

  // Convert from millisecs to a String with a defined format
  private void calcDate(long millisecs) {
    SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
    Date resultdate = new Date(millisecs);
    System.out.println(date_format.format(resultdate));
  }
  
  private void writeActualDate(){
    Calendar cal = new GregorianCalendar();
    Date creationDate = cal.getTime();
    SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
    System.out.println(date_format.format(creationDate));
  }
  

  public static void main(String[] args) {
    ConversionExamplesDate convert = new ConversionExamplesDate();
    convert.stringToDate();
    convert.calcDate(System.currentTimeMillis());
    convert.writeActualDate();
  }
} 

Display Year Month and Day using GregorianCalendar java

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarTest {
  public static void main(String[] args) {
    // Constructor allows to set year, month and date
    Calendar cal1 = new GregorianCalendar(2008, 01, 01);
    // Constructor could also be empty
    // Calendar cal2 = new GregorianCalendar();
    // Change the month
    cal1.set(Calendar.MONTH, Calendar.MAY);

    System.out.println("Year: " + cal1.get(Calendar.YEAR));
    System.out.println("Month: " + cal1.get(Calendar.MONTH));
    System.out.println("Days: " + cal1.get(Calendar.DAY_OF_MONTH) + 1);

    // Format the output with leading zeros for days and month
    SimpleDateFormat date_format = new SimpleDateFormat("yyyyMMdd");
    System.out.println(date_format.format(cal1.getTime()));

  }
} 

Thursday 20 September 2012

Creating Batch using java,JDBC code

tr
 
y {
    // Disable auto-commit
    connection.setAutoCommit(false);

    // Create a prepared statement
    String sql = "INSERT INTO my_table VALUES(?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);

    // Insert 10 rows of data
    for (int i=0; i<10; i++) {
        pstmt.setString(1, ""+i);
        pstmt.addBatch();
    }

    // Execute the batch
    int [] updateCounts = pstmt.executeBatch();

    // All statements were successfully executed.
    // updateCounts contains one element for each batched statement.
    // updateCounts[i] contains the number of rows affected by that statement.
    processUpdateCounts(updateCounts);

    // Since there were no errors, commit
    connection.commit();
} catch (BatchUpdateException e) {
    // Not all of the statements were successfully executed
    int[] updateCounts = e.getUpdateCounts();

    // Some databases will continue to execute after one fails.
    // If so, updateCounts.length will equal the number of batched statements.
    // If not, updateCounts.length will equal the number of successfully executed statements
    processUpdateCounts(updateCounts);

    // Either commit the successfully executed statements or rollback the entire batch
    connection.rollback();
} catch (SQLException e) {
}

public static void processUpdateCounts(int[] updateCounts) {
    for (int i=0; i<updateCounts.length; i++) {
        if (updateCounts[i] >= 0) {
            // Successfully executed; the number represents number of affected rows
        } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
            // Successfully executed; number of affected rows not available
        } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
            // Failed to execute
        }
    }
}

1.Display the date using java simple in yyyy/MM/dd HH:mm:ss format

1.Display the date using java simple

 Date() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));



Displaying the date using calender instance

Calender() + SimpleDateFormat()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));


Complete code Example

Full Demo Example

Here is the full source code to show you the use of Date() and Calender() class to get and display the current date time.

package com.onerupya;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class GetCurrentDateTime {
  public static void main(String[] args) {

       DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
       //get current date time with Date()
       Date date = new Date();
       System.out.println(dateFormat.format(date));

       //get current date time with Calendar()
       Calendar cal = Calendar.getInstance();
       System.out.println(dateFormat.format(cal.getTime()));

  }
}

how to create a connecction in mysql jsp or java

how to create a connecction in mysql jsp?

How to create mysql connectiion using jsp?

Ans:-
Creating connection using mysql,jsp

<%@ page language="java" import="java.sql.*" %>


<%
Connection con = null;
String databaseDriver = "com.mysql.jdbc.Driver";
String connectionURL="";


try {
connectionURL = "jdbc:mysql://localhost:3306/DataBaseName";
Class.forName(databaseDriver).newInstance();

con = DriverManager.getConnection(connectionURL, "username", "password");

}catch(Exception e){
out.print("Please wait 'http://rajdeokumarsingh1.blogspot.in/' will be back soon ");
}

%>

ow wait before doing this you have to put mySqlConnector.jar in lib folder of jdkx.xx.Ok

Doooooooooooooooooooooooooooooone!!!!!!!!!!!!!!!

you can download mySqlConnector.jar from this site
http://dev.mysql.com/downloads/connector/j/3.1.html

Extract it and paste on lib folder that's it


Now you done it

Thanks

How to Do Pagination using Jsp,Servlet ?

For Pagination first of all you need to create a connection using jsp. i use the mysql server for data base.

create a table in mysql.

Create table pagination
(
id int ,
title varchar (50),
Description varchar(50),
)

Step 2:create the Database Connection.

create a connection.jsp file

Simple code:-

String connectionURL = "jdbc:mysql://localhost:3306/DatabaseName";
Connection con = null;
Statement statement = null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "username", "Password");

save it to connection.jsp

Connection Created

Step 3:- Create a search.jsp file


"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>






Welcome to music | Movie Search Engine


<%@include file="music.html"%>
/*
String connectionURL = "jdbc:mysql://localhost:3306/";
Connection con = null;
Statement statement = null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "", "");
*/
<%@ include file="connection.jsp"%>
<%
Statement statement = null;
ResultSet rs = null;

try {


statement = con.createStatement();

String qs=request.getParameter("q");
if(qs==null)
qs="";

String item=request.getParameter("item");
if(item==null){item="0";}
int indexcounter=Integer.parseInt(item);

String query1 = "select count(*) from music_search where title LIKE '%"+qs+"%' order by id desc limit "+indexcounter+", 5";

Statement stat1 = con.createStatement();
ResultSet rs1 = stat1.executeQuery(query1);
rs1.next();
int resultcounter=0;
//resultcounter_blankresult=resultcounter;
resultcounter=rs1.getInt(1);

String QueryString = "SELECT * from music_search where title LIKE '%"+qs+"%' order by id desc limit "+indexcounter+", 5";




rs = statement.executeQuery(QueryString);
%>



<%
while (rs.next()) {

%>


<%}%>

<%
// close all the connections.
}catch (Exception ex){
%>
<%
out.println("Unable to connect to database.");
}
%>

Wednesday 19 September 2012

Multi-Language Support in MYSQL

Multi-Language Support in MYSQL

This article is about how to store and manipulate multi languages in mysql table. May be useful while developing globalization / locale support enabled websites
By default mysql supports many european languages, Since unicode character(UTF-8) support implemented in mysql it allows us to store many of the indian (Asian) languages.
Mysql supports Gujrathi, Hindi, Telugu and TAMIL among too many languages in the subcondinent
Let’s consider TAMIL language and workout:-
To store & search tamil character sets in MySQL table, first of all we need to create a table with character set UTF-8.
CREATE TABLE multi_language
(
id INTEGER NOT NULL AUTO_INCREMENT,
language VARCHAR(30),
characters TEXT,
PRIMARY KEY(id)
) ENGINE=INNODB CHARACTER SET = utf8;

INSERT INTO multi_language VALUES (NULL, ‘English’, ‘abcdefghijklmnopqsrtuvwxyz’);
INSERT INTO multi_language VALUES (NULL, ‘Arabic’, ‘ﺃ‎ﺏﺝﺩ‎ﻫﻭﺯﺡﻁﻱﻙﻝ‎ﻡﻥ’);
INSERT INTO multi_language VALUES (NULL, ‘Arabic’, ‘ﺃ‎ﺏﺝﺩ‎ﻫﻭﺯﺡﻁﻱﻙﻝ‎ﻡ ﻥ’);
INSERT INTO multi_language VALUES (NULL, ‘Hindi’, ‘ਓਊਨਣਥਨਫ’);
INSERT INTO multi_language VALUES (NULL, ‘Thai’, ‘ЁώύЂЬЫЗЪШДГЦШГЕ’);

INSERT INTO multi_language VALUES (NULL, ‘Telugu’, ‘ని మీ హొమ్ పేజిగా అమర్చుకోండి’);
INSERT INTO multi_language VALUES (NULL, ‘Tamil’, ‘இந்தியா நாட்டின் பக்கங்கள்’);
INSERT INTO multi_language VALUES (NULL, ‘Arabic’, ‘البحث في الصفحات العربية ‘);
INSERT INTO multi_language VALUES (NULL, ‘Korean’, ‘시작페이지로 하세요 채용정보 광고 프로그램 정보’);

Command to Change the client character set (which sends request to the server):
this has to be done so that the server can understand the request which send by Client.
– To be executed at Client Side
 SET NAMES ‘utf8′;

– System Variable Name : character_set_client
– To Set Locale time zone name
SET @@lc_time_names = ‘en_US’;

For Tamil language, we need to set the time zone as follows..
SET @@lc_time_names = ‘ta_IN’;
Now, we use select query and check out the result.
Important :
————–

 1. If the result shows like the ???? then prpoerly in your system (windows XP) need to install the  extral language support tool by enabling the following options,
 Control Panel -> Regional and Language Option ->  Languages -> Install files for complex script and right-to-left languages (including Thai) 
 2. While fecthing the row using PHP, for displaying the Multilanguage content properly, you must need to include the Meta tag like,
 <META HTTP-EQUIV=”Content-Type” CONTENT=”text/html; charset=utf-8″>
 if needed the add mysql_query(‘SET character_set_results=utf8′) in the php code before fecthing the reocrd.

Display Hindi code in using java from Unicode.

import org.apache.commons.lang3.StringEscapeUtils;
// open the file as ASCII, read it into a string, then
String escapedStr; // = "\u0905\u092d\u0940 \u0938\u092e\u092f \u0939\u0948 ..."
// (to include such a string in a Java program you would have to double each \)
String hindiStr = StringEscapeUtils.unescapeJava( escapedStr );
System.out.println(hindiStr);

Facebook Auto Login using Curl PHP


<?php

// script name: login_to_facebook.php

// coder: Sony AK Knowledge Center - www.sony-ak.com



// your facebook credentials

$username = "----";

$password = "-----";


// access to facebook home page (to get the cookies)

$curl = curl_init ();

curl_setopt ( $curl, CURLOPT_URL, "http://www.facebook.com" );

curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 );

curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );

curl_setopt ( $curl, CURLOPT_ENCODING, "" );

curl_setopt ( $curl, CURLOPT_COOKIEJAR, getcwd () . '/cookies_facebook.cookie' );

curl_setopt ( $curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)" );

$curlData = curl_exec ( $curl );

curl_close ( $curl );


// do get some parameters for login to facebook

$charsetTest = substr ( $curlData, strpos ( $curlData, "name=\"charset_test\"" ) );

$charsetTest = substr ( $charsetTest, strpos ( $charsetTest, "value=" ) + 7 );

$charsetTest = substr ( $charsetTest, 0, strpos ( $charsetTest, "\"" ) );


$locale = substr ( $curlData, strpos ( $curlData, "name=\"locale\"" ) );

$locale = substr ( $locale, strpos ( $locale, "value=" ) + 7 );

$locale = substr ( $locale, 0, strpos ( $locale, "\"" ) );


$lsd = substr ( $curlData, strpos ( $curlData, "name=\"locale\"" ) );

$lsd = substr ( $lsd, strpos ( $lsd, "value=" ) + 7 );

$lsd = substr ( $lsd, 0, strpos ( $lsd, "\"" ) );


// do login to facebook

$curl = curl_init ();

curl_setopt ( $curl, CURLOPT_URL, "https://login.facebook.com/login.php?login_attempt=1" );

curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 );

curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );

curl_setopt ( $curl, CURLOPT_POST, 1 );

curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false );

curl_setopt ( $curl, CURLOPT_POSTFIELDS, "charset_test=" . $charsetTest . "&locale=" . $locale . "&non_com_login=&email=" . $username . "&pass=" . $password . "&charset_test=" . $charsetTest . "&lsd=" . $lsd );

curl_setopt ( $curl, CURLOPT_ENCODING, "" );

curl_setopt ( $curl, CURLOPT_COOKIEFILE, getcwd () . '/cookies_facebook.cookie' );

curl_setopt ( $curl, CURLOPT_COOKIEJAR, getcwd () . '/cookies_facebook.cookie' );

curl_setopt ( $curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)" );

//$curlData is the html of your facebook page

$curlData = curl_exec ( $curl );


?>