Tuesday, 28 May 2013

How to know mysql database size

How to know mysql database size

There are two ways to know the mysql database size

1 : BY SQL Script


Sum of data_length + index_length is equal to the total table size
       data_length – store the real data.
       index_length – store the table index.
Here’s the SQL script to list out the entire databases size
1 : SELECT table_schema "Data Base Name", SUM( data_length + index_length) / 1024 / 1024 
"Data Base Size in MB" FROM information_schema.TABLES GROUP BY table_schema ;

2 : SELECT TABLE_NAME, table_rows, data_length, index_length, 
ROUND(((data_length + index_length) / 1024 / 1024),2) "Size in MB"
FROM information_schema.TABLES WHERE table_schema = "msplash";
Table counts for a database the query is :
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'test';

2. Locate the MySQL stored data

Windows
1) Locate the my.ini, which store in the MySQL installation folder
for example :
C:\Program Files\MySQL\MySQL Server 5.2\my.ini
Open it any text editor

#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.2/"
 
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.2/Data/"
Find the “datadir”, this is the where  MySQL stored the data in Windows.
Linux
1) Locate the my.cnf with the find / -name my.cnf command.
cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
[mysqld]
#
# * Basic Settings
#
user   = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket  = /var/run/mysqld/mysqld.sock
port   = 3306
basedir  = /usr
datadir  = /var/lib/mysql
tmpdir  = /tmp
language = /usr/share/mysql/english
skip-external-locking
3) Find the “datadir”, this is where  MySQL stored the data in Linux system.


Friday, 24 May 2013

Mysql Replication setup for master to slave on windows


Mysql Replication setup for  master to slave on windows
Description :
You can back up your MySQL database using the built-in dump tool, but the second you do that backup is out of date. Since so many companies and web-based tools rely heavily on databases, it’s crucial that those databases are as up-to-date as possible. One very simple solution is database replication, which keeps a real-time copy of the database on a remote server. With this in place, if something happens to the primary database, it will be much easier to get your database back up and running with current information.

The are easy steps to Mysql Replication setup for master to slave on windows
What we need to setup correctly replication on windows are :
1 : Two correctly configured MySQL servers.
2 : Root access and access to the database administrator on both servers.
3 : Ability to work from the command line.
The setup will use two machine master and slave.
First we start setup from master configuration
Suppose 192.168.1.34 is a master and 192.168.1.35 is slave
On Master Machine Configuration
Step 1 : Open the my.ini/my.cnf file and add the following lines below [mysqld]
log-bin=mysql-bin
server-id=1
innodb_flush_log_at_trx_commit=1
sync_binlog=1
binlog-do-db=database_to_be_replicated
Save the my.ini/my.cnf file and restart the mysql server on master machine
For linux : /etc/inid.t/mysqld restart
For windows you can restart from services by control panel.

Step 2 : Setup a user for replication privileges.
Log on to master with root privileges with command line
Mysql –u root –pxxxx
CREATE USER ‘replication_user’@ ‘X.X.X.X’ IDENTIFIED BY ‘password’;

GRANT REPLICATION SLAVE ON *.* TO ‘replication_user’@'X.X.X.X’ IDENTIFIED BY ‘password’;

Replace the X.X.X.X with ip address of slave machine.

Step 3 : To unlock the database do the following commands
FLUSH TABLES WITH READ LOCK;
Now unlock the tables
Show master status to user later
UNLOCK TABLES;

On Slave Configuration :
Mysql Replication setup for  master to slave on windows are as follows

Step 4 : Open the my.ini/my.cnf file from slave server
Add the following lines below [mysqld] line
server-id=2
 
Step 5 : Go to the master and issue the following command as
SHOW MASTER STATUS; 
 
 
mysql> show master status;
+------------------+-----------+--------------+------------------+
| File             | Position  | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+-----------+--------------+------------------+
| mysql-bin.000001 | 346934211 |              |                  |
+------------------+-----------+--------------+------------------+
1 row in set (0.00 sec)
 
Step 6 : Again go to the slave machine and issue the following command as
 
STOP SLAVE;
Step 7 : You must run the following command as
 
