Wednesday, November 27, 2013

Unix Network Programming: Simple Client Server using Sockets

To keep this program simple
  1. The server accepts connection from a single client only
  2. The server doesn't fork new process to handle client requst
  3. Client sends only a single message to server and server replies back with another message

Algorithm

Server

  1. Create socket
  2. Bind
  3. Listen
  4. Accept connection
  5. Read data sent by client
  6. Send data back to client
  7. Close socket descriptors
Client

  1. Create socket
  2. Connect to server
  3. Send data to server
  4. Receive data from server
  5. Close socket descriptors

Program

server
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define SERVERPORT 3098
#define SERVERIP "192.168.1.4"
#define SIZE 10
#define DEFAULT_FLAG 0
int main()
{
    int sockfd, newsockfd, n;
    int addrlen = sizeof(struct sockaddr_in);
    struct sockaddr_in *serveraddr = (struct sockaddr_in *)malloc(addrlen);
    struct sockaddr_in *clientaddr = (struct sockaddr_in *)malloc(addrlen);
    char buff[10];

    /* Create socket */
    if((sockfd = socket(AF_INET, SOCK_STREAM, DEFAULT_FLAG))<0)
    {
        printf("Error: Socket creation failed... Exiting...\n");
        return 0;
    }
  
    /* Bind */
    bzero(serveraddr,addrlen);                // Initailize serveraddr as null. defined in <string.h>
    serveraddr->sin_family = AF_INET;        // Set address family as INET
    serveraddr->sin_port = SERVERPORT;
    serveraddr->sin_addr.s_addr = inet_addr(SERVERIP);    // Convert character string to dotted decimal format. Defined in <arpa/inet.h>
    if(bind(sockfd, (struct sockaddr*) serveraddr, addrlen)<0)
    {
        printf("Error: Bind failed... Exiting...\n");
        return 0;
    }
  
    /* listen */
    listen(sockfd,4);
    printf("Server waiting for connection request . . .\n");
  
    /* Accept connection */
    if((newsockfd = accept(sockfd, (struct sockaddr*)clientaddr, &addrlen))<0)
        printf("Error: Accepting connection request failed\n");
    else
        printf("Connection Accepted \n");

    /* Read data sent by client */
    n = recv(newsockfd, buff, SIZE, DEFAULT_FLAG);
    buff[n] = '\0';
    printf("Message Received: %s\n",buff);
  
    /* Send replt to client */
    strcpy(buff,"Thank You");
    send(newsockfd, buff, strlen(buff), DEFAULT_FLAG);

    /* Close both socket descriptors*/
    close(newsockfd);
    close(sockfd);
    return 0;
}


client

#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define SERVERPORT 3098
#define SERVERIP "192.168.1.4"
#define SIZE 10
#define DEFAULT_FLAG 0
int main()
{
    int sockfd,n;
    int addrlen = sizeof(struct sockaddr_in);
    struct sockaddr_in *serveraddr = (struct sockaddr_in *)malloc(addrlen);
    char buff[10];

    /* Create socket */
    if((sockfd = socket(AF_INET, SOCK_STREAM, DEFAULT_FLAG))<0)
    {
        printf("Error: Socket creation failed... Exiting...\n");
        return 0;
    }
  
    /* Connect to server */
    bzero(serveraddr, addrlen);                // Initailize serveraddr as null. defined in <string.h>
    serveraddr->sin_family = AF_INET;        // Set address family as INET
    serveraddr->sin_port = SERVERPORT;
    serveraddr->sin_addr.s_addr = inet_addr(SERVERIP);    // Convert character string to dotted decimal format defined in <arpa/inet.h>
    if(connect(sockfd, (struct sockaddr*)serveraddr, addrlen)<0)
    {
        printf("Error: Connection failed... Exiting...\n");
        return 0;
    }else
        printf("Connection to server established successfully . . . \n");
  
    /* Send data to Server */
    printf("Enter Message to be sent ");
    scanf("%s",buff);
    send(sockfd, buff, strlen(buff), DEFAULT_FLAG);
  
    /* Read reply from server */
    n = recv(sockfd, buff, SIZE, DEFAULT_FLAG);
    buff[n] = '\0';
    printf("Message from Server: %s\n",buff);

    /* Close socket descriptor */
    close(sockfd);
    return 0;
}


