Ipt Lab Manual New.pdf

  • Uploaded by: Akansh Srivastava
  • 0
  • 0
  • August 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Ipt Lab Manual New.pdf as PDF for free.

More details

  • Words: 5,865
  • Pages: 72
Exercise: 01 Date:

JNI - Object Passing

Aim: To create a JNI program to pass object as argument from java to c program. Procedure: 1) Create a Java Application named as “Exercise1_JNI” with a java main class named as “PassingObject” and a java class named as “SimpleClass” 2) In the “SimpleClass” file do the following a. Declare a variable int count;

b. Define a method named “Increment()” to increment the count value by 10 as count=count*10; and print the count value inside the method. 3) In the “PassingObject” class/file do the following a. Define a native method declaration as follows b. public static native void changecountvalue ( SimpleClass sc); and inside the main() method perform the following

1. 2. 3. 4. 5.

Create the obj for SimpleClass as sc, assign the value of count to 10, invoke the Increment() method, invoke changecountvalue by passing ‘sc’ as argument , print the value of count before and after changecountvalue() method call.

4) Create a C/C++ application project named as “Excercise2_JNI_C” with “PassingObject.c” file in it. 5) Create headerfile & perform the necessary step to change the value of count from c program.

Program: 1. Object Passing Java Program package objectpass; import java.io.*; import java.util.*; public class ObjectPass { private int number=100; private String message="hi"; static { System.load("D:\\javapro\\ObjectC\\dist\\object.dll"); } public static void main(String[] args) { ObjectPass op=new ObjectPass();

op.modify(); System.out.println("Number In Java="+op.number+"\n"+"Text in Java="+op.message); // TODO code application logic here } private native void modify(); } C Program #include <stdio.h> #include <stdlib.h> #include <jni.h> #include "objectheader.h" JNIEXPORT void JNICALL Java_objectpass_ObjectPass_modify (JNIEnv *env, jobject job) { jclass tc=(*env)->GetObjectClass(env,job); jfieldID fid=(*env)->GetFieldID(env,tc,"number","I"); jint num=(*env)->GetIntField(env,job,fid); printf("Number in c=%d",num); num=200; (*env)->SetIntField(env,job,fid,num); jfieldID fidm=(*env)->GetFieldID(env,tc,"message","Ljava/lang/String;"); jstring mess=(*env)->GetObjectField(env,job,fidm); const char *str=(*env)->GetStringUTFChars(env,mess,NULL); printf("\nMessage in C=%s\n",str); mess=(*env)->NewStringUTF(env,"hello"); (*env)->SetObjectField(env,job,fidm,mess); }

Output:

Result: The program is successfully executed.

Exercise: 02 Date:

JNI –Sorting Array

Aim: To create a JNI program to sort the values in an array by using C++ application.

Procedure: 1. Create a java main class named as “Sorting_array” which contain only one native method as follows public native int[] ArraySorting (int[] array); and a static array declaration as Static int array[]; within the main() method perform the following. a. get the length of the array b. now using length create a new array c. from user get the values for the array d. call the method ArraySorting (int []) by passing the array values got from the user. e. assign the return value of ArraySorting() method to a new array variable called as sorted_array[] and print the sorted_array[] values. 2. create a c/c++ application with “Sorting_Array.c” file create headerfile & perform the necessary step to sort the values either in ascending or descending order using C++ and return the sorted array to the jave code.

Program: 1. Sorting without returning the values Java Program package sortdemo; import java.io.*; import java.util.*; public class SortDemo { static { System.load("D:\\javapro\\Sortingdemo\\dist\\sort.dll"); } public static void main(String[] args) { Scanner s=new Scanner(System.in); int n; n=s.nextInt(); int[] b=new int[20]; for(int i=1;i<=n;i++) b[i]=s.nextInt(); SortDemo sd=new SortDemo(); sd.sorting(b,n); // TODO code application logic here } private native void sorting(int[] b,int n); } C Program #include <stdio.h> #include <stdlib.h> #include <jni.h> #include "sortheader.h" JNIEXPORT void JNICALL Java_sortdemo_SortDemo_sorting (JNIEnv *env, jobject job, jintArray b, jint n) { int i,j,temp; jint *p=(*env)->GetIntArrayElements(env,b,NULL); for(i=1;ip[j]) { temp=p[i]; p[i]=p[j]; p[j]=temp; }

} } for(i=1;i<=n;i++) printf("%d\n",p[i]); } 2. Sorting with returning values Java Program package sortingdeemo; import java.io.*; import java.util.*; public class SortingDeemo { static { System.load("D:\\javapro\\SortingDeeemo\\dist\\sorted.dll"); } public static void main(String[] args) { Scanner s=new Scanner(System.in); int n; n=s.nextInt(); int[] b=new int[20]; int[] c=new int[20]; for(int i=0;i #include <stdlib.h> #include <jni.h> #include "soheader.h" JNIEXPORT jintArray JNICALL Java_sortingdeemo_SortingDeemo_sorting (JNIEnv *env, jobject job, jintArray b, jint n) { int i,j,temp; jint *p=(*env)->GetIntArrayElements(env,b,NULL); for(i=0;i
if(p[i]>p[j]) { temp=p[i]; p[i]=p[j]; p[j]=temp; }}} jintArray array=(*env)->NewIntArray(env,n); (*env)->SetIntArrayRegion(env,array,0,n,p); return array; } Output:

Result: The program is successfully executed.

JNI – Different Data Types and Exception handling

Exercise: 03 Date:

Question: Create a JNI program to use different types such as int, float, String & Exception Handling with c program. Aim: To create a JNI program to use different types such as int, float, String & Exception Handling with c program.

Procedure: 1. create a java main class called as “Exception_Difftypes”Define the following method(s) declaration a. public native int intMethod (int n); b. public native Boolean booleanMethod (boolean text) c. public native string stringMethod (String text); d. public native void doit() throws IllegalArgumentException; and the following method definition e. public void callback () throws NullPointerException { throw new NullPointerException(“CatchThrow.callback”) } Inside the main () function perform the following Create the object of the class and invoke the method a, b, c and print the values returned by them. In try… catch block call the d & e method. 2. Create a C/C++ application with “Exception_Differenttype.c” file Create headerfile & perform the following operation in different method. a. intMethod ()  return the product of 2 No’s b. booleanMethod ()  return the !boolean value c. StringMethod ()  return the uppercase string d. doit ()  to throw the exception

Program: 1. Exceptions Java Program package catchthrow; public class CatchThrow { static { System.load("D:\\javapro\\CatchC\\dist\\catch.dll"); } private native void catchThrow() throws IllegalArgumentException; private void callback() throws NullPointerException { throw new NullPointerException("thrown in CatchThrow.callback"); } public static void main(String[] args) { CatchThrow c = new CatchThrow(); try { c.catchThrow(); } catch (Exception e) { System.out.println("In Java:\n " + e); } } } C Program #include <stdio.h> #include <stdlib.h> #include <jni.h> #include "catchheader.h" JNIEXPORT void JNICALL Java_catchthrow_CatchThrow_catchThrow (JNIEnv *env, jobject obj) { jclass cls = (*env)->GetObjectClass(env, obj); jmethodID mid = (*env)->GetMethodID(env, cls, "callback", "()V"); jthrowable exc; if (mid == 0) { return; } (*env)->CallVoidMethod(env, obj, mid);

exc = (*env)->ExceptionOccurred(env); if (exc) { /* We don't do much with the exception, except that we print a debug message using ExceptionDescribe, clear it, and throw a new exception. */ jclass newExcCls; (*env)->ExceptionDescribe(env); (*env)->ExceptionClear(env); newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); if (newExcCls == 0) { /* Unable to find the new exception class, give up. */ return; } (*env)->ThrowNew(env, newExcCls, "thrown from C code"); }} Output:

Result: The program is successfully executed.

Exercise: 04 Date:

Account Details –Using Non-Visual Bean

Aim: To develop a JAVA Bean to calculate the current balance in your account and display the balance detail as a message using JFrame. Procedure: 1. Create a java bean class named as ‘AccountDetail_Bean’. Define the following Properties a. private String Date b. private long Acct_no c. private String Name d. private double Withdraw_amount e. private final double Balance_amt = 100000 Methods a. public void generate_SystemDate( ) It gets the system date and from this call setDate( ) method. b. public double current_balance( ) This method calculates balance as balance = Balance_amt – withdraw_amount. If balance_amt is less than Withdraw_amount then return balance_amt itself, otherwise return the balance calculated. 2. Create another project with java swing Form. In this create a JFrame called as Account_Form. Design the form with following details.

3. On double clicking the “OK” button a. Set Accountno,name,Withdraw_amount, values of Bean class by the values entered in the jtextfield Text_AccountNo, Text-Name and Text_withdraw respectively.

b. Get the balance from the Bean class and set the “Text-balance” jtextfield Box with it. c. Calculate the current balance by invoking the method current_balance( ) defined in Bean class and set the calculated current balance to the label “lbl_Balance”. 4. On double clicking the ‘Message button 5. Display the message as “Balance in your Account no: as on is ” 6. The message should be displayed using JoptionPane.showMessageDialog(null, output, “sms”, 1) Program: AccountDetail_Bean.java import java.util.Calendar; import java.util.GregorianCalendar; public class AccountDetail_Bean { private String Date; private long Acct_no; private String Name; private final double Balance_amt = 100000; private double Withdraw_amount; public double getWithdraw_amount() { return Withdraw_amount; } public void setWithdraw_amount(double Withdraw_amount) { this.Withdraw_amount = Withdraw_amount; } public double getBalance_amt() { return Balance_amt; } public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public long getAcct_no() { return Acct_no; } public void setAcct_no(long Acct_no) { this.Acct_no = Acct_no; } public String getDate() { return Date; } public void setDate(String Date) { this.Date = Date; } public void generate_SystemDate() { Calendar cal = new GregorianCalendar(); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR);

int day = cal.get(Calendar.DAY_OF_MONTH); setDate("Date is : " + day + "/" + (month + 1) + "/" + year); } public double current_Balance { double balance = Balance_amt-Withdraw_amount; if(Withdraw_amount>Balance_amt) { return Balance_amt; } else { return balance; } } } Account_form.java import javax.swing.JOptionPane; public class Account_form extends javax.swing.JFrame { public Account_form() { setSize(500, 650); initComponents(); accountDetail_Bean1.generate_SystemDate(); Lbl_date.setText(accountDetail_Bean1.getDate()); } private void Button_OKActionPerformed(java.awt.event.ActionEvent evt) { accountDetail_Bean1.setName(Text_name.getText()); accountDetail_Bean1.setAcct_no(Long.parseLong(Text_AccountNo.getText())); double bala=accountDetail_Bean1.getBalance_amt(); Double balance = new Double(bala); Text_balance.setText(balance.toString()); accountDetail_Bean1.setWithdraw_amount(Double.parseDouble(Text_Withdraw.getText())); double current_balance=accountDetail_Bean1.current_Balance(); Double current_bala = new Double(current_balance); Lbl_Balance.setText("Current Balance is=="+current_bala.toString()); } private void Button_MsgActionPerformed(java.awt.event.ActionEvent evt) { String Message="Balance in your Account No:"+accountDetail_Bean1.getAcct_no()+ " as on "+ Lbl_date.getText()+" is :"+ accountDetail_Bean1.getBalance_amt(); JOptionPane.showMessageDialog(null, Message, "SMS", 1); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Account_form().setVisible(true); } }); } }