CHANGE MASTER TO MASTER_HOST=’IP_ADDRESS_OF_MASTER’, MASTER_USER=’USER’, MASTER_PASSWORD=’USER_PASSWORD’, MASTER_LOG_FILE=’mysql-bin.007′, MASTER_LOG_POS=NUMBER;
Where the following applies:
IP_ADDRESS_OF_MASTER is the actual IP address of the Master
USER is the MySQL admin user
USER_PASSWORD is the password for the USER
NUMBER is the Position Number reported from the SHOW MASTER STATUS command.
For Example
 
 
CHANGE MASTER TO 
MASTER_HOST=’192.168.1.34’,
MASTER_USER='replication_user',
MASTER_PASSWORD='password', 
MASTER_PORT=3306,
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=346934211;
Save the file and exit.
Step 8 : Restart the Slave by issuing the command 
SLAVE START; 
 
Now you can follow these steps to make sure everything is working fine.
 
SHOW SLAVE STATUS;.
 
 
mysql> show slave status \G
*************************** 1. row *********************
               Slave_IO_State: Waiting for master to sen
                  Master_Host: 192.168.1.34
                  Master_User: replication_user
                  Master_Port: 3306
                Connect_Retry: 10
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 346934211
               Relay_Log_File: WIN-THQO1NKG27F-relay-bin
                Relay_Log_Pos: 785
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 1146
 
In the above output if you see the following
 
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
 
Then all is fine. Replicated MySQL database. 
Congratulations!
 
 
 
 





Wednesday, 22 May 2013

How to create PDF with Java and iText Example

How to create PDF with Java and iText Example
iText is a Java library originally created by Bruno Lowagie which allows to create PDF, read PDF and manipulate them. I will show you a example here.

iText has a hierarchical structure. The smallest text unit is a "Chunk" which is a String with a pre-defined font. A "Phrase" combines several Chunks and allows to define line spacing. "Paragraph" is a subclass of "Phrase" and allows to define more layout attributes, e.g. margins. The class "Anchor" is a subclass of "Paragraph" and serves as the basis for hyperlinks in the generated PDF.

for How to create PDF with Java and iText Example

Installation
Download the iText core binary from here link. Download iText Jar

Creating PDF


package itext.test;
import java.io.FileOutputStream;
import java.util.Date;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class GeneratePDFTest {
public static void main(String[] args) {
try {
 //create a document
     Document document = new Document();
     PdfWriter.getInstance(document, new FileOutputStream(FILE));
     document.open();
     //adding metadata about pdf file
     addMetaData(document);
     //adding title of pdf file
     addTitlePage(document);
     //adding contents into pdf file.
     addContent(document);
     document.close();
   } catch (Exception e) {
     e.printStackTrace();
   }

}
 private static String FILE = "D:/test/TestPdf.pdf";
 private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
 private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.NORMAL, BaseColor.RED);
 private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,Font.BOLD);
 private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.BOLD);

 //iText allows to add metadata to the PDF which can be viewed in your Adobe Reader
 // You can view under File -> Properties
 private static void addMetaData(Document document) {
   document.addTitle("My Test PDF");
   document.addSubject("Using iText");
   document.addKeywords("Java, PDF, iText");
   document.addAuthor("Wakil Ahmad");
   document.addCreator("Wakil");
}

 private static void addTitlePage(Document document) throws DocumentException {
   Paragraph preface = new Paragraph();
   // We add one empty line
   addEmptyLine(preface, 1);
   // Writing a big header
   preface.add(new Paragraph("Title of the document as pdf file", catFont));
   addEmptyLine(preface, 1);
   // Will create: Report generated by: _name, _date
   preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),smallBold));
   addEmptyLine(preface, 3);
   preface.add(new Paragraph("Describes about document ",smallBold));
   addEmptyLine(preface, 8);
   preface.add(new Paragraph("This document is a preliminary version", redFont));
   document.add(preface);
   // Start a new page
   document.newPage();
 }
    private static void addEmptyLine(Paragraph paragraph, int number) {
   for (int i = 0; i < number; i++) {
     paragraph.add(new Paragraph(" "));
   }
 }
 
    private static void addContent(Document document) throws DocumentException {
       Anchor anchor = new Anchor("Testing page 1", catFont);
       anchor.setName("Test Chapter 1");

       // Second parameter is the number of the chapter
       Chapter catPart = new Chapter(new Paragraph(anchor), 1);

       Paragraph subPara = new Paragraph("Subcategory 1", subFont);
       Section subCatPart = catPart.addSection(subPara);
       subCatPart.add(new Paragraph("How are you"));

       subPara = new Paragraph("Subcategory 2", subFont);
       subCatPart = catPart.addSection(subPara);
       subCatPart.add(new Paragraph("Paragraph 1"));
       subCatPart.add(new Paragraph("Paragraph 2"));
       subCatPart.add(new Paragraph("Paragraph 3"));
       subCatPart.add(new Paragraph("Paragraph 4"));
       // Add a list
       createList(subCatPart);
       Paragraph paragraph = new Paragraph();
       addEmptyLine(paragraph, 5);
       subCatPart.add(paragraph);

       // Adding a table
       createTable(subCatPart);

       // Now add all this to the document
       document.add(catPart);

       // Next section
       anchor = new Anchor("Second Chapter", catFont);
       anchor.setName("Second Chapter");

       // Second parameter is the number of the chapter
       catPart = new Chapter(new Paragraph(anchor), 1);

       subPara = new Paragraph("Subcategory", subFont);
       subCatPart = catPart.addSection(subPara);
       subCatPart.add(new Paragraph("This is a very important message"));

       // Now add all this to the document
       document.add(catPart);

     }
 
        private static void createList(Section subCatPart) {
       List list = new List(true, false, 10);
       list.add(new ListItem("First point"));
       list.add(new ListItem("Second point"));
       list.add(new ListItem("Third point"));
       subCatPart.add(list);
     }
 
    private static void createTable(Section subCatPart) throws BadElementException {
       PdfPTable table = new PdfPTable(3);
       PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       table.addCell(c1);

       c1 = new PdfPCell(new Phrase("Table Header 2"));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       table.addCell(c1);
       c1 = new PdfPCell(new Phrase("Table Header 3"));
       c1.setHorizontalAlignment(Element.ALIGN_CENTER);
       table.addCell(c1);
       table.setHeaderRows(1);
       table.addCell("1.0");
       table.addCell("1.1");
       table.addCell("1.2");
       table.addCell("2.1");
       table.addCell("2.2");
       table.addCell("2.3");
       subCatPart.add(table);
     }
}