Output

server window
Server waiting for connection request . . .
Connection Accepted
Message Received: Welcome

client window
Connection to server established successfully . . .
Enter Message to be sent Welcome
Message from Server: Thank You


Friday, November 22, 2013

Unix Network Programming: FTP using message queue

Algorithm

Create a structute that defines a message item in the message queue, say messageBuf

Client Side
  1. Get a message queue
  2. Read a filename from the standard input
  3. Set the message type as 1 and send the message
  4. Read messages of type 2 from the mesaage queue
  5. display the contents read
Server Side
  1. Get a message queue
  2. Read the filename from the meassage queue with type as 1
  3. Open requested file
  4. Read contents from the file and write into the message queue with type as 2
  5. Close the file

Program

message.h
 
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define PERMS 0666
#define KEY1 2345
#define TYPE1 100
#define TYPE2 111
#define SIZE 20

struct messageBuf{
    int type;
    char msg[SIZE];
}

server
#include<stdio.h>
#include<malloc.h>
#include<fcntl.h>
#include<string.h>
#include "message.h"
main()
{
    int mq1,fd,n;
    struct messageBuf *m1 = (struct messageBuf *)malloc(sizeof(struct messageBuf));
    if(mq1 = msgget(KEY1,PERMS|IPC_CREAT)<0)
        printf("Error: Message Q unavaillable\n");
    msgrcv(mq1,m1,sizeof(struct messageBuf),TYPE1,0);
    printf("File Requested:%s\n",m1->msg);
    fd = open(m1->msg, O_RDONLY, 0);
    if(fd<0)
        printf("Error: Unable to open requested file\n");
    do
    {
        n = read(fd,m1->msg,SIZE);
        m1->type = TYPE2;
        msgsnd(mq1, m1, n, 0);
    }while(n==SIZE);
    close(fd);
}

client
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include "message.h"

main()
{
    int mq1,n;
    struct messageBuf *m1 = (struct messageBuf *)malloc(sizeof(struct messageBuf));
    if(mq1 = msgget(KEY1,PERMS|IPC_CREAT)<0)
        printf("Error: Message Q unavaillable\n");
    printf("Enter Required file name: ");
    scanf("%s",m1->msg);
    m1->type = TYPE1;
    msgsnd(mq1, m1, strlen(m1->msg),0);
    do{
        n = msgrcv(mq1,m1,SIZE,TYPE2,0);
        printf("%s",m1->msg);
    }while(n==SIZE);
}

Run the server and client from two different windows

Output

Client window

Enter Required file name: message.h
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define PERMS 0666
#define KEY1 2345
#define TYPE1 100
#define TYPE2 111
#define SIZE 20

struct messageBuf{
    int type;
    char msg[SIZE];
}

Server window
File Requested:message.h

Thursday, November 21, 2013

Unix Network Programming: Process synchronization using semaphore

Algorithm


main() function
  1. Create a semaphore
  2. fork()
  3. In both parent and child
    1. Obtain lock by calling lock() function
    2. sleep for some time
    3. unlock by calling unlock() function
lock() function
  1. Create array of sembuf with size two
    1. First element waiting for semaphore to be zero
    2. Second element incrementing it
  2. Do semop with the created array as argument
unlock() function
  1. Create array of sembuf with size one
    1. The element decrementing semaphore
  2. Do semop with the created array as argument

Program

#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#define PERMS 0666
#define KEY 1234

main(){
    int pid,semid,i;
    semid = semget(KEY, 1, IPC_CREAT|PERMS);
    pid = fork();
    if(pid == 0){                // Child Process
        for(i=1;i<=5;i++){
            printf("%d: Child waiting for lock\n",i);
            lock(semid);
                printf("%d: Child has the lock\n",i);
                sleep(1);
                printf("%d: Child unlocking\n",i);
            unlock(semid);
        }
    }else{                        // Parent Process
        for(i=1;i<=5;i++){
            printf("%d: Parent waiting for lock\n",i);
            lock(semid);
                printf("%d: Parent has the lock\n",i);
                sleep(1);
                printf("%d: Parent unlocking\n",i);
            unlock(semid);       
        }
    }
}