Steps to Create Non-Visual Beans 1. Create Java Class Library 

Open NetBeans IDE  Select File  Select New Project



Select Java in Categories  Select Java Class Library in Projects  Click on Next button



Enter the Project Name  Click on Finish button



Now the project is created



Right-click on the package  Select New  Select Java Class…

 

Enter Class Name and Package name  Click on Finish button Now the Java class is created



To add properties: Right-Click on the Class  Select Insert Code…



Select Add Property…



Enter the property name, change data type and other details  Click on OK button



Add methods  Compile the program



Right-Click on the file  Select Tools  Select Add to Palette…



Select Beans  Click on OK button

2. Using the Non-Visual Beans 

Select File menu  Select New Project  Select Java in Categories  Select Java Application in Projects  Click on Next button



Enter the Project Name  Click on Finish button



Right-Click on the package  Select New  Select JFrame Form…



Enter the Frame name  Select the package…  Click the Finish button



Drag and drop the Beans from the Beans Palette



Add the Swing controls in the JFrame



Change the text property of the jLabel, jTextField and jButton controls and set the width of the controls



Double-Click on the buttons and write the code

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { arithmeticBeans1.setA(Integer.parseInt(jTextField1.getText())); arithmeticBeans1.setB(Integer.parseInt(jTextField2.getText())); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { jLabel4.setText(String.valueOf(arithmeticBeans1.getA())); jLabel5.setText(String.valueOf(arithmeticBeans1.getB())); jLabel6.setText(""); } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { jLabel6.setText(String.valueOf(arithmeticBeans1.add())); } private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { int x=Integer.parseInt(jTextField1.getText()); int y=Integer.parseInt(jTextField2.getText()); int z=arithmeticBeans1.add(x, y); jTextField3.setText(String.valueOf(z)); } 

Right-Click on the JFrame Java file and Run the file

Sample Output:

Result: The program is successfully executed.

Exercise: 05 Date:

Color Bean – Using Visual Bean

Question: Create a visual java bean using mouse event for moving a small oval along with the cursor point. Aim:

Procedure: 1. Design a Java Bean class named as “MouseMove_Bean” extends JPanel class. with properties :- private int Circle_size=20 private int xm, ym ; method:- private color randomColor() {……} > used to generate random colors. [Hint- use predefined color() class  takes 3 int org for color() constructor.Math.random() used to provide random no.] Overridden methods ( From JPanel) a. public void paintComponent (Graphics g) Set the color by calling random color () method & draw the oval with the “Circlesize” property defined above b. public Dimension get( ) Return new Dimension (200, 200) for setting the size of the JPanel Inside the Constructor a. Set the background for the JPanel (Bean created) and addMouseMotionListener to perform Mousemoved event. b. Inside the MouseMoved () event method get the x, y position of the cursor and set it from xm & ym variables. Note :- While drawing the oval use xm, ym, circle-size, so that circle moves when xm, ym changes when mouse is moved. 2.Design a JApplet Form called as “MouseMove_Form” Here drag & drop the above bean created. 3.Execute the JApplet.

Program: MouseMove_Bean.java import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JPanel; public class MouseMove_Bean extends JPanel { private int Circle_Size=20; private int xm,ym; public int getCircle_Size() { return Circle_Size; } public void setCircle_Size(int Circle_Size) { this.Circle_Size = Circle_Size; } private Color randomcolor() { int r=(int)(255*Math.random()); int g=(int)(255*Math.random()); int b=(int)(255*Math.random()); return new Color(r,g,b); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(randomcolor()); g.fillOval(xm - Circle_Size/2, ym - Circle_Size/2, Circle_Size, Circle_Size); } public MouseMove_Bean() { setBackground(Color.CYAN); addMouseMotionListener (new MouseAdapter() { @Override public void mouseMoved(MouseEvent me) { xm = me.getX(); ym = me.getY(); repaint(); } }); } @Override public Dimension getPreferredSize() { return new Dimension(200, 200); } }

Create a file named as Mousemove_form.java and drag and drop the bean added to the pallete

Steps to Create Visual Beans 1. Create Java Class Library 

Open NetBeans IDE  Select File  Select New Project



Select Java in Categories  Select Java Class Library in Projects  Click on Next button



Enter the project name  Click on Finish button



Right-click on the package  Select New  Select JPanel Form



Enter the JPanel class name  Enter the package name  Click on Finish button



Design the JPanel ( drag and drop Swing controls)



Change the text property of the jLabel, jTextField and jButton controls and set the width of the controls



Double-Click on the buttons and write the code  Compile the program



Right-Click on the file  Select Tools  Select Add to Palette…



Select AWT  Click on OK button

2. Using the Non-Visual Beans 

Select File menu  Select New Project  Select Java in Categories  Select Java Application in Projects  Click on Next button



Enter the Project Name  Click on Finish button



Right-Click on the package  Select New  Select JFrame Form…



Enter the Frame name  Select the package…  Click the Finish button



Drag and drop the Beans from the AWT Palette



Run the JFrame file

Output:

Result: The program is successfully executed.

Stateless Session Bean – Shopping Cart

Exercise: 06 Date: Aim:

To create a stateless session bean for shopping cart application Procedure: 1) Create a Java class Library named as “ Exercise5B_Remote” 2) Create JavaEE Enterprise Application named as “Exercise5B_EntAppln_ShopCart” 3) In Exercise5B_EntAppln_ShopCart-ejb project add a java class file named as “Shop.java” under “ejbpkg” user defined package a. Include the following methods inside Shop.java i. void addItem(int parameter) for adding item ii. void removeItem(int buy)for reducing the item count iii. int stock() to return the item value b. One variable int item=0; 4) Create JavaEE Enterprise Application Client named as “Exercise5B_Shopcart_Client” with one java main class named as “Shop_Client.java” under the auto generated package same as the project name. a. Inside the Shop_client file under main function do the following operation for two different customers i. Use choice, no_items as int variables ii. Get any one choice as follows with a variable int choice.  1To buy – call the method removeItem() by passing no:of items (no_items) to buy as parameter  2To Add – call the method addItem() by passing no:of items(no_items) to add to stock  0 To finish the transaction iii. Repeat the above process for a single customer minimum of 5 times