After Running the above java program, the output file below here.







Read an existing PDF :

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class ReadUsePDFTest {
  private static String INPUTFILE = "D:/test/testPdf.pdf";
  private static String OUTPUTFILE = "D:/test/ReadPdf.pdf";

  public static void main(String[] args) throws DocumentException,
      IOException {
    Document document = new Document();

    PdfWriter writer = PdfWriter.getInstance(document,
        new FileOutputStream(OUTPUTFILE));
    document.open();
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages();
    PdfImportedPage page;
    // Go through all pages
    for (int i = 1; i <= n; i++) {
      // Only page number 2 will be included
      if (i == 2) {
        page = writer.getImportedPage(reader, i);
        Image instance = Image.getInstance(page);
        document.add(instance);
      }
    }
    document.close();

  }

} 


Thursday, 16 May 2013

JAX-RS @Path URI Matching Example - RESTful web service

JAX-RS @Path URI Matching Example - RESTful web service

JAX-RS @Path URI Matching Example - RESTful web service


In JAX-RS you can use the @Path annotation to bind the URI pattern to java method
First We see the simple URL Pattern matching with @Path annotation
Simple URI Matching Pattern

URI Matching and Request Parameter
The value within open brace "{" and close brace "}" represent a parameter and can be
acessed using @PathParam annotation for example.

URI Matching and Regular Expression
@Path support complex URI matching with regular expression, via following expression
{" variable-name [ ":" regular-expression ] "}

@PathParam with multiple parameters
This example show how to inject multiple parameters into a java method

Wednesday, 15 May 2013

JAX-RS RESTful web service using Jersey

JAX-RS RESTful web service using Jersey

JAX-RS RESTful web service using Jersey

JAX-RS provides the functionality for Representational State Transfer (RESTful) web services.
RESTful web services often better integrated with HTTP than SOAP based service. Which does not require
XML message or wsdl service.
There are two most important implementation of JAX-RS Java API are Jersey and Resteasy
What Are RESTful Web Services?
RESTful web services are built to work best on the Web. Representational State Transfer (REST) is a
architectural style that specifies constraints, such as the uniform interface, that if applied to a
web service induce desirable properties, such as performance, scalability, and modifiability, that
enable services to work best on the Web. In the REST architectural style, data and functionality are
considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web.
The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style
constrains an architecture to a client/server architecture and is designed to use a stateless communication
protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of
resources by using a standardized interface and protocol.
The following principles encourage RESTful applications to be simple, lightweight, and fast:

Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets
of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space
for resource and service discovery. See The @Path Annotation and URI Path Templates for more information.

Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations:
PUT, GET, POST, and DELETE. PUT creates a new resource, which can be then deleted by using DELETE. GET retrieves
the current state of a resource in some representation. POST transfers a new state onto a resource. See Responding
to HTTP Methods and Requests for more information.

Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed
in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource
is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate
representation format, and perform authentication or access control. See Responding to HTTP Methods and Requests
and Using Entity Providers to Map HTTP Response and Request Entity Bodies for more information.

Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages
are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques
exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response
messages to point to valid future states of the interaction. See Using Entity Providers to Map HTTP Response and
Request Entity Bodies and “Building URIs” in the JAX-RS Overview document for more information.