lock(int id){
    struct sembuf op_lock[2]={
        0, 0, 0,                   // Wait for id to be 0
        0, 1, 0                    // Then increment it
    };
    semop(id, op_lock,2);
}

unlock(int id){
    struct sembuf op_unlock[1]={
        0, -1, IPC_NOWAIT        // Decrement semid by 1
    };
    semop(id,op_unlock,1);
}

Output

1: Parent waiting for lock
1: Parent has the lock
1: Child waiting for lock
1: Parent unlocking
2: Parent waiting for lock
1: Child has the lock
1: Child unlocking
2: Child waiting for lock
2: Parent has the lock
2: Parent unlocking
3: Parent waiting for lock
2: Child has the lock
2: Child unlocking
3: Child waiting for lock
3: Parent has the lock
3: Parent unlocking
4: Parent waiting for lock
3: Child has the lock
3: Child unlocking
4: Child waiting for lock
4: Parent has the lock
4: Parent unlocking
5: Parent waiting for lock
4: Child has the lock
4: Child unlocking
5: Child waiting for lock
5: Parent has the lock
5: Parent unlocking
5: Child has the lock
5: Child unlocking

Unix: File permissions


File Permissions in Unix


Every user on a Unix system has a unique username, and is a member of at least one group. This group information is held in the password file (/etc/passwd). A user can also be a member of one or more other groups. The auxiliary group information is held in the file /etc/group. Only the administrator can create new groups or add/delete group members.
Every directory and file on the system has an owner, and also an associated group. It also has a set of permission flags which specify separate read(r), write(w) and execute(x) permissions for the 'user' (owner), 'group', and 'other' (everyone else with an account on the computer) The 'ls -l' command can be used to view the permissions and group associated with files in current directory.
An example of the output produced by ls -l is shown below.
drwxr-xr-x 2 teacher staff 4096 Nov 21 15:05 Desktop
drwxr-xr-x 2 teacher staff 4096 Nov 12 10:32 Documents
drwxr-xr-x 2 teacher staff 4096 Nov 21 15:44 Downloads
drwxr-xr-x 2 teacher staff 4096 Nov 12 10:32 Music
-rw-r--r-- 1 teacher staff 406558 Nov 21 10:23 NPrecord.odt
drwxr-xr-x 2 teacher staff 4096 Nov 22 11:14 Unix Programming
Each line in the output has the following fields
Field 1: a set of ten permission flags.
Field 2: link count (don't worry about this)
Field 3: owner of the file
Field 4: associated group for the file
Field 5: size in bytes
Field 6-8: date and time of last modification
Field 9: name of file
The permission flags are interpreted as follows
Position         Meaning
1                        directory flag, 'd' if a directory, '-' if a normal file, something   else occasionally may appear here for special devices.
2,3,4                  read, write, execute permission for User (Owner) of file
5,6,7                  read, write, execute permission for Group
8,9,10                read, write, execute permission for Other
Given below is the interpretation for the symbols used in permission flag
Value             Meaning
-                        in any position means that flag is not set
r                       file is readable
w                      file is writable. On a directory, means you can add or delete files
x                       file is executable. On a directory, means you can list the files in that directory
So if we interpret the very first line of the output given above, we can understand that: Desktop is a directory owned by teacher, who belongs to the group staff, the size of the folder is 4096 bytes and was modified on Nov 21 15:05 hours. The permissions for owner is read, write and execute while the other members of the group staff has permissions only for reading and executing(i.e. no write permissions) and users who doesn't belong to the group also has permissions for reading and executing. 

Setting permissions

chmod command can be used to change the permissions of a file.
syntax: chmod {a,u,g,o} {+,-} {r,w,x} files
      Value   Meaning
       
       a           all users 
      u           the owner 
      g           the owner group 
      o           others (neither u, nor g)
      +           give permission 
      -            remove permission
e.g. chmod g+rw files give the group read and write permission
 

Numbers can also be used to set the permissions
The number equivalents of r, w, x are:
                              r        w        x
OWNER(USER)    400    200    100
GROUP                40      20      10
PUBLIC                4        2        1
      e.g. (i) 700 means read write and execute permissions for owner(400 + 200 + 100) and no permissions for group(0) and others(0).
             (ii) 666 means r and w for owner, group and others   
The real stuff behind this is that the permissions for each are defined using 3 bits, with 9 bits defining the whole permission. where the last bit specifying an execute permission, the middle bit specifing write permission and the last bit read permission so a binary 100(octal 4) means r for owner and 111(octal 7). represents rwx for owner.

Wednesday, September 25, 2013

JavaScript: Functions

JavaScript Functions

A function is a group of reusable code which can be called anywhere in your programme. This eliminates the need of writing same code again and again. Functions help programmers to write modular code. We can divide our programme into a number of small and manageable functions. Like any other advance programming language, JavaScript also supports all the features necessary to write modular code using functions.
Functions that are provided by JavaScript are called built-in functions and those defined by the user are called user-defined functions. alert(), confirm() etc. are examples for built-in functions.

Function Definition
Before we use a function we need to define that function. A function is defined as a code block (inside curly { } braces), preceded by the function keyword and name of the function.
A function can receive a list of values on which it can operate, known as the parameters of the function.
 The basic syntax is:
<script type="javascript">
      function functionname(parameter-list){
                              statements
      }
</script>
Example:
<script type="javascript">
      function helloWorld(){
                              alert("Hello World");
      }
</script>

Calling a Function
The function can be called directly when an event occurs (like when a user clicks a button), and it can be called from anywhere by JavaScript code.
To invoke a function we should simply write the name of that function as follows:
<script type="javascript">
      helloWorld();
</script>

Function Parameters
JavaScript allows the programmers to pass different parameters while calling a function.
These passed parameters can be captured inside the function and any manipulation can be done over them.
A function takes multiple parameters specified as a comma separated list.
<script type="javascript">
      function sayHello(name){
                              alert( "Hello "+name);
      }
</script>
Example:
<script type="javascript">
      sayHello("Vinod");
</script>
When the function is called as shown, it displays an alert dialog box with message 'Hello Vinod'.

Returning values
A JavaScript function can have an optional return statement. This is required if we want to return a value from a function. This statement should be the last statement in a function.
For example we can pass two numbers as parameters to function sum() and we can expect the function to return their sum to the point where it is called.
<script type="javascript">
      function sum(x, y){
                              var s;
                              s = x + y;
                              return  s;
      }
</script>
Now we can call this function as follows:
<script type="javascript">
      var result;
      result = sum(8, 6);
      alert("Sum:"+result );
</script>
The output of the above code will be an alert dialog box displaying 'Sum:14'
Scope of Variables
With respect to their scope variables can be classified into two as local variables and global variables.
A variable declared within a JavaScript function becomes local variable and can only be accessed from within that function. It is said to have local scope. We can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. Local variables are deleted as soon as the function is completed.
Variables declared outside a function, become global variable, and all scripts and functions on the web page can access it. They are deleted only when the page closes
Example:
<script  type="javascript">
      var x;
      function sum(a,b){
                              x=a+b
      }
      function displaySum(){
                              alert("Sum:"+x)
      }
</script>
In the above example x is a global variable while a and b are local to the function sum(). So x can be easily accessed by the function displaySum() which displays the sum calculated in sum().

Tuesday, September 24, 2013

Microsoft FrontPage

Microsoft FrontPage

Introduction
Microsoft FrontPage (full name Microsoft Office FrontPage) is a WYSIWYG(What-You-See-Is-What-You-Get) HTML editor and web site administration tool from Microsoft. It was a part of the Microsoft Office suite from 1997 to 2003. It has since been replaced by Microsoft Expression Web and Sharepoint Designer, which were first released in December 2006 alongside Microsoft Office 2007. FrontPage was initially created by the Cambridge, Massachusetts company Vermeer Technologies Incorporated. Vermeer was acquired by Microsoft in January 1996.
As a WYSIWYG editor, FrontPage is designed to hide the details of pages' HTML code from the user, making it possible for novices to easily create web pages and sites.
In 2006, Microsoft announced that FrontPage would eventually be superseded by two products. Microsoft SharePoint Designer will allow business professionals to design SharePoint-based applications. Microsoft Expression Web is targeted at the web design professional for the creation of feature-rich web sites. Microsoft announced that FrontPage will be discontinued from December 2006.

Advantages
  1. FrontPage 2003 consists of a Split View option to allow the user to code in Code View and preview in Design View without the hassle of switching from the Design and Code View tabs for each review
  2. Dynamic Web Templates (DWT) allows the users to create a single template that could be used across multiple pages and even the whole Web site
  3. Interactive Buttons give users a new easy way to create web graphics for navigation and links, eliminating the need for a complicated image-editing package such as Adobe Photoshop
  4. The accessibility checker gives user the ability to check if their code is standards compliant and that their Web site is easily accessible for people with disabilities. An HTML optimizer is included to aid in optimizing code to make it legible and quicker to process
  5. Intellisense, which is a form of auto completion, is a key feature that assists the user while typing in Code View. When working in Code View, Intellisense will suggest tags and/or properties for the code that the user is entering which significantly reduces the time to write code. 
  6. Code Snippets give users the advantage to create snippets of their commonly used pieces of code allowing them to store it for easy access whenever it is next needed
  7. FrontPage includes support for programming in ASP.NET, a server-side scripting language, that adds interactivity to Web sites and Web pages
  8. FrontPage includes support for macros in Visual Basic.


Sunday, September 22, 2013

Programming in Java: AWT classes 02

Working with Graphics, Colours and Fonts

Working with Graphics
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to a window. This can be the main window of an applet, a child window of an applet, or a stand-alone application window. The origin of each window is at the top-left corner and is (0,0). Coordinates are specified in pixels.
The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled. Objects are drawn and filled in the currently selected graphics colour, which is black by default. When a graphics object is drawn that exceeds the dimensions of the window, output is automatically clipped. Let’s take a look at several of the drawing methods.

Drawing Lines
Lines are drawn by means of the drawLine() method, shown here:
void drawLine(int x1, int y1, int x2, int y2)
It displays a line in the current drawing colour that begins at (x1, y1) and ends at (x2, y2).

Drawing Rectangles
The drawRect() and fillRect() methods display an outlined and filled rectangle, respectively. The signature is:
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
The upper-left corner of the rectangle is at top, left. The dimensions of the rectangle are specified by width and height.
To draw a rounded rectangle, use drawRoundRect() or fillRoundRect(), The signature is:
void drawRoundRect(int top, int left, int width, int height, int xArc, int yArc)
void fillRoundRect(int top, int left, int width, int height, int xArc, int yArc)
A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at top, left. The dimensions of the rectangle are specified by width and height. The diameter of the rounding arc along the X axis is specified by xArc. The diameter of the rounding arc along the Y axis is specified by yArc.

Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). The signature is:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top, left and whose width and height are specified by width and height. To draw a circle, specify a square as the bounding rectangle.

Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ) methods. The signature is:
void drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top, left and whose width and height are specified by width and height. The arc is drawn from startAngle through the angular distance specified by sweepAngle. Angles are specified in degrees. Zero degrees is on the horizontal, at the three o’clock position. The arc is drawn counter-clockwise if sweepAngle is positive, and clockwise if sweepAngle is negative. Therefore, to draw an arc from twelve o’clock to six o’clock, the start angle would be 90 and the sweep angle 180.

Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ). The signature is:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)