Program: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package shopcartclientapp; import java.util.Scanner; import javax.ejb.EJB; import shopcart.ShopCartSessionBeanRemote; /** * * @author hp */ public class Main { @EJB private static ShopCartSessionBeanRemote shopCartSessionBean; /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int choice=1,amt=0; while(choice!=0){ System.out.println("Enter your choice(1-3):"); Scanner sc=new Scanner(System.in); choice=sc.nextInt(); if(choice!=3&&choice!=0) { System.out.println("Enter your amount:"); amt=sc.nextInt(); }

if(choice==1){ shopCartSessionBean.removeItem(amt); } else if(choice==2){ shopCartSessionBean.addItem(amt); } else if(choice==3){ System.out.println("Stock= "+shopCartSessionBean.stock()); } } } }

Output: values adding: 2018-10-28T10:02:07.622+0200|INFO: Hello from servlet 2018-10-28T10:02:07.622+0200|INFO: shoppingCart created 2018-10-28T10:02:07.622+0200|INFO: product Nokia 1 added 2018-10-28T10:02:07.622+0200|INFO: Hello from servlet

2018-10-28T10:02:07.622+0200|INFO: product Nokia 2 added

Result: The program is successfully executed.

Exercise: 07 Date:

Stateful Session Bean – Banking Application

Aim: To create a stateful session bean for Banking Application. Procedure: 1) Create a Java class Library named as “ Exercise5A_Remote” 2) Create JavaEE Enterprise Application named as “Exercise5A_EntAppln_BankAppln” 3) In Exercise5A_EntAppln_BankAppln-ejb project add a java class file named as “Bank.java” under “ejbpkg” user defined package a. Include the following methods inside Bank.java i. void withDraw(int amount) for reducing the balance ii. void deposit(int dep_amt)for adding the balance iii. int balance() to return the balance amount b. One variable int balance =100000 4) Create JavaEE Enterprise Application Client named as “Exercise5A_BankAppln_Client” with one java main class named as “Bank_Client.java” under the auto generated package same as the project name. a. Inside the Bank_client file under main function do the following operation for two different customers i. Use choice, amount as int variables ii. Get any one choice as follows with a variable int choice.  1To withdraw – call the method withdraw() by passing amount as parameter to reduce the balance  2To deposit – call the method deposit() by passing amount to add the amount to the balance  0 To finish the transaction iii. Repeat the above process for a single customer minimum of 5 times Program: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bankappclientapp; import bankapp.BankAppSessionBeanRemote; import java.util.Scanner; import javax.ejb.EJB; /** * * @author hp */

