· 6 years ago · Aug 28, 2019, 07:38 AM
1Practical No - 1
2Aim: Write a program to implement the following Substitution Cipher Techniques:
3
4Practical Creaser Cipher:-
5
6import java.io.*;
7public class CeaserCipher
8{
9 static String s;
10 static char ch;
11 public String encrypt(String str)
12 {
13 s="";
14 for(int i=0;i<str.length();i++)
15 {
16 if(str.charAt(i)=='x')
17 s+='a';
18 else if(str.charAt(i)=='y')
19 s+='b';
20 else if(str.charAt(i)=='z')
21 s+='c';
22 else
23 {
24 ch=str.charAt(i);
25 s+=(char)(ch+3);
26 }
27
28 }
29 return s;
30 }
31 public String decrypt(String str)
32 {
33 s="";
34 for(int i=0;i<str.length();i++)
35 {
36 if(str.charAt(i)=='a')
37 s+='x';
38 else if(str.charAt(i)=='b')
39 s+='y';
40 else if(str.charAt(i)=='c')
41 s+='z';
42 else
43 {
44 ch=str.charAt(i);
45 s+=(char)(ch-3);
46 }
47
48 }
49 return s;
50 }
51 public static void main(String[] args)throws Exception
52 {
53 CeaserCipher cc=new CeaserCipher();
54 String en;
55 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
56 System.out.println("Enter your text: ");
57 en=cc.encrypt(br.readLine().toLowerCase());
58 System.out.print("ENCRYPTED TEXT IS: "+en+"\n");
59 System.out.println("DECRYPTED TEXT IS: "+cc.decrypt(en));
60 }
61 }
62
63Practical monoalphabetic :-
64
65import java.io.*;
66public class MonoAlphabetic
67{
68
69 public static char plaintext[]={'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i','j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v','w', 'x', 'y', 'z', ' ', '_'};
70 public static char charactertext[]={'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C','V', 'B', 'N', 'M','^','*'};
71 public static String doEncryption(String s)
72 {
73 char ciphertext[]=new char[(s.length())];
74 for(int i=0;i<s.length();i++)
75 {
76 for(int j=0;j<28;j++) //we have added two more character i.e space and underscore(26+2=28)
77 {
78 if(plaintext[j]==s.charAt(i))
79 {
80 ciphertext[i]=charactertext[j];
81 break;
82 }
83 }
84 }
85 return(new String(ciphertext));
86 }
87 public static String doDecryption(String s)
88 {
89 char newplaintext[]=new char[(s.length())];
90 for(int i=0;i<s.length();i++) //we have added two more character i.e space and underscore(26+2=28)
91 {
92 for(int j=0;j<28;j++)
93 {
94 if(charactertext[j]==s.charAt(i))
95 {
96 newplaintext[i]=plaintext[j];
97 break;
98 }
99 }
100 }
101 return(new String(newplaintext));
102 }
103 public static void main(String[] args) throws IOException
104 {
105 MonoAlphabetic ma=new MonoAlphabetic();
106 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
107 System.out.println("Entr your text: ");
108 String in=ma.doEncryption(br.readLine().toLowerCase());
109 System.out.print("Ciphered_Text is: "+in+"\n");
110 System.out.println("Decrypted_Text is: "+ma.doDecryption(in));
111 } }
112
113
114Practical 02 Vernam Cipher:-
115
116import java.lang.Math;
117import java.util.*;
118public class VernamCipher
119{
120 public static void main(String args[])
121 {
122
123 String text, key, output = "";
124 char t, k;
125 int x;
126 Scanner s = new Scanner(System.in);
127 System.out.println("Enter text to Encrypt/Decrypt: ");
128 text = s.nextLine();
129 System.out.println("Enter One Time Password: ");
130 key = s.nextLine();
131 for(int i = 0;i < text.length(); i++)
132 {
133 t = text.charAt(i);
134 k = key.charAt(i);
135 x = t ^ k;
136 output += (char)(x+96);
137 }
138 System.out.println("Encrypted/Decrypted Text is : " + output);
139 }
140}
141
142
143Practical 03:-
144
145a) Railfence:-
146
147public class Railfence
148{
149 public static void main(String[] args)
150 {
151 String input = "inputstring";
152 String output = "";
153 int len = input.length(),flag = 0;
154 System.out.println("Input String : " + input);
155 for(int i=0;i<len;i+=2)
156 {
157 output += input.charAt(i);
158 }
159 for(int i=1;i<len;i+=2)
160 {
161 output += input.charAt(i);
162 }
163
164 System.out.println("Ciphered Text : "+output);
165 }
166
167}
168
169b)Simple columnar technique
170
171
172import java.io.*;
173public class SCTS
174{
175 public static void main(String[] args) throws IOException
176 {
177 BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
178 System.out.println("Enter your plain text");
179 String accept=br.readLine();
180 System.out.println("Enter no of rows");
181 int r=Integer.parseInt(br.readLine());
182 System.out.println("Enter no of cols");
183 int c=Integer.parseInt(br.readLine());
184 int count=0;
185 char cont[][]=new char[r][c];
186 for(int i=0;i<r;i++)
187 {
188 for(int j=0;j<c;j++)
189 {
190 if(count>=accept.length())
191 {
192 cont[i][j]=' ';
193 count++;
194 }
195 else
196 {
197 cont[i][j]=accept.charAt(count);
198 count++;
199 }
200 }
201 }
202
203 System.out.println("\nEnter the order of choices");
204 int choice[]=new int[c];
205 for(int k=0;k<c;k++)
206 {
207 System.out.println("choice" +k+ "-->");
208 choice[k]=Integer.parseInt(br.readLine());
209 }
210 System.out.println("\nCipher text in matrix is -->");
211 String cipher=" ";
212 for(int j=0;j<c;j++)
213 {
214 int k=choice[j];
215 for(int i=0;i<r;i++)
216 {
217 cipher+=cont[i][k];
218 }
219 }
220 cipher=cipher.trim();
221 System.out.println(cipher);
222 }
223
224}
225
226PRACTICAL NO 4:-
227
228
229import java.io.*;
230import javax.crypto.*;
231public class DESFile
232{
233 Cipher ecipher,dcipher;
234 byte[] buf=new byte[1024];
235 public DESFile(SecretKey key)
236 {
237 try
238 {
239 ecipher=Cipher.getInstance("DES");
240 ecipher.init(Cipher.ENCRYPT_MODE,key);
241 dcipher=Cipher.getInstance("DES");
242 dcipher.init(Cipher.DECRYPT_MODE,key);
243 }
244 catch(Exception e)
245 {
246 System.out.println("Exception occur:"+e);
247 }
248 }
249
250 public void encrypt(InputStream in,OutputStream out)
251 {
252 try
253 {
254 int numRead=0;
255 out=new CipherOutputStream(out,ecipher);
256 while((numRead=in.read(buf))>=0)
257 {
258 out.write(buf,0,numRead);
259 }
260 out.close();
261 }
262 catch(Exception e)
263 {
264 System.out.println("Exception occur:"+e);
265 }
266 }
267 public void decrypt(InputStream in,OutputStream out)
268 {
269 try
270 {
271 int numRead=0;
272 in=new CipherInputStream(in,dcipher);
273 while((numRead=in.read(buf))>=0)
274 {
275 out.write(buf,0,numRead);
276 }
277 out.close();
278 }
279 catch(Exception e)
280 {
281 System.out.println("Exception occur:"+e);
282 }
283 }
284 public static void main(String[] args)
285 {
286 try
287 {
288 System.out.println("Encryption & Decryption of File using DES");
289 SecretKey key=KeyGenerator.getInstance("DES").generateKey();
290 DESFile encrypter=new DESFile(key);
291 encrypter.encrypt(new FileInputStream("C:\\Users\\RiaRY\\Desktop\\test.txt"),new
292
293 FileOutputStream("ciphertext.txt"));
294
295 encrypter.decrypt(new FileInputStream("ciphertext.txt"),new
296
297 FileOutputStream("text2.txt"));
298
299 System.out.println("Encryption & decryption done successfully!!!!!!!!!!!");
300 }
301 catch(Exception e)
302 {
303 System.out.println("Exception occur:"+e) } } }
304
305PRACTICAL NO 05 :- RSA ALGO
306
307import java.math.*;
308import java.security.*;
309public class RSA
310{
311 SecureRandom r;
312 BigInteger p,q,p1,q1,n,n1,e,d,msg,ct,pt;
313 public RSA()
314 {
315 int bitLength=512;
316 int certainty=100;
317 r=new SecureRandom();
318 //step 1: Generate prime no. p & q
319 p=new BigInteger(bitLength,certainty , r) ;
320 q=new BigInteger(bitLength,certainty, r) ;
321
322 //step 2: n=p*q
323 n=p.multiply(q); //n=p*q
324 System.out.println("Prime no. P is:"+p.intValue());
325 System.out.println("Prime no. Q is:"+q.intValue());
326 System.out.println("N=P*Q is:"+n.intValue());
327 //step 3: Generating public key(E)
328 p1=p.subtract(new BigInteger("1"));
329 q1=q.subtract(new BigInteger("1"));
330 n1=p1.multiply(q1);
331 e=new BigInteger("2");
332 while(n1.gcd(e).intValue()>1 || e.compareTo(p1)!=-1)
333 e=e.add(new BigInteger("1"));
334 System.out.println("Public key is (" +n.intValue()+","+e.intValue()+")");
335 //step 4:D=E^-1 mod(P-1)(Q-1)
336 d=e.modInverse(n1);
337 System.out.println("Private key is (" +n.intValue()+","+d.intValue()+")");
338
339 //step 5:Encryption CT=(PT)^e mod n
340 msg=new BigInteger("5");
341 ct=encrypt();
342 System.out.println("Encrypted text is:"+ct.intValue());
343 //step 6:Decryption PT=(CT)^d mod n
344 pt=decrypt(ct);
345 System.out.println("Decrypted text is:"+pt.intValue());
346
347 }
348 public BigInteger encrypt()
349 {
350 return msg.modPow(e,n);
351 }
352 public BigInteger decrypt(BigInteger ct)
353 {
354 return ct.modPow(d,n);
355 }
356 public static void main(String[] args)
357 {
358 new RSA();
359 }
360
361}
362
363PRACTICAL NO :- 06
364import java.io.*;
365import java.math.BigInteger;
366public class Diffie
367{
368 public static void main(String[] args) throws IOException
369 {
370 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
371 System.out.println("Enter prime number1:");
372 BigInteger p=new BigInteger(br.readLine());
373 System.out.println("Enter prime number2");
374 BigInteger g=new BigInteger(br.readLine());
375 System.out.println("Enter value for x");
376 BigInteger x=new BigInteger(br.readLine());
377 BigInteger K1=g.modPow(x,p);
378 System.out.println("K1="+K1);
379 System.out.print("Enter value for y :");
380 BigInteger y=new BigInteger(br.readLine());
381 BigInteger K2=g.modPow(y,p);
382 System.out.println("K2="+K2);
383 BigInteger k1=K2.modPow(x,p);
384 System.out.println("Key calculated at Alice's side:"+k1);
385 BigInteger k2=K1.modPow(y,p);
386 System.out.println("Key calculated at Bob's side:"+k2);
387 System.out.println("deffie hellman secret key Encryption has Taken");
388 if(k1.equals(k2))
389 {
390 System.out.println("Hence Both keys are similar");
391 }
392 else
393 System.out.println("hence keys are not similar");
394 }
395
396}
397
398PRACTICAL NO :- 07 MDS ALGO
399
400import java.io.*;
401import java.security.*;
402public class Send
403{
404 public static void main(String args[])
405 {
406 String input;
407 byte buffer[]=new byte[1024];
408 System.out.println("Enter the message to be send:");
409 try
410 {
411 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
412
413 input=br.readLine();
414 FileOutputStream fos=new FileOutputStream("C:\\Users\\RiaRY\\Desktop\\abc.txt");
415 ObjectOutputStream oos=new ObjectOutputStream(fos);
416 MessageDigest md = MessageDigest.getInstance("MD5");
417 buffer=input.getBytes();
418 md.update(buffer);
419 oos.writeObject(input); //original data
420 oos.writeObject(md.digest()); //fingerprint of data
421 System.out.println("Message send successfully!!!!!!!!!!");
422
423 }
424 catch(Exception e)
425 {
426 e.printStackTrace();
427 }
428 }
429}
430
431
432Receive.java
433import java.io.*;
434import java.security.*;
435public class Receive
436{
437 public static void main(String args[])
438 {
439 byte dig[]=new byte[1024];
440 try
441 {
442 FileInputStream fis=new FileInputStream("C:\\Users\\RiaRY\\Desktop\\abc.txt");
443 ObjectInputStream ois=new ObjectInputStream(fis);
444 Object obj=ois.readObject();
445
446 String data=(String)obj;
447 System.out.println("Received Data: "+data);
448 obj=ois.readObject();
449 dig=(byte[])obj;
450 MessageDigest md=MessageDigest.getInstance("MD5");
451 md.update(data.getBytes());
452 if(MessageDigest.isEqual(md.digest(),dig))
453 System.out.println("message retrived sucessfully");
454 ois.close();
455 }
456 catch(StreamCorruptedException e)
457 {
458 System.out.println("Message is Corrupted!!!!!!!!!!!!");
459 }
460 catch(IOException e)
461 {
462 e.printStackTrace();
463 }
464 catch(NoSuchAlgorithmException e)
465 {
466 e.printStackTrace();
467 }
468 catch(ClassNotFoundException e)
469 {
470 e.printStackTrace();
471 }
472 }
473}
474
475PRACTICAL NO :-08 AES ALGO
476
477import java.io.*;
478import javax.crypto.*;
479public class AESFile
480{
481 Cipher ecipher,dcipher;
482 byte[] buf=new byte[1024];
483 public AESFile(SecretKey key)
484 {
485 try
486 {
487 ecipher=Cipher.getInstance("AES");
488 ecipher.init(Cipher.ENCRYPT_MODE,key);
489 dcipher=Cipher.getInstance("AES");
490 dcipher.init(Cipher.DECRYPT_MODE,key);
491 }
492 catch(Exception e)
493 {
494 System.out.println("Exception occur:"+e);
495 }
496 }
497 public void encrypt(InputStream in,OutputStream out)
498 {
499 try
500 {
501 int numRead=0;
502 out=new CipherOutputStream(out,ecipher);
503 while((numRead=in.read(buf))>=0)
504 {
505 out.write(buf,0,numRead);
506 }
507 out.close();
508 }
509 catch(Exception e)
510 {
511 System.out.println("Exception occur:"+e);
512 }
513 }
514 public void decrypt(InputStream in,OutputStream out)
515 {
516 try
517 {
518 int numRead=0;
519 in=new CipherInputStream(in,dcipher);
520 while((numRead=in.read(buf))>=0)
521 {
522 out.write(buf,0,numRead);
523 }
524 out.close();
525 }
526 catch(Exception e)
527 {
528 System.out.println("Exception occur:"+e);
529 }
530 }
531 public static void main(String[] args)
532 {
533 try
534 {
535 System.out.println("Encryption & Decryption of File using AES");
536 SecretKey key=KeyGenerator.getInstance("AES").generateKey();
537 AESFile encrypter=new AESFile(key);
538 encrypter.encrypt(new FileInputStream("C:\\Users\\RiaRY\\Desktop\\test.txt"),new FileOutputStream("ciphertext.txt"));
539
540 encrypter.decrypt(new FileInputStream("ciphertext.txt"),new FileOutputStream("text2.txt"));
541
542 System.out.println("Encryption & decryption done successfully!!!!!!!!!!!");
543 }
544 catch(Exception e)
545 {
546 System.out.println("Exception occur:"+e);
547 }
548 }
549
550}
551
552################ NETWORK SECURITY END #############
553
554################ WEB SERVICES PRACTICAL ###########
555
556Practical 1
557
558Aim: Create a Web service in Java and consume that Web service by using .NET application
559
560
561Source Code:
562factorial.java
563package com.fact;
564import javax.jws.WebService;
565import javax.jws.WebMethod;
566import javax.jws.WebParam;
567
568@WebService(serviceName = "factorial")
569public class factorial {
570
571 @WebMethod(operationName = "factorial")
572 public double factorial(@WebParam(name = "n") double n)
573 {
574 double fact=1.0;
575 for(int i=1;i<=n;i++)
576 {
577 fact=fact*i;
578 }
579 return fact;
580 }
581
582}
583
584Factorial.apsx
585<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
586
587<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
588
589<html xmlns="http://www.w3.org/1999/xhtml">
590<head runat="server">
591 <title></title>
592</head>
593<body>
594 <form id="form1" runat="server">
595 <div>
596 <asp:Label ID="Label1" runat="server" Text="Enter Number" Font-Bold="true"></asp:Label>
597
598 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
599 <br />
600 <br/>
601 <asp:Button ID="Button1" runat="server" Text="Factorial" BackColor="#33ccff"
602 Font-Bold="true" BorderStyle="None" onclick="Button1_Click"/>
603 <br />
604 <br/>
605 <asp:Label ID="Label2" runat="server" Text="" Font-Bold="true" Font-Italic="true"></asp:Label>
606 </div>
607 </form>
608</body>
609</html>
610
611Factorial.apsx.cs
612using System;
613using System.Collections.Generic;
614using System.Linq;
615using System.Web;
616using System.Web.UI;
617using System.Web.UI.WebControls;
618
619namespace Factorial
620{
621 public partial class Factorial : System.Web.UI.Page
622 {
623 protected void Page_Load(object sender, EventArgs e)
624 {
625
626 }
627
628 protected void Button1_Click(object sender, EventArgs e)
629 {
630 ServiceReference1.factorialClient ws = new ServiceReference1.factorialClient();
631 int n = Convert.ToInt32(TextBox1.Text);
632 Label2.Text = ws.factorial(n).ToString();
633
634 }
635 }
636}
637
638
639PRACTICAL NO:- 2
640Aim:Celsius toFahrenheit
641
642convert.java
643package com.convert;
644import javax.jws.WebService;
645import javax.jws.WebMethod;
646import javax.jws.WebParam;
647
648@WebService(serviceName = "convert")
649public class convert {
650@WebMethod(operationName = "toCelsius")
651 public double toCelsius(@WebParam(name = "cel") double cel, @WebParam(name = "unit") String unit) {
652 if("Kelvin".equals(unit))
653 cel=cel-273.15;
654 else
655 cel=(cel-32)*5.0/9.0;
656 return cel;
657 }
658 @WebMethod(operationName = "toKelvin")
659 public double toKelvin(@WebParam(name = "cel") double cel, @WebParam(name = "unit") String unit) {
660 if("Celsius".equals(unit))
661 cel=cel+273.15;
662 else
663 cel=(cel-32)*5.0/9.0+273.15;
664 return cel;
665 }
666 @WebMethod(operationName = "toFahrenhiet")
667 public double toFahrenhiet(@WebParam(name = "cel") double cel, @WebParam(name = "unit") String unit) {
668 if("Kelvin".equals(unit))
669 cel=(cel-273.15)*9.0/5.0+32;
670 else
671 cel=cel*9.0/5.0+32;
672 return cel;
673 }
674}
675
676Convert.java
677package com.temp;
678
679import com.abc.Convert_Service;
680import java.io.IOException;
681import java.io.PrintWriter;
682import javax.servlet.ServletException;
683import javax.servlet.annotation.WebServlet;
684import javax.servlet.http.HttpServlet;
685import javax.servlet.http.HttpServletRequest;
686import javax.servlet.http.HttpServletResponse;
687import javax.xml.ws.WebServiceRef;
688
689@WebServlet(name = "Converter", urlPatterns = {"/Converter"})
690public class Converter extends HttpServlet {
691
692 @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/Convert/convert.wsdl")
693 private Convert_Service service;
694
695 @Override
696 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
697 PrintWriter pw= response.getWriter();
698 response.setContentType("text/html");
699 String s1= request.getParameter("t1");
700 double n= Double.parseDouble(s1);
701 double res;
702 String unit=request.getParameter("s1");
703 String type=request.getParameter("s2");
704 switch (type) {
705 case "Celsius":
706
707
708 res = toCelsius(n,unit);
709 break;
710 case "Kelvin":
711 res = toKelvin(n,unit);
712 break;
713 default:
714 res = toFahrenhiet(n,unit);
715 break;
716 }
717 String str=String.valueOf(res);
718 pw.write("<br><strong>Conversion is "+str+"</strong>");
719 }
720
721 private double toCelsius(double cel, java.lang.String unit) {
722 // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
723 // If the calling of port operations may lead to race condition some synchronization is required.
724 com.abc.Convert port = service.getConvertPort();
725 return port.toCelsius(cel, unit);
726 }
727
728 private double toFahrenhiet(double cel, java.lang.String unit) {
729 // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
730 // If the calling of port operations may lead to race condition some synchronization is required.
731 com.abc.Convert port = service.getConvertPort();
732 return port.toFahrenhiet(cel, unit);
733 }
734
735 private double toKelvin(double cel, java.lang.String unit) {
736 // Note that the injected javax.xml.ws.Service reference as well as port objects are not thread safe.
737 // If the calling of port operations may lead to race condition some synchronization is required.
738 com.abc.Convert port = service.getConvertPort();
739 return port.toKelvin(cel, unit);
740 }
741}
742index.html
743<!DOCTYPE html>
744\<html>
745 <head>
746 <title>Convert Temperature</title>
747 <meta charset="UTF-8">
748 <meta name="viewport" content="width=device-width, initial-scale=1.0">
749 </head>
750 <body>
751 <div>
752 <form method="post" action="Converter" name="f1">
753 <strong>Enter Value:</strong>
754 <input type="text" name="t1"><br>
755 <select name="s1">
756 <option>Celsius</option>
757 <option>Kelvin</option>
758 <option>Fahrenhiet</option>
759 </select><strong> to </strong>
760 <select name="s2">
761 <option>Celsius</option>
762 <option>Kelvin</option>
763 <option>Fahrenhiet</option>
764 </select><br>
765 <input type="submit" value="Convert" style="background-color: #33ccff; border-style: none">
766 </div>
767 </body>
768</html>
769
770PRACTICAL NO:-3 ARMSTRONG
771
772Source Code:
773
774armstrong.java
775package com.check;
776
777import javax.jws.WebService;
778import javax.jws.WebMethod;
779import javax.jws.WebParam;
780
781@WebService(serviceName = "armstrong")
782public class armstrong {
783 @WebMethod(operationName = "armstrong")
784 public boolean armstrong(@WebParam(name = "num") String num) {
785 int n=num.length();
786 int temp,d,res,r,m;
787 m=1;
788 res=0;
789 temp=Integer.parseInt(num);
790 d=temp;
791 while(temp>0)
792 {
793 r=temp%10;
794 for(int i=0;i<n;i++)
795 m=m*r;
796 res=res+m;
797 temp=temp/10;
798 m=1;
799 }
800 if(res==d)
801 return true;
802 else
803 return false;
804 }
805
806}
807
808ArmstrongCheck.java
809package armstrongcheck;
810
811import java.awt.Container;
812import java.awt.GridLayout;
813import java.awt.event.ActionEvent;
814import java.awt.event.ActionListener;
815import javafx.scene.paint.Color;
816import javax.swing.JButton;
817import javax.swing.JFrame;
818import javax.swing.JLabel;
819import javax.swing.JTextField;
820import java.awt.Color.*;
821
822public class ArmstrongCheck extends JFrame implements ActionListener{
823 JTextField t1;
824 Container c;
825 JButton b1;
826 JLabel l1,l2;
827
828 public ArmstrongCheck()
829 {
830 c=getContentPane();
831 c.setLayout(new GridLayout(3,2));
832 l1=new JLabel("Enter Number:");
833 l2=new JLabel();
834 t1=new JTextField(10);
835 b1=new JButton("Armstrong Check");
836 b1.setBackground(java.awt.Color.cyan);
837 c.add(l1);
838 c.add(t1);
839 c.add(b1);
840 c.add(new JLabel());
841 c.add(l2);
842 b1.addActionListener(this);
843 setSize(500,150);
844 setVisible(true);
845 }
846
847 @Override
848 public void actionPerformed(ActionEvent e) {
849 String str;
850 String s1=t1.getText();
851 boolean res=armstrong(s1);
852 if(res==true)
853 str="Number is Armstrong";
854 else
855 str="Number is not Armstrong";
856 l2.setText(str);
857 }
858
859 private static boolean armstrong(java.lang.String num) {
860 com.check.Armstrong_Service service = new com.check.Armstrong_Service();
861 com.check.Armstrong port = service.getArmstrongPort();
862 return port.armstrong(num);
863 }
864
865 public static void main(String[] args) {
866 new ArmstrongCheck();
867 }
868}
869
870PRACTICAL NO :- 4
871Aim: Create a WCF with typical client and typical server.
872
873
874Source Code:
875
876IService1.cs
877using System;
878using System.Collections.Generic;
879using System.Linq;
880using System.Runtime.Serialization;
881using System.ServiceModel;
882using System.Text;
883
884namespace WcfService1
885{
886 // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
887 [ServiceContract]
888 public interface IService1
889 {
890 [OperationContract]
891 String checkPrime(int n);
892 }
893}
894
895Service1.svc.cs
896using System;
897using System.Collections.Generic;
898using System.Linq;
899using System.Runtime.Serialization;
900using System.ServiceModel;
901using System.Text;
902
903namespace WcfService1
904{
905 // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
906 public class Service1 : IService1
907 {
908 public string checkPrime(int n)
909 {
910 int i;
911 string s;
912 for (i = 2; i <= n / 2; i++)
913 {
914 if (n % i == 0)
915 break;
916 }
917 if(i<=n/2)
918 s="Number is not Prime";
919 else
920 s="Number is Prime";
921 return s;
922 }
923 }
924}
925
926Prime.aspx
927<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="prime.aspx.cs" Inherits="PrimeCheck.prime" %>
928
929<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
930
931<html xmlns="http://www.w3.org/1999/xhtml">
932<head runat="server">
933 <title></title>
934</head>
935<body>
936 <form id="form1" runat="server">
937 <div>
938 <asp:Label ID="Label1" runat="server" Text="Enter Number" Font-Bold="true"></asp:Label>
939
940 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
941 <br />
942 <br/>
943 <asp:Button ID="Button1" runat="server" Text="Check Prime" BackColor="#33ccff"
944 Font-Bold="true" BorderStyle="None" onclick="Button1_Click"/>
945 <br />
946 <br/>
947 <asp:Label ID="Label2" runat="server" Text="" Font-Bold="true" Font-Italic="true"></asp:Label>
948 </div>
949 </form>
950</body>
951</html>
952
953Prime.apsx.cs
954using System;
955using System.Collections.Generic;
956using System.Linq;
957using System.Web;
958using System.Web.UI;
959using System.Web.UI.WebControls;
960
961namespace PrimeCheck
962{
963 public partial class prime : System.Web.UI.Page
964 {
965 protected void Page_Load(object sender, EventArgs e)
966 {
967
968 }
969
970 protected void Button1_Click(object sender, EventArgs e)
971 {
972 ServiceReference1.Service1Client ws = new ServiceReference1.Service1Client();
973 int n = Convert.ToInt32(TextBox1.Text);
974 Label2.Text = ws.checkPrime(n).ToString();
975
976 }
977 }
978}
979
980PRACTICAL NO:- 6
981Aim: Create a RESTful Web service and retrieve information in different in format such as plain text (html/XML).
982
983Source Code:
984
985GenericResource.java
986package com.abc;
987import javax.ws.rs.core.Context;
988import javax.ws.rs.core.UriInfo;
989import javax.ws.rs.Produces;
990import javax.ws.rs.Consumes;
991import javax.ws.rs.GET;
992import javax.ws.rs.Path;
993import javax.ws.rs.PUT;
994import javax.ws.rs.core.MediaType;
995@Path("generic")
996public class GenericResource {
997
998 @Context
999 private UriInfo context;
1000
1001 /**
1002 * Creates a new instance of GenericResource
1003 */
1004 public GenericResource() {
1005 }
1006
1007 /**
1008 * Retrieves representation of an instance of com.abc.GenericResource
1009 * @return an instance of java.lang.String
1010 */
1011 @GET
1012 @Produces(MediaType.TEXT_PLAIN)
1013 public String getText() {
1014 return "RESTful Web service with Patterns";
1015 //throw new UnsupportedOperationException();
1016 }
1017
1018 /**
1019 * PUT method for updating or creating an instance of GenericResource
1020 * @param content representation for the resource
1021 */
1022 @PUT
1023 @Consumes(MediaType.TEXT_PLAIN)
1024 public void putText(String content) {
1025 }
1026}
1027
1028PRACTICAL NO:-7
1029Aim: Define a web service method that returns the contents of a database in a XML string.
1030
1031
1032Source Code:
1033
1034Friend.java
1035package abc;
1036
1037import java.io.Serializable;
1038import javax.persistence.Basic;
1039import javax.persistence.Column;
1040import javax.persistence.Entity;
1041import javax.persistence.Id;
1042import javax.persistence.NamedQueries;
1043import javax.persistence.NamedQuery;
1044import javax.persistence.Table;
1045import javax.validation.constraints.NotNull;
1046import javax.validation.constraints.Size;
1047import javax.xml.bind.annotation.XmlRootElement;
1048
1049@Entity
1050@Table(name = "FRIENDS")
1051@XmlRootElement
1052@NamedQueries({
1053 @NamedQuery(name = "Friends.findAll", query = "SELECT f FROM Friends f")
1054 , @NamedQuery(name = "Friends.findById", query = "SELECT f FROM Friends f WHERE f.id = :id")
1055 , @NamedQuery(name = "Friends.findByName", query = "SELECT f FROM Friends f WHERE f.name = :name")
1056 , @NamedQuery(name = "Friends.findByAddress", query = "SELECT f FROM Friends f WHERE f.address = :address")})
1057public class Friends implements Serializable {
1058
1059 private static final long serialVersionUID = 1L;
1060 @Id
1061 @Basic(optional = false)
1062 @NotNull
1063 @Column(name = "ID")
1064 private Integer id;
1065 @Size(max = 25)
1066 @Column(name = "NAME")
1067 private String name;
1068 @Size(max = 25)
1069 @Column(name = "ADDRESS")
1070 private String address;
1071
1072 public Friends() {
1073 }
1074
1075 public Friends(Integer id) {
1076 this.id = id;
1077 }
1078
1079 public Integer getId() {
1080 return id;
1081 }
1082
1083 public void setId(Integer id) {
1084 this.id = id;
1085 }
1086
1087 public String getName() {
1088 return name;
1089 }
1090
1091 public void setName(String name) {
1092 this.name = name;
1093 }
1094
1095 public String getAddress() {
1096 return address;
1097 }
1098
1099 public void setAddress(String address) {
1100 this.address = address;
1101 }
1102
1103 @Override
1104 public int hashCode() {
1105 int hash = 0;
1106 hash += (id != null ? id.hashCode() : 0);
1107 return hash;
1108 }
1109
1110 @Override
1111 public boolean equals(Object object) {
1112 // TODO: Warning - this method won't work in the case the id fields are not set
1113 if (!(object instanceof Friends)) {
1114 return false;
1115 }
1116 Friends other = (Friends) object;
1117 if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
1118 return false;
1119 }
1120 return true;
1121 }
1122
1123 @Override
1124 public String toString() {
1125 return "abc.Friends[ id=" + id + " ]";
1126 }
1127
1128}
1129
1130FriendsFacadeREST.java
1131package abc.service;
1132
1133import abc.Friends;
1134import java.util.List;
1135import javax.ejb.Stateless;
1136import javax.persistence.EntityManager;
1137import javax.persistence.PersistenceContext;
1138import javax.ws.rs.Consumes;
1139import javax.ws.rs.DELETE;
1140import javax.ws.rs.GET;
1141import javax.ws.rs.POST;
1142import javax.ws.rs.PUT;
1143import javax.ws.rs.Path;
1144import javax.ws.rs.PathParam;
1145import javax.ws.rs.Produces;
1146import javax.ws.rs.core.MediaType;
1147@Stateless
1148@Path("abc.friends")
1149public class FriendsFacadeREST extends AbstractFacade<Friends> {
1150
1151 @PersistenceContext(unitName = "aws6PU")
1152 private EntityManager em;
1153
1154 public FriendsFacadeREST() {
1155 super(Friends.class);
1156 }
1157
1158 @POST
1159 @Override
1160 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1161 public void create(Friends entity) {
1162 super.create(entity);
1163 }
1164
1165 @PUT
1166 @Path("{id}")
1167 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1168 public void edit(@PathParam("id") Integer id, Friends entity) {
1169 super.edit(entity);
1170 }
1171
1172 @DELETE
1173 @Path("{id}")
1174 public void remove(@PathParam("id") Integer id) {
1175 super.remove(super.find(id));
1176 }
1177
1178 @GET
1179 @Path("{id}")
1180 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1181 public Friends find(@PathParam("id") Integer id) {
1182 return super.find(id);
1183 }
1184
1185 @GET
1186 @Override
1187 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1188 public List<Friends> findAll() {
1189 return super.findAll();
1190 }
1191
1192 @GET
1193 @Path("{from}/{to}")
1194 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1195 public List<Friends> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
1196 return super.findRange(new int[]{from, to});
1197 }
1198
1199 @GET
1200 @Path("count")
1201 @Produces(MediaType.TEXT_PLAIN)
1202 public String countREST() {
1203 return String.valueOf(super.count());
1204 }
1205
1206 @Override
1207 protected EntityManager getEntityManager() {
1208 return em;
1209 }
1210
1211}
1212
1213Practical 8a
1214
1215Aim: Define a RESTful web service that accepts the details to be stored in a database and performs CRUD operation.
1216
1217Source Code:
1218
1219Prac9.java
1220package com.xyz;
1221
1222import java.io.Serializable;
1223import javax.persistence.Entity;
1224import javax.persistence.GeneratedValue;
1225import javax.persistence.GenerationType;
1226import javax.persistence.Id;
1227@Entity
1228public class prac9 implements Serializable {
1229
1230 private static final long serialVersionUID = 1L;
1231 @Id
1232 @GeneratedValue(strategy = GenerationType.AUTO)
1233 private Long id;
1234 private String emp_name;
1235
1236 /**
1237 * Get the value of emp_name
1238 *
1239 * @return the value of emp_name
1240 */
1241 public String getEmp_name() {
1242 return emp_name;
1243 }
1244
1245 /**
1246 * Set the value of emp_name
1247 *
1248 * @param emp_name new value of emp_name
1249 */
1250 public void setEmp_name(String emp_name) {
1251 this.emp_name = emp_name;
1252 }
1253
1254
1255 public Long getId() {
1256 return id;
1257 }
1258
1259 public void setId(Long id) {
1260 this.id = id;
1261 }
1262
1263 @Override
1264 public int hashCode() {
1265 int hash = 0;
1266 hash += (id != null ? id.hashCode() : 0);
1267 return hash;
1268 }
1269
1270 @Override
1271 public boolean equals(Object object) {
1272 // TODO: Warning - this method won't work in the case the id fields are not set
1273 if (!(object instanceof prac9)) {
1274 return false;
1275 }
1276 prac9 other = (prac9) object;
1277 if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
1278 return false;
1279 }
1280 return true;
1281 }
1282
1283 @Override
1284 public String toString() {
1285 return "com.xyz.prac9[ id=" + id + " ]";
1286 }
1287
1288}
1289
1290Prac9Facade.java
1291package com.xyz;
1292
1293import javax.ejb.Stateless;
1294import javax.persistence.EntityManager;
1295import javax.persistence.PersistenceContext;
1296
1297/**
1298 *
1299 * @author RiaRY
1300 */
1301@Stateless
1302public class prac9Facade extends AbstractFacade<prac9> {
1303
1304 @PersistenceContext(unitName = "aws9PU")
1305 private EntityManager em;
1306
1307 @Override
1308 protected EntityManager getEntityManager() {
1309 return em;
1310 }
1311
1312 public prac9Facade() {
1313 super(prac9.class);
1314 }
1315
1316}
1317
1318Practical 8b
1319
1320
1321Aim: Define a RESTful web service that accepts the details to be stored in an Entity and performs CRUD operation.
1322
1323
1324Source Code:
1325
1326Frnd.java
1327package com.prac8;
1328import java.io.Serializable;
1329import javax.persistence.Basic;
1330import javax.persistence.Column;
1331import javax.persistence.Entity;
1332import javax.persistence.Id;
1333import javax.persistence.NamedQueries;
1334import javax.persistence.NamedQuery;
1335import javax.persistence.Table;
1336import javax.validation.constraints.NotNull;
1337import javax.validation.constraints.Size;
1338import javax.xml.bind.annotation.XmlRootElement;
1339@Entity
1340@Table(name = "FRND")
1341@XmlRootElement
1342@NamedQueries({
1343 @NamedQuery(name = "Frnd.findAll", query = "SELECT f FROM Frnd f")
1344 , @NamedQuery(name = "Frnd.findById", query = "SELECT f FROM Frnd f WHERE f.id = :id")
1345 , @NamedQuery(name = "Frnd.findByName", query = "SELECT f FROM Frnd f WHERE f.name = :name")})
1346public class Frnd implements Serializable {
1347
1348 private static final long serialVersionUID = 1L;
1349 @Id
1350 @Basic(optional = false)
1351 @NotNull
1352 @Column(name = "ID")
1353 private Short id;
1354 @Size(max = 24)
1355 @Column(name = "NAME")
1356 private String name;
1357
1358 public Frnd() {
1359 }
1360
1361 public Frnd(Short id) {
1362 this.id = id;
1363 }
1364
1365 public Short getId() {
1366 return id;
1367 }
1368
1369 public void setId(Short id) {
1370 this.id = id;
1371 }
1372
1373 public String getName() {
1374 return name;
1375 }
1376
1377 public void setName(String name) {
1378 this.name = name;
1379 }
1380
1381 @Override
1382 public int hashCode() {
1383 int hash = 0;
1384 hash += (id != null ? id.hashCode() : 0);
1385 return hash;
1386 }
1387
1388 @Override
1389 public boolean equals(Object object) {
1390 // TODO: Warning - this method won't work in the case the id fields are not set
1391 if (!(object instanceof Frnd)) {
1392 return false;
1393 }
1394 Frnd other = (Frnd) object;
1395 if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
1396 return false;
1397 }
1398 return true;
1399 }
1400
1401 @Override
1402 public String toString() {
1403 return "com.prac8.Frnd[ id=" + id + " ]"}}
1404
1405FrndFacadeREST.java
1406package service;
1407import com.prac8.Frnd;
1408import java.util.List;
1409import javax.ejb.Stateless;
1410import javax.persistence.EntityManager;
1411import javax.persistence.PersistenceContext;
1412import javax.ws.rs.Consumes;
1413import javax.ws.rs.DELETE;
1414import javax.ws.rs.GET;
1415import javax.ws.rs.POST;
1416import javax.ws.rs.PUT;
1417import javax.ws.rs.Path;
1418import javax.ws.rs.PathParam;
1419import javax.ws.rs.Produces;
1420import javax.ws.rs.core.MediaType;
1421@Stateless
1422@Path("com.prac8.frnd")
1423public class FrndFacadeREST extends AbstractFacade<Frnd> {
1424
1425 @PersistenceContext(unitName = "aws8newPU")
1426 private EntityManager em;
1427
1428 public FrndFacadeREST() {
1429 super(Frnd.class);
1430 }
1431
1432 @POST
1433 @Override
1434 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1435 public void create(Frnd entity) {
1436 super.create(entity);
1437 }
1438
1439 @PUT
1440 @Path("{id}")
1441 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1442 public void edit(@PathParam("id") Short id, Frnd entity) {
1443 super.edit(entity);
1444 }
1445
1446 @DELETE
1447 @Path("{id}")
1448 public void remove(@PathParam("id") Short id) {
1449 super.remove(super.find(id));
1450 }
1451
1452 @GET
1453 @Path("{id}")
1454 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1455 public Frnd find(@PathParam("id") Short id) {
1456 return super.find(id);
1457 }
1458
1459 @GET
1460 @Override
1461 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1462 public List<Frnd> findAll() {
1463 return super.findAll();
1464 }
1465
1466 @GET
1467 @Path("{from}/{to}")
1468 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
1469 public List<Frnd> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
1470 return super.findRange(new int[]{from, to});
1471 }
1472
1473 @GET
1474 @Path("count")
1475 @Produces(MediaType.TEXT_PLAIN)
1476 public String countREST() {
1477 return String.valueOf(super.count());
1478 }
1479
1480 @Override
1481 protected EntityManager getEntityManager() {
1482 return em;
1483 }}
1484
1485
1486Practical 9
1487
1488
1489Aim: Define a RESTful web service that accepts the details to be stored in a database and retrieve information in JSON string format in table.
1490
1491Source Code:
1492
1493index.html
1494<!DOCTYPE html>
1495<!--
1496To change this license header, choose License Headers in Project Properties.
1497To change this template file, choose Tools | Templates
1498and open the template in the editor.
1499-->
1500<html>
1501 <head>
1502 <title>JSON</title>
1503 <meta charset="UTF-8">
1504 <meta name="viewport" content="width=device-width">
1505 <script>
1506 var req=new XMLHttpRequest();
1507 req.open("GET","http://localhost:13544/RDataBase/webresources/com.abc.student/",true)
1508 req.onload=function()
1509 {
1510 var data=JSON.parse(this.response);
1511 var tb=document.getElementById("t");
1512 for(var i=0;i<data.length;i++)
1513 {
1514 var row=tb.insertRow();
1515 var c1=row.insertCell(0);
1516 var c2=row.insertCell(1);
1517
1518 c1.innerHTML=data[i].id;
1519 c2.innerHTML=data[i].name;
1520
1521 }
1522 };
1523 req.send();
1524 </script>
1525 </head>
1526 <body>
1527 <div>
1528 <table id="t">
1529 <tr>
1530 <td>ID</td>
1531 <td>NAME</td>
1532
1533 </tr>
1534 </table>
1535 </div>
1536 </body>
1537</html>
1538
1539StudentFacadeREST.java
1540package com.abc.service;
1541
1542import com.abc.Student;
1543import java.util.List;
1544import javax.ejb.Stateless;
1545import javax.persistence.EntityManager;
1546import javax.persistence.PersistenceContext;
1547import javax.ws.rs.Consumes;
1548import javax.ws.rs.DELETE;
1549import javax.ws.rs.GET;
1550import javax.ws.rs.POST;
1551import javax.ws.rs.PUT;
1552import javax.ws.rs.Path;
1553import javax.ws.rs.PathParam;
1554import javax.ws.rs.Produces;
1555@Stateless
1556@Path("com.abc.student")
1557public class StudentFacadeREST extends AbstractFacade<Student> {
1558 @PersistenceContext(unitName = "RDataBasePU")
1559 private EntityManager em;
1560
1561 public StudentFacadeREST() {
1562 super(Student.class);
1563 }
1564
1565 @POST
1566 @Override
1567 @Consumes({"application/json"})
1568 public void create(Student entity) {
1569 super.create(entity);
1570 }
1571
1572 @PUT
1573 @Path("{id}")
1574 @Consumes({"application/json"})
1575 public void edit(@PathParam("id") Integer id, Student entity) {
1576 super.edit(entity);
1577 }
1578
1579 @DELETE
1580 @Path("{id}")
1581 public void remove(@PathParam("id") Integer id) {
1582 super.remove(super.find(id));
1583 }
1584
1585 @GET
1586 @Path("{id}")
1587 @Produces({"application/json"})
1588 public Student find(@PathParam("id") Integer id) {
1589 return super.find(id);
1590 }
1591
1592 @GET
1593 @Override
1594 @Produces({"application/json"})
1595 public List<Student> findAll() {
1596 return super.findAll();
1597 }
1598
1599 @GET
1600 @Path("{from}/{to}")
1601 @Produces({"application/xml", "application/json"})
1602 public List<Student> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
1603 return super.findRange(new int[]{from, to});
1604 }
1605
1606 @GET
1607 @Path("count")
1608 @Produces("text/plain")
1609 public String countREST() {
1610 return String.valueOf(super.count());
1611 }
1612
1613 @Override
1614 protected EntityManager getEntityManager() {
1615 return em;
1616 }
1617
1618}