2018 Assigment 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Question 1

a. Write code for a multi-threaded server that would echo system time to a telnet
client on port 23.
[10]

import java.net.Socket;

import java.net.ServerSocket;

public class EchoServer {

public static void main(String[ ] args) throws Exception {

int port = 28;

ServerSocket serverSocket = new ServerSocket(port);

System.err.println("Started server on port " + port);

// repeatedly wait for connections, and process

while (true) {

// a "blocking" call which waits until a connection is requested

Socket clientSocket = serverSocket.accept();

System.err.println("Accepted connection from client");

// open up IO streams

In in = new In (clientSocket);

Out out = new Out(clientSocket);


// waits for data and reads it in until connection dies

// readLine() blocks until the server receives a new line from client

String s;

while ((s = in.readLine()) != null) {

out.println(s);

// close IO streams, then socket

System.err.println("Closing connection with client");

out.close();

in.close();

clientSocket.close();

Question 2

a. Create a serializable Class called BankAccount with the following fields account
name, account number, account type and balance. You should provide getters
and setters for the variables you define
[10]

import java.text.NumberFormat;

import java.lang.Comparable;

import java.io.*; // For serializable

public class BankAccount implements Comparable

{
// Data fields that every BankAccount object will maintain

private String my_ID;

private double my_balance;

/** Initialize private data fields with arguments during construction.

* @param initID A String meant to uniquely identify this BankAccount.

* @param initBalance This BankAccount's starting balance.

*/

public BankAccount( String initID, double initBalance )

my_ID = initID;

my_balance = initBalance;

/** Credit this account by depositAmount.

* Precondition: depositAmount >= 0.0. If negative, balance is DEBITed.

* @param depositAmount amount of money to credit to this BankAccount.

*/

public void deposit( double depositAmount )

my_balance = my_balance + depositAmount;

/** Debit this account by withdrawalAmount if it is positive

public boolean withdraw ( double withdrawalAmount )

{
boolean result = true;

if( ( withdrawalAmount <= my_balance ) && ( withdrawalAmount > 0.0 ) )

my_balance = my_balance - withdrawalAmount;

else

result = false;

return result;

public String getID( )

return my_ID;

/** Access this account's current balance.

* @return the BankAccount's current balance.

*/

public double getBalance( )

return my_balance;

/** Return the state of this object as a String.

This method will be used by LinkedList.toString.

You is also called in a print like this

System.out.println( anInstanceOfBankAccount ); // .toString not necessary

*/

public String toString( )

{
NumberFormat nf = NumberFormat.getCurrencyInstance( );

return my_ID +" " + nf.format( my_balance );

/** This method allows for comparison of two BankAccount objects.

* @param The argument which must be an instance of BankAccount

* @returns a negative int if this object has an ID that

* lexicraphically precedes argument, 0 if the IDs are equals and

* a positive if this object would follow argument in the phone book.

*/

public int compareTo( Object argument )

String leftID = this.getID( );

String rightID = ((BankAccount)argument).getID();

return leftID.compareTo(rightID);

/** Override the Object equals method so BankAccount equals compares

* the state of two BankAccount objects rather than the references.

* @return true if one BankAccount is has the same ID as the other.

*/

public boolean equals( Object argument )

if( argument instanceof BankAccount )

return( this.compareTo( argument ) == 0 );

else

return false;
}

} // end class BankAccount

Write a Java class method called saveToFile ( ) that persists the calling object to a
file called bankaccounts.dat [10]

public static void writeFile(String bankaccount.dat, String text)

throws IOException

File file = new File (bankaccount);

BufferedWriter out = new BufferedWriter(new FileWriter(file));

out.write(text);

out.close();

Question 4

ROT13 Algorithm
ROT13 (rotate by 13 places) replaces a letter with the letter 13 letters after it in the
alphabet.

For example :

The quick brown fox jumps over 13 lazy dogs.

Becomes

Gur dhvpx oebja sbk whzcf bire 13 ynml qbtf.

a. Write source code for a client and server application. The client is supposed to send text
message input from the user and then encrypts it using the ROT13 algorithm. The server
is supposed to be listening to client messages on port 2018. When the client connects to
the server, the server prints the encrypted and decrypted message using the ROT13
Algorithm and prompts user for a response message. The response is ROT13 encrypted
before sending it back to the client. Your client is able to decrypt the message from the
server and display both the encrypted and decrypted messages. The server and client
processes terminate when either of them sends a message “bye” or “olr” its ROT13
equivalent. [20]

import java.nio.CharBuffer;

import java.nio.ByteBuffer;

import java.nio.charset.Charset;

import java.nio.charset.CharsetEncoder;

import java.nio.charset.CharsetDecoder;

import java.nio.charset.CoderResult;

import java.util.Map;

import java.util.Iterator;

import java.io.Writer;

import java.io.PrintStream;

import java.io.PrintWriter;

import java.io.OutputStreamWriter;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.FileReader;

public class Rot13Charset extends Charset

private static final String BASE_CHARSET_NAME = "UTF-8";

Charset baseCharset;

protected Rot13Charset (String canonical, String [] aliases)

super (canonical, aliases);


baseCharset = Charset.forName (BASE_CHARSET_NAME);

public CharsetEncoder newEncoder()

return new Rot13Encoder (this, baseCharset.newEncoder());

public CharsetDecoder newDecoder()

return new Rot13Decoder (this, baseCharset.newDecoder());

public boolean contains (Charset cs)

return (false);

private void rot13 (CharBuffer cb)

for (int pos = cb.position(); pos < cb.limit(); pos++) {

char c = cb.get (pos);

char a = '\u0000';

if ((c >= 'a') && (c <= 'z')) {

a = 'a';

if ((c >= 'A') && (c <= 'Z')) {

a = 'A';

if (a != '\u0000') {

c = (char)((((c - a) + 13) % 26) + a);


cb.put (pos, c);

private class Rot13Encoder extends CharsetEncoder

Rot13Encoder (Charset cs, CharsetEncoder baseEncoder)

super (cs, baseEncoder.averageBytesPerChar(),

baseEncoder.maxBytesPerChar());

this.baseEncoder = baseEncoder;

protected CoderResult encodeLoop (CharBuffer cb, ByteBuffer bb)

CharBuffer tmpcb = CharBuffer.allocate (cb.remaining());

while (cb.hasRemaining()) {

tmpcb.put (cb.get());

tmpcb.rewind();

rot13 (tmpcb);

baseEncoder.reset();

CoderResult cr = baseEncoder.encode (tmpcb, bb, true);

cb.position (cb.position() - tmpcb.remaining());


return (cr);

private class Rot13Decoder extends CharsetDecoder

private CharsetDecoder baseDecoder;

Rot13Decoder (Charset cs, CharsetDecoder baseDecoder)

super (cs, baseDecoder.averageCharsPerByte(),

baseDecoder.maxCharsPerByte());

this.baseDecoder = baseDecoder;

protected CoderResult decodeLoop (ByteBuffer bb, CharBuffer cb)

baseDecoder.reset();

CoderResult result = baseDecoder.decode (bb, cb, true);

rot13 (cb);

return (result);

public static void main (String [] argv)


throws Exception

BufferedReader in;

if (argv.length > 0) {

in = new BufferedReader (new FileReader (argv [0]));

} else {

in = new BufferedReader (new InputStreamReader (System.in));

PrintStream out = new PrintStream (System.out, false, "X-ROT13");

String s = null;

while ((s = in.readLine()) != null) {

out.println (s);

out.flush();

You might also like