public class Main { @EJB private static BankAppSessionBeanRemote bankAppSessionBean; /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int choice=1,amt=0; while(choice!=0){ System.out.println("Enter your choice(1-3):"); Scanner sc=new Scanner(System.in); choice=sc.nextInt(); if(choice!=3&&choice!=0) { System.out.println("Enter your amount:"); amt=sc.nextInt(); }

if(choice==1){ bankAppSessionBean.withDraw(amt); } else if(choice==2){ bankAppSessionBean.deposit(amt); } else if(choice==3){ System.out.println(bankAppSessionBean.balance()); } } } } Output:

Result: The program is successfully executed.

Exercise: 08 Date:

Developing JMS Application

Question: Aim: To developing java message service application for any department analysis of educational institution Procedure: Creating the JMS Server To create the JMS Server: 1. From the WebLogic Administration Console, select the domain in which you want to create the JMS Server. 2. Click on YourDomain > Services > Messaging > JMS Servers 3. In the right panel click the New button.

4. On Create a New JMS Server, enter a value for the name of the JMS server to be created. In this guide, the name is Test-JMSServer. 5. Use the pulldown to select the Persistence Store. 6. Click the Next button.

7. On Create a New JMS Server, select the Weblogic server node and click the Finish button. As shown below, at this point using the example in this guide a JMS server called Test-JMSServer is created. This Test-JMSServer is targeted to AdminServer. However this can be targeted to any other container available, which may not necessarily be AdminServer

F.2 Creating the JMS Module To create a subscriber queue on WebLogic Server: 1. In the WebLogic Administration Console, select the domain into which you want to create the JMS Module. 2. Click on YourDomain > Services > Messaging > JMS Modules 3. In the right panel click the New button.

4. On Create JMS System Module, enter a value for the name of the JMS module to be created. In this guide, the name is Test-SystemModule. 5. Click the Next button.

6. On Create JMS System Module, select the target of Weblogic server node. 7. Click the Finish button. As shown below at this point, using the example in this guide, the Test-SystemModule is created. This Test- SystemModule is targeted to AdminServer. However this can be targeted to any other container.

F.3 Creating the JMS Resource Use this procedure to create a JMS resource such as connection factory, queue, or topic in the JMS Module you created in the previous section. To create a JMS Resource: 1. Click the JMS Module where you want to create a resource (in this guide Test-SystemModule).

2. On Settings for <Module_Name> , click the New Button.

3. On Create a New JMS System Module Resource, select the radio button for the resource type to be created. In this example, Connection Factory is selected.

4. On Create a New JMS System Module Resource, enter Connection Factory name and JNDI name for this Connection Factory. 5. Click the Next button.

6. On Create a New JMS System Module Resource, use the pulldown to select the Subdeployment. If no existing Subdeployment can be used click on Create a New Subdeployment button.

7. On Create a New Subdeployment, enter a name for a new Subdeployment. 8. Click the OK button.

9. On Create a New JMS System Module Resource, click the checkbox next to the JMS Server for which you just created a resource. 10. Click the Next button.

11. On Create a New JMS System Module Resource, click the radio button for Queue. 12. Click the Next button.

13. On Create a New JMS System Module Resource, enter a I and JNDI Name for this Queue. 14. Click the Next button.

15. On Create a New JMS System Module Resource, select the Subdeployment. 16. Click the Finish button. 17. As shown below, verify that both the xxxx

JMS CODING: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jmspubsubmodel; import java.io.Serializable; public class EventMessage implements Serializable { private static final long serialVersionUID = 1L; private int messageId; private String messageText = ""; public EventMessage(int id, String messageText) { this.messageId = id; this.messageText = messageText; } public int getMessageId() { return messageId; }

public void setMessageId(int messageId) { this.messageId = messageId; } public String getMessageText() { return messageText; } public void setMessageText(String messageText) { this.messageText = messageText; } public String toString(){ return "Message Id = "+getMessageId()+" ; Message Text = "+getMessageText(); } } FIRST CLIENT: package jmspubsubmodel; import java.util.Properties; import javax.jms.JMSException; import javax.jms.ObjectMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class FirstClient { private Context context = null; private TopicConnectionFactory factory = null; private TopicConnection connection = null; private TopicSession session = null; private Topic topic = null; private TopicPublisher publisher = null; public FirstClient() { Properties initialProperties = new Properties(); initialProperties.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory"); initialProperties.put(InitialContext.PROVIDER_URL, "tcp://localhost:3035"); try { context = new InitialContext(initialProperties); factory = (TopicConnectionFactory) context .lookup("ConnectionFactory"); topic = (Topic) context.lookup("topic1"); connection = factory.createTopicConnection(); session = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE); publisher = session.createPublisher(topic); EventMessage eventMessage = new EventMessage(1,

"Message from FirstClient"); ObjectMessage objectMessage = session.createObjectMessage(); objectMessage.setObject(eventMessage); connection.start(); publisher.publish(objectMessage); System.out.println(this.getClass().getName() + " has sent a message : " + eventMessage); } catch (NamingException e) { e.printStackTrace(); } catch (JMSException e) { e.printStackTrace(); } if (context != null) { try { context.close(); } catch (NamingException ex) { ex.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (JMSException ex) { ex.printStackTrace(); } } } public void sendMessage() { } public static void main(String[] args) { FirstClient firstClient = new FirstClient(); firstClient.sendMessage(); } }