The polygon’s endpoints are specified by the coordinate pairs contained within the x and y arrays. The number of points defined by x and y is specified by numPoints.

Working with colour
Java supports colour in a portable, device-independent fashion. The AWT colour system allows you to specify any colour you want. It then finds the best match for that colour, given the limits of the display hardware currently executing your program or applet. Colour is encapsulated by the Color class.
You can also create your own colours, using one of the colour constructors. Three commonly used forms are:
Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the colour as a mix of red, green, and blue. These values must be between 0 and 255
The second colour constructor takes a single integer that contains the mix of red, green, and blue packed into an integer. The integer is organized with red in bits 16 to 23, green in bits 8 to 15, and blue in bits 0 to 7.
The final constructor, Color(float, float, float), takes three float values (between 0.0 and 1.0) that specify the relative mix of red, green, and blue.
Once you have created a colour, you can use it to set the foreground and/or background colour by using the setForeground( ) and setBackground( ) methods.

Color Constatnts
The class Color defines the constants shown here that can be used to specify colours:

Color.black
Color.magenta
Color.blue
Color.orange
Color.cyan
Color.pink
Color.darkGray
Color.red
Color.gray
Color.white
Color.green
Color.yellow
Color.lightGray



Color Methods
You can obtain the red, green, and blue components of a colour independently using the methods shown below:
int getRed( )
int getGreen( )
int getBlue( )
Each of these methods returns the RGB colour component found in the invoking Color object in the lower 8 bits of an integer.
To obtain a packed, RGB representation of a colour, use getRGB( ), shown here:
int getRGB( )
The return value is organized as described earlier.