There are some annotations implemented by Jersy and Resteasy
@Path : The @Path annotation’s value is a relative URI path indicating where the Java class will be hosted:
for example, /helloworld. You can also embed variables in the URIs to make a URI path template. For example,
you could ask for the name of a user and pass it to the application as a variable in the
URI: /helloworld/{username}.
@GET :The @GET annotation is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP GET requests. The behavior of a
resource is determined by the HTTP method to which the resource is responding.
@POST :The @POST annotation is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP POST requests. The behavior of a
resource is determined by the HTTP method to which the resource is responding.
@PUT : The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP PUT requests. The behavior of
a resource is determined by the HTTP method to which the resource is responding.
@DELETE : The @DELETE annotation is a request method designator and corresponds to the similarly named
HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests.
The behavior of a resource is determined by the HTTP method to which the resource is responding.
@HEAD : The @HEAD annotation is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP HEAD requests. The behavior of a
resource is determined by the HTTP method to which the resource is responding.
@PathParam : The @PathParam annotation is a type of parameter that you can extract for use in your resource class.
URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template
variable names specified in the @Path class-level annotation.
@QueryParam : The @QueryParam annotation is a type of parameter that you can extract for use in your resource
class. Query parameters are extracted from the request URI query parameters.
@Consumes : The @Consumes annotation is used to specify the MIME media types of representations a resource can
consume that were sent by the client.
@Produces : The @Produces annotation is used to specify the MIME media types of representations a resource can
produce and send back to the client: for example, "text/plain".
@Provider : The @Provider annotation is used for anything that is of interest to the JAX-RS runtime,
such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an
HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP
response entity body by using a MessageBodyWriter. If the application needs to supply additional metadata,
such as HTTP headers or a different status code, a method can return a Response that wraps the entity and
that can be built using Response.ResponseBuilder.

JAX-RS RESTful web service using Jersey Hello World Example

Where Jersy is reference implementation of JAX-RS Java API. Jersy is used to build RESTful web service.
Dependency of application are :
Jersey 1.8
JDK 1.6
Tomcat 6.0
Eclipse 3.6
Step 1 : Create REST Service

Step 2 : web.xml
In web.xml, register com.sun.jersey.spi.container.servlet.ServletContainer, and puts your Jersey
service folder under init-param, com.sun.jersey.config.property.packages.

In this example, web request from appname/rest/hello/ will match to HelloWorldService, via @Path("/hello").
And the {any values} from appname/rest/hello/{any values} will match to parameter annotated with @PathParam.
URL : http://localhost:8080/appname/rest/hello/wakil

When Run the above url in your browser, the output will come as
Jersey say wakil


Tuesday, 14 May 2013

Convert Java Object To/From JSON (Gson)

How To Convert Java Object To/From JSON (Gson)


Gson is google library for internal use, but now you can use publically.
It is a lightweight data-interchange format.
Gson is easy to learn and implement, We need to know two methods given below.
1 : toJson() – Convert Java object to JSON format.
2 : fromJson() – Convert JSON into Java object.
A pojo, with initialized values, Later use Gson to convert this object to/from JSON formatted string.

toJson() Example:
Convert object to JSON string, and save it as test.json

fromJson() Example: Read data from test.json , convert back to object.

Monday, 13 May 2013

JSON.simple Example

JSON.simple Example


JSON simple is a simple Java toolkit for JSON . You can use JSON simple to encode or
decode JSON text.
Features :
1 : Full compliance with JSON specification (RFC4627) and reliable.
2 : Provides multiple functionalities such as encode, decode/parse and escape
JSON text while keeping the library lightweight.
3 : Flexible, simple and easy to use by reusing Map and List interfaces.
4 : Supports streaming output of JSON text.
5 : Heap based parser.
6 : High performance.
7 : No dependency at all.

You need to download the JSON.simple library here and include it in java classpath.
1 : Write JSON to File
Write JSON data via JSONObject and JSONArray, and save it into a file named test.json


2 : Read JSON from File
Use JSONParser to read above generated JSON file test.json, and display each of the values.

Encode a JSON object - Streaming

Encode a JSON object - Using Map

Encode a JSON object - Using Map and streaming