SECOND client: package jmspubsubmodel; import java.util.Properties; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.ObjectMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException;

public class SecondClient { private Context context = null; private TopicConnectionFactory factory = null; private TopicConnection connection = null; private TopicSession session = null; private Topic topic = null; private TopicSubscriber subscriber = null; public SecondClient() { } public void receiveMessage() { Properties initialProperties = new Properties(); initialProperties.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory"); initialProperties.put(InitialContext.PROVIDER_URL, "tcp://localhost:3035"); try { context = new InitialContext(initialProperties); factory = (TopicConnectionFactory) context .lookup("ConnectionFactory"); topic = (Topic) context.lookup("topic1"); connection = factory.createTopicConnection(); session = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE); subscriber = session.createSubscriber(topic); connection.start(); Message message = subscriber.receive(); if (message instanceof ObjectMessage) { Object object = ((ObjectMessage) message).getObject(); System.out.println(this.getClass().getName() + " has received a message : " + (EventMessage) object); } } catch (NamingException e) { e.printStackTrace(); } catch (JMSException e) { e.printStackTrace(); } if (context != null) { try { context.close(); } catch (NamingException ex) { ex.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (JMSException ex) {

ex.printStackTrace(); } } } public static void main(String[] args) { SecondClient secondClient = new SecondClient(); secondClient.receiveMessage(); } } THIRD CLIENT: package jmspubsubmodel; import java.util.Properties; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.ObjectMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; import javax.jms.TopicSubscriber; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class ThirdClient { private Context context = null; private TopicConnectionFactory factory = null; private TopicConnection connection = null; private TopicSession session = null; private Topic topic = null; private TopicSubscriber subscriber = null; public ThirdClient() { } public void receiveMessage() { Properties initialProperties = new Properties(); initialProperties.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory"); initialProperties.put(InitialContext.PROVIDER_URL, "tcp://localhost:3035"); try { context = new InitialContext(initialProperties); factory = (TopicConnectionFactory) context .lookup("ConnectionFactory"); topic = (Topic) context.lookup("topic1"); connection = factory.createTopicConnection(); session = connection.createTopicSession(false,

TopicSession.AUTO_ACKNOWLEDGE); subscriber = session.createSubscriber(topic); connection.start(); Message message = subscriber.receive(); if (message instanceof ObjectMessage) { Object object = ((ObjectMessage) message).getObject(); System.out.println(this.getClass().getName() + " has received a message : " + (EventMessage) object); } } catch (NamingException e) { e.printStackTrace(); } catch (JMSException e) { e.printStackTrace(); } if (context != null) { try { context.close(); } catch (NamingException ex) { ex.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (JMSException ex) { ex.printStackTrace(); } } } public static void main(String[] args) { ThirdClient thirdClient = new ThirdClient(); thirdClient.receiveMessage(); } } Output:

Result: The program is successfully executed.

Exercise: 09 Date:

Simple Swing applications in Java using Jython

Aim: To create a simple Swing application in Java using Jython Procedure: Simple GUI Application with JYTHON 1. Download nbplugin , extract it and add it in netbeans Tools->plugins->downloaded->check for the nbplugin(extracted folder) select all .nbm files and add. 2. Download jython installer 2.7.0 from jython.org and install it Go to the downloaded folder and execute the following command in command prompt java –jar jython_installer_2.7.0.jar jython _installer for simple jython modules. In case of java integration, install jyhton_standalone.jar 3. Once python plugin is added with netbeans , you can see python project in netbeans.

4. When you create python project for the first time , you need to specify python platform. Just select the folder of jython ->bin .

5. Once python module is created copy the below code. from javax.swing import * from java.awt import * from student import Student from com.ziclix.python.sql import zxJDBC url = "jdbc:mysql://localhost:3306/dbstudent?zeroDateTimeBehavior=convertToNull" user = "root" password="" driver = "com.mysql.jdbc.Driver" frame=JFrame('Application Details', defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(300,400) ) panel=JPanel(); frame.add(panel); def react(event):