Setting the Current Graphics Color
By default, graphics objects are drawn in the current foreground colour. You can change this colour by calling the Graphics method setColor( ):
void setColor(Color newColor)
Here, newColor specifies the new drawing colour. You can obtain the current colour by calling getColor(), as shown:
Color getColor( )

Working with fonts
The AWT supports multiple type fonts. The AWT provides flexibility by abstracting font-manipulation operations and allowing for dynamic selection of fonts. Fonts have a family name and a face name. The family name is the general name of the font, such as Courier. The face name specifies a specific font, such as Courier Italic. Fonts are encapsulated by the Font class.

Font variables
The Font class defines the following variables:
String name: Name of the font
float pointSize: Size of the font in points
int size: Size of the font in points
int style: Font style

Font methods
The most commonly used methods defined by Font are listed below:
Method
Description
static Font decode(String str)
Returns a font given its name.
boolean equals(Object FontObj)
Returns true if the invoking object contains the same font as that specified by FontObj. Otherwise, it returns false.
String getFamily( )
Returns the name of the font family to which the invoking font belongs.
String getFontName()
Returns the face name of the invoking font.
int getSize( )
Returns the size, in points, of the invoking font.
int getStyle( )
Returns the style values of the invoking font.
boolean isBold( )
Returns true if the font includes the BOLD style value. Otherwise, false is returned.
boolean isItalic( )
Returns true if the font includes the ITALIC style value. Otherwise, false is returned.
boolean isPlain( )
Returns true if the font includes the PLAIN style value. Otherwise, false is returned.
String toString( )
Returns the string equivalent of the invoking font.

Determining the Available Fonts
When working with fonts, often we need to know which fonts are available on your machine. To obtain this information, we can use the getAvailableFontFamilyNames( ) method defined by the GraphicsEnvironment class as shown here:
String[ ] getAvailableFontFamilyNames( )
This method returns an array of strings that contains the names of the available font families. In addition, the getAllFonts( ) method is defined by the GraphicsEnvironment class as shown:
Font[ ] getAllFonts( )
This method returns an array of Font objects for all of the available fonts. Since these methods are members of GraphicsEnvironment, we need a GraphicsEnvironment reference to call them. We can obtain this reference by using the getLocalGraphicsEnvironment() static method, which is defined by GraphicsEnvironment as shown:
static GraphicsEnvironment getLocalGraphicsEnvironment( )

Creating and Selecting a Font
To select a new font, we must first construct a Font object that describes that font. One Font constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
Here, fontName specifies the name of the desired font. The name can be specified using either the logical or face name. All Java environments will support the following fonts: Dialog, DialogInput, Sans Serif, Serif, and Monospaced. Dialog is the font used by your system’s dialog boxes. Dialog is also the default if we don’t explicitly set a font. We can also use any other fonts supported by your particular environment. The style of the font is specified by fontStyle. It may consist of one or more of these three constants: Font.PLAIN, Font.BOLD, and Font.ITALIC.
To combine styles, OR them together. For example, Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by pointSize.
To use a font that we have created, we must select it using, which is defined by Component. as:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font.

Obtaining Font Information
Suppose we want to obtain information about the currently selected font. To do this, we must first get the current font by calling getFont( ). This method is defined by the Graphics class, as shown:
Font getFont( )

Once we have obtained the currently selected font, we can retrieve information about it using various methods defined by Font.