index=lst.selectedIndex lbl4.setText(state[index]) total=((int(phyfield.getText()))+(int(chefield.getText()))+(int(matfield.getText()))) avg=(total/3) total1=str(total) if avg>=90: option='Application Selected with 75% sscholarship' elif avg<90 and avg>=80: option='Application selected with 50% scholarship' elif avg>=60 and avg<80: option='Application selected with no scholarship' else: option='Sorry not Selected' with zxJDBC.connect(url, user, password, driver) as conn: with conn: with conn.cursor() as c: c.execute("insert into studentdetails values(?,?,?,?,?,?,?,?,?)",[namefield.getText(),numberfield.getText(),grp.getSelection().getActionComm and(),lbl4.getText(),int(phyfield.getText()),int(chefield.getText()),int(matfield.getText()),total,option]) student=Student(namefield.getText(),numberfield.getText(),grp.getSelection().getActionCommand(),lbl 4.getText(),int(phyfield.getText()),int(chefield.getText()),int(matfield.getText()),total,option) student.print(); JOptionPane.showMessageDialog(frame,"Welcome "+namefield.getText()+"\n"+"Your Registration Number is"+numberfield.getText()+"\n"+"Gender is: "+grp.getSelection().getActionCommand()+"\n"+"State :"+lbl4.getText()+"\n"+"Total: "+total1+"\n"+"Status: "+option+"\n"+"Successfully Registered") #def listselect(event): #index=lst.getSelectedIndex #lbl4.setText(state[index]) #t=JLabel("ENTER YOUR APPLICATION DETAILS",JLabel.CENTER) #t.setBounds(200,200,200,200) #panel.add(t) namefield=JTextField('',20) label=JLabel("Name: ") #label.setBounds(60,20,40,20) panel.add(label) #namefield.setBounds(120,20,40,20) panel.add(namefield) numberfield=JTextField('',20) label1=JLabel("Reg.No: ") #label1.setBounds(60,20,40,20) panel.add(label1) #numberfield.setBounds(120,20,40,20) panel.add(numberfield)

#panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) #frame.add(panel) rb1 = JRadioButton("Male") rb1.setActionCommand("Male") rb2 = JRadioButton("Female") rb2.setActionCommand("Female") frame.add(panel) grp = ButtonGroup() grp.add(rb1) grp.add(rb2) lbl1 = JLabel("Gender :") #panel.add(Box.createVerticalGlue()) #panel.add(Box.createRigidArea(Dimension(0,10))) panel.add(lbl1) panel.add(rb1) panel.add(rb2) lbl2=JLabel("Languages Known: ") box1 = JCheckBox("Tamil") box2 = JCheckBox("English") box3=JCheckBox("Hindi") box4=JCheckBox("Telugu") box5=JCheckBox("Physically Challenged") panel.add(lbl2) panel.add(box1) panel.add(box2) panel.add(box3) panel.add(box4) panel.add(box5) lbl3=JLabel("Select State :") lbl4=JLabel() state=("Andhra Pradesh","Telangana","TamilNadu","Maharashtra","Assam","Kerala","Karnataka","Uttar Pradesh","Madhya Pradesh","Punjab","Haryana","Himachal Pradesh","Orissa","West Bengal","Tripura","Sikkim","Nagaland","Arunachal Pradesh","Rajasthan","Meghalaya","Goa","Gujarat","Bihar","Chhattisgarh","Jammu and Kashmir","Manipur","Jharkand","Mizoram","Uttranchal") lst=JComboBox(state) panel.add(lbl3) panel.add(lst) lbl5=JLabel("Enter the Mark details of (Phy/Che/Mat) Out of 100",JLabel.CENTER) phylabel=JLabel("Physi") phyfield=JTextField(20) chelabel=JLabel("Chemi") chefield=JTextField(20) matlabel=JLabel("Maths")

matfield=JTextField(20) panel.add(lbl5) panel.add(phylabel) panel.add(phyfield) panel.add(chelabel) panel.add(chefield) panel.add(matlabel) panel.add(matfield) button=JButton("Submit",actionPerformed=react) button.setBounds(60,20,40,20) panel.add(button) frame.getContentPane().add(panel,"Center") frame.visible= True

Program: Java application for student details using Jython package student; public class Student { String name; String regno; String gender; String state; int phy; int che; int mat; int tot; String status; public Student(String name,String regno,String gender,String state,int phy,int che,int mat,int tot,String status) { this.name=name; this.regno=regno; this.gender=gender; this.state=state; this.phy=phy; this.che=che; this.mat=mat; this.tot=tot; this.status=status; } public void print() { System.out.println("Name:"+name); System.out.println("Reg no:"+regno); System.out.println("Gender:"+gender);

System.out.println("State:"+state); System.out.println("Physics:"+phy); System.out.println("Chemistry:"+che); System.out.println("maths:"+mat); System.out.println("Total:"+tot); System.out.println("Status:"+status); } } 6. Clean and build the java project. Add the generated jar file of the project to the python platforms. Tools->Pyton platforms->pythonpath tab->add the jar file

7. Next step is database connectivity, for this you need to download zxJDBC jar and include in project properties. Also include mysql-connector.jar. Create table in mysql and insert some records manually.

8. Run the python module/project. Output:

The highlighted text is displayed with java integration.

Result: The program is successfully executed.

Exercise: 10 Date:

Web application with Django using Jython

Aim: To design a Web application with Django using Jython Procedure: CREATE YOUR FIRST DATABASE -DRIVEN APP AND USE THE DJANGO ADMIN Initial Setup 1. Create a new directory for our code on the Desktop called mb 2. Install Django in a new virtual environment 3. Create a new project called mb_project 4. Create a new app call posts 5. Update settings.py a) Creation of project structure

b) After creation of project structure c) Migrate the project Then execute the migrate command to create an initial database based on Django’s default settings.

d) Explanation 1. Technically a db.sqlite3 file is created the first time you run either migrate or run server. 2. Using run server configures a database using Django’s default settings, however migrate will sync the database with the current state of any database models contained in the project and listed in INSTALLED_APPS. 3. In other words, to make sure the database reflects the current state of your project you’ll need to run migrate (and also make migrations) each time you update a model.. e) To confirm everything works correctly, spin up our local server

f)

Fds

g) Create a database model

1. Our first task is to create a database model where we can store and display posts from our users. Django will turn this model into a database table for us.

2. In real-world Django projects, it’s often the case that there will be many complex, interconnected database models but in our simple message board app we only need one 3. Open the posts/models.py file and look at the default code which Django provides:

h) After creating models, Activating models Note that we’ve created a new database model called Post which has the database field text. We’ve also specified the type of content it will hold, TextField(). Django provides many model fields supporting common types of content such as characters, dates, integers, emails, and so on. 1. First we create a migration file with the make migrations command which generate the SQL commands for preinstalled apps in our INSTALLED_APPS setting. Migration files do not execute those commands on our database file; rather they are a reference of all new changes to our models. This approach means that we have a record of the changes to our models over time. i) Activating Models 2. Second we build the actual database with migrate which does execute the instructions in our migrations file.( Hint : before making make sure installed apps include the posts ) (mb) $ python manage.py make migrations posts (mb) $ python manage.py migrate posts j) DJANGO admin To use the Django admin, we first need to create a superuser who can login. In your command line console, type syntax below and respond to the prompts for a username, email, and password: python manage.py createsuperuser

k) Check

Restart the Django server with python manage.py run server and in your browser goes to http://127.0.0.1:8000/admin/. You should see the admin’s login screen:

# posts/admin.py from django.contrib import admin from .models import Post admin.site.register(Post)

l)

Created Page Now let’s create our first message board post for our database. Click on the + Add button opposite Posts. Enter your own text in the Text form field.

m) Modify the models # posts/models.py from django.db import models class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] n) After Posted message

o) View 1. In order to display our database content on our homepage, we have to wire up our views, templates, and URLConfs. This pattern should start to feel familiar now. 2. Let’s begin with the view. Earlier in the book we used the built-in generic Template View to display a template file on our homepage. Now we want to list the contents of our database model. Fortunately this is also a common task in web development and Django comes equipped with the generic class-based ListView. p) Modify view # posts/views.py from django.views.generic import ListView from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' q) Create Template Folder

Let’s start with the template. Create a project-level directory called templates and a home.html template file. >> mkdir templates Create home.html inside the template folder Then update the DIRS field in our settings.py file so that Django knows to look in this templates folder. # settings.py TEMPLATES = [ 1 { ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], # new ... }, ]

Message board homepage

    {% for post in object_list %} 2
  • {{ post }}
  • {% endfor %}
# posts/views.py context_object_name = 'all_posts_list' # new r) URL Modification 1. #mb_project_sm/urls from django.contrib import admin from django.conf.urls import include,url urlpatterns = [ url('admin/', admin.site.urls), url('',include('posts.urls')), ]

2. Then create urls.py inside the posts posts/urls.py from django.conf.urls import url from .views import HomePageView urlpatterns = [ url('', HomePageView.as_view(), name='home'), ] s) Run the server

Output:

Result: The program is successfully executed.

VALUE ADDED EXPERIMENT

Exercise: 11 Date:

Multiple Inheritance – Employee Detail

Aim: To develop a payroll System in JAVA to illustrate the concept of Multiple Inheritance. Procedure: 1. Design a interface called as “NetPayCalculation” with the following method declarations. a.void grosspaycalculation(); b.void taxcalculation(); c.float netpaycalculation(); 2.Design a simple class called as “Employee” with the following variables & methods Variables are :int ID_No; String Name, DOJ, Designation, PAN_No, Department; float Basic_pay; Methods are:void get_Data()  get all the variables defined/mentioned above 3.Design a main class which called “payroll” extends and implements the above mentioned class & interface respect with following variables & methods. Variables are:float gross-pay, Taxable_amount, Net_pay; Method :void display_details() to display all the details about an employee. Specifications :grosspay calculation method: Define 2 float variables DA, HRA Where DA= 50% of basic_pay HRA= 20% of basic_pay Gross_pay = sum of DA, HRA & Basic_pay Tax calculation method: If the total income for 12 months is between >=1,00,000 & <2,00,000 then Taxable _amount = 20% of gross_pay else if > 3,00,000 Taxable_amount = 30% of gross_pay Netpaycalculation method: From this method call the grosspay & tax calculation methods and calculate the Net_pay as gross_pay – taxable_amount; Return the net_pay In main() method create an object & call the get_data() & display_details() methods.

Output:

Result:

The program is successfully executed.

Related Documents

Ipt Lab Manual New.pdf
August 2019 23
Ipt
November 2019 24
Lab Manual
May 2020 7
Ipt Project
November 2019 11
Tcs 151251 Lab Manual
June 2020 0

More Documents from ""