Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Accurately implement your model (behaviors, states, events and relationships) So

ID: 3851008 • Letter: A

Question

Accurately implement your model (behaviors, states, events and relationships)

Source code:

=================================

public interface RemoteControl {

   public void homeBtn();

   public void internetBtn();

   public void navRightBtn();

   public void navUpBtn();

   public void navDownBtn();

   public void playBtn();

   public void stopBtn();

   public void pauseBtn();

   public void fFwdBtn();

   public void fRevBtn();

   public void skipSceneFwdBtn();

   public void skipSceneRevBtn();

   public void ejectBtn();

   public void closeDrawerBtn();

   public void openDrawerBtn();

   public void acceptBtn();

   public void powerBtn();

}


======================

public class DVDPlayer implements RemoteControl {

   public void processRemoteCMD() {

       powerBtn();
   }

   public void displayResultionDisplay() {
       playBtn();

   }

   public void homeBtn() {
       System.out.println("Here is the HOME Button");
       System.out.println(" ");
       internetBtn();

   }

   public void internetBtn() {
       System.out.println("Now we are in internet menu");
       System.out.println("Please click on Right Navigation button");
       System.out.println(" ");
       navRightBtn();

   }

   public void navRightBtn() {
       System.out.println("Now we are in Right Navigation");
       System.out.println("Now we are going to Up Navigation");
       System.out.println(" ");
       navUpBtn();

   }

   public void navUpBtn() {
       System.out.println("We are in Up Navigation menu");
       System.out.println("Cliking on Down Navigation menu");
       System.out.println(" ");
       navDownBtn();
   }

   public void navDownBtn() {
       System.out.println("Now we are in Down Navigation menu");
       System.out.println("Please press the play button to start");
       System.out.println(" ");
       playBtn();

   }

   public void playBtn() {
       System.out.println("Now we are playing");
       fFwdBtn();

   }

   public void stopBtn() {
       System.out.println("Stopped the play");
       ejectBtn();

   }

   public void pauseBtn() {
       System.out.println("We just pause play");
       stopBtn();

   }

   public void fFwdBtn() {
       System.out.println("We are in fast forward stage");
       fRevBtn();

   }

   public void fRevBtn() {

       System.out.println("We are in fast Reverse stage");
       skipSceneFwdBtn();

   }

   public void skipSceneFwdBtn() {
       System.out.println("Now we are in skip Scene forward");
       skipSceneRevBtn();

   }

   public void skipSceneRevBtn() {
       System.out.println("Now we are in skip Scene Reverse");
       pauseBtn();

   }

   public void ejectBtn() {
       System.out.println("Removed the CD.");
       openDrawerBtn();

   }

   public void closeDrawerBtn() {
       System.out.println("close the Drawer");

   }

   public void openDrawerBtn() {
       System.out.println("Now we are in opned the Drawer");
       acceptBtn();

   }

   public void acceptBtn() {
       System.out.println("accept the CD.");
       closeDrawerBtn();

   }

   public void powerBtn() {
       System.out.println("Start the power button");
       homeBtn();
   }

}


====================

import java.util.Scanner;

public class DVDSimulationDisplay {

   static String value = null;

   public static void displayCMD() {
       DVDPlayer dvdPlayer = new DVDPlayer();
       if (value.equalsIgnoreCase("1")) {
           dvdPlayer.displayResultionDisplay();
       } else {
           dvdPlayer.processRemoteCMD();
       }

   }

   public static void main(String a[]) {

       System.out.println("Here are the DVD Player Remote methods");
       System.out.println(" ");

       System.out.println("please select displayResultionDisplay -1 and processRemoteCMD -2");
       System.out.println(" ");

       Scanner sc = new Scanner(System.in);

       value = sc.nextLine();

       DVDSimulationDisplay.displayCMD();

   }

}

You are to design and then build a software simulation of a DVD player that also has WIFI capability and can connect to Netflix and play streaming video (we will keep it to Netflix at the moment). You are given the complete specification for the remote control until. It is modeled in the Analysis Classification model provided to you. Your task will be:

In assignment #4 to complete the analysis and design of the DVDPLayer class which is the model (in the MV two-tier arvchitecture) so that we can test out its functioning against the remote control before actually building the hardware DVD Player.

Implement the classes RemoteControl and DVDPlayer to demonstrate that the remote control can correctly and completely control the DVD player. For output of the DVD player functioning you can either direct status messages to the console, or build a GUI to demonstrate the DVD status. In either case, this is a view and must be totally separate from the DVDPlayer class.

System Requirements:

The remote control has been chosen. The following descriptions provide what is expected behaviour from the DVD player when each button is pressed:

HomeBtn: places the DVD player into home state and displays the home screen. If connected to the inetrnet, the connection is terminated. If a DVD is playing, it is stopped.

InternetBtn: If at home screen and internet service is available, connect to the last internet site visited (ex. Netflix). If there is no last site, go to “list of sites” screen. If no internet service is available, do nothing.

NavRightBtn: Move the cursor display to the right

NavLeftBtn: Move the cursor display to the left

NavUpBtn: Move the cursor display up one line

NavDownBtn: Move the cursor display down one line

PlayBtn: if a DVD is inserted and we are not in internet mode, begin playing the DVD. If

connected to an internet site, play (or select) the highlighted item (ex. Movie)

StopBtn: if playing a DVD, stop playing. If streaming an Internet movie stop and return to the

movie select screen.

PauseBtn: Pause playing the DVD or Internet movie

FFwdBtn: Fast-forward the DVD or Internet movie

FRevBtn: Fast-reverse the DVD or Internet movie

SkipSceneFwdBtn: skip one sceen forward on the DVD; if an internet movie, play in fast-forward

SkipSceneRevBtn: skip one sceen backward on the DVD; if an internet movie, play in fast-reverse

EjectBtn: If a DVD is in the drawer, open the drawer.

CloseDrawerBtn: Close the drawer if open.

OpenDrawerBtn: Open the drawer if closed.

AcceptBtn: (Internet only) Accept the highlighted item on the Internet site

PowerBtn: If DVD is currently ON, turn it OFF. If it is OFF, turn it ON.

In this part, you implement your model in Java. This part will not be marked according to how well the implementation behaves according to the description of the DVD. It will be marked according to how well you implemented your model from assignment #4. You must:

Accurately implement your model (behaviors, states, events and relationships)

Keep the model separate from the view – no view code in the model; no model code in the view

You may use either a GUI or console for the view (or a combination). For example, you can have

a window GUI representing the buttons of the remote, while displaying text on the console advising what the DVD is doing. Do not incorporate input/output into the console if you use a GUI for the remote.

You may

o Make minor adjustments to your model while implementing: you may discover that you identified attributes that are, in fact, redundent or unnecessary. You may also discover the need for attributes you did not identify in the model. Also methods may be identifed in your model that you now find unnecssary, or introduce methods that are not in the model because you discovered they were necessary.

o Any deviations from the model must be well documented (i.e. why you removed the characteristic, or why you introduced a characteristic)

Explanation / Answer

I implemented the following code related to remote control.

public class TVRemote implements RemoteControl

{

private boolean power;

private boolean muted;

private int MIN_CHANNEL = 2;

private int MAX_CHANNEL = 10;

private int channel;

private int MIN_VOLUME = 0;

private int MAX_VOLUME = 10;

private int volume;

private boolean checkMute = true; // added to check if muted is true or false

public TVRemote()

{

boolean power = false;

muted = false;

channel =MIN_CHANNEL;

volume = MIN_VOLUME;

}

public boolean getPower()

{

return power;

}

public boolean getMuted()

{

return muted;

}

public int getChannel()

{

return channel;

}

public int getVolume ()

{

return volume;

public void powerOnOff()

{

if (power)

muted = muted;

else

power =! power;

}

public void mute ()

{

if (power)

muted =!muted;

}

public void channelUp ()

{

if (power)

{

if (channel == MAX_CHANNEL)

{

channel = MIN_CHANNEL;

}

else

{

channel++;

}

}

}

public void channelDown()

{

if (power)

{

if (channel == MIN_CHANNEL)

{

channel = MAX_CHANNEL;

}

else

{

channel--;

}

} }

}

public void volumeUp ()

{

if (power)

{

if (muted == checkMute)

{

volume = MAX_VOLUME;

}

else

{

volume++;

}

}

public void volumeDown ()

{

if (power)

{

if (muted == checkMute)

{

volume = MIN_VOLUME;

}

else

{

volume--;

}

}

}

CLIENT:

RemoteClientController.java

package org.one.stone.soup.remote.control.client;

import java.awt.event.ActionEvent;

import java.awt.event.KeyListener;

public interface RemoteClientController extends KeyListener{

public void actionPerformed( ActionEvent actionEvent );

public void requestNextFrame();

}

RemoteControlClient.java

package org.one.stone.soup.remote.control.client;

import java.awt.Component;

import org.one.stone.soup.screen.recorder.ScreenPlayerListener;

public interface RemoteControlClient extends ScreenPlayerListener{

public abstract void setFullscreen(boolean state);

public Component getView();

public void dispose();

}

HUB:

HubHelper.java

package org.one.stone.soup.remote.control.hub;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

public class HubHelper {

public static String login(String subdomain,Socket socket,String userName,String password) throws IOException

{

return login(subdomain,socket.getOutputStream(),socket.getInputStream(),userName,password);

}

public static String login(String subdomain,OutputStream oStream,InputStream iStream,String userName,String password) throws IOException

{

System.out.println("Logging into hub. Sending "+subdomain);

writeLine(subdomain,oStream);

System.out.println("Waiting for response.");

String line = readLine(iStream);

System.out.println("Received "+line);

System.out.println("Sending alias "+userName);

writeLine( userName+":"+password,oStream );

System.out.println("Waiting for response.");

line = readLine(iStream);

System.out.println("Received "+line);

if(line.equals("BYE"))

{

iStream.close();

oStream.close();

System.out.println("Login to hub failed.");

return null;

}

else if(( line.indexOf("HELLO ")==0 ))

{

String serverKey = line.substring( line.indexOf("HELLO ")+6 );

System.out.println("Logged into hub.");

return serverKey;

}

iStream.close();

oStream.close();

System.out.println("Login to hub failed.");

return null;

}

public static String readLine(InputStream iStream) throws IOException

{

int in = iStream.read();

StringBuffer buffer = new StringBuffer();

while(in!=-1 && in!=' ' && buffer.length()<100)

{

if(in!=0) // keep alive byte

{

buffer.append((char)in);

}

in = iStream.read();

}

System.out.println("< "+buffer.toString());

return buffer.toString();

}

public static void writeLine(String line,OutputStream outputStream) throws IOException

{

outputStream.write( (line+" ").getBytes() );

outputStream.flush();

System.out.println("> "+line);

}

}

HubServer.java

package org.one.stone.soup.remote.control.hub;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.util.Enumeration;

import java.util.Hashtable;

import org.one.stone.soup.authentication.client.Authenticator;

import org.one.stone.soup.authentication.server.AccessCheck;

import org.one.stone.soup.authentication.server.Login;

import org.one.stone.soup.constants.TimeConstants;

import org.one.stone.soup.io.Connection;

import org.one.stone.soup.io.ConnectionListener;

import org.one.stone.soup.io.StreamConnection;

import org.one.stone.soup.net.SocketConnection;

import org.one.stone.soup.server.PlainServer;

import org.one.stone.soup.server.RouterThread;

import org.one.stone.soup.server.http.Logger;

import org.one.stone.soup.stringhelper.StringArrayHelper;

import org.one.stone.soup.util.TimeWatch;

public class HubServer extends PlainServer implements ConnectionListener,ActionListener{

private Hashtable sessions = new Hashtable();

private Authenticator authenticator;

private Logger logger;

private SessionListener sessionListener;

private long lastDataSize = 0;

private long maxDataSize = 1;

public class Session implements Runnable

{

String owner;

String user;

String alias;

Socket serverSocket;

Socket clientSocket;

SocketConnection connection;

public Session()

{

new Thread(this,"Session keep alive").start();

}

public void run()

{

while(alive && !active)

{

if(serverSocket!=null)

{

try{

Thread.sleep(1000);

serverSocket.getOutputStream().write(0);

serverSocket.getOutputStream().flush();

}

catch(Exception e)

{

//e.printStackTrace();

alive=false;

}

}

}

}

boolean alive = true;

boolean active = false;

}

private TimeWatch connectionChecker;

public HubServer(String address,int port,String alias,Authenticator authenticator,Logger logger) throws Exception

{

this.alias = alias;

this.authenticator = authenticator;

this.logger = logger;

start("Remote Control Hub",address,port,100,1000);

connectionChecker = new TimeWatch(5000);

connectionChecker.setActionCommand("check connections");

connectionChecker.addActionListener(this);

connectionChecker.startTimer();

}

public void stop()

{

super.stop();

Enumeration keys = sessions.keys();

while(keys.hasMoreElements())

{

Object key = keys.nextElement();

Session session = (Session)sessions.get(key);

try{

session.clientSocket.close();

}catch(Exception e){}

try{

session.serverSocket.close();

}catch(Exception e){}

}

}

public void setSessionListener(SessionListener listener)

{

this.sessionListener = listener;

}

public void actionPerformed(ActionEvent ae)

{

int sessionCount = 0;

long dataSent = 0;

try{

Enumeration enumerator = sessions.keys();

while(enumerator.hasMoreElements())

{

String key = enumerator.nextElement().toString();

Session session = (Session)sessions.get(key);

if(session.alive==false)

{

try{ session.clientSocket.close(); }catch(Exception e){}

try{ session.serverSocket.close(); }catch(Exception e){}

try{ session.connection.close(); }catch(Exception e){}

if(sessionListener!=null)

{

sessionListener.sessionClosed(session.owner,session.user);

}

sessions.remove(key);

Login login = new Login(null,session.owner,null);

authenticator.logout(login);

System.out.println(login.getResult()+" Session "+key+" closed and now removed.");

}

else

{

sessionCount++;

dataSent+=session.connection.getDataSentSize()+session.connection.getDataReceivedSize();

}

}

} catch(Exception e){}

long dataSize = dataSent-lastDataSize;

if(dataSize>maxDataSize)

{

maxDataSize = dataSize;

}

lastDataSize = dataSent;

sessionListener.logData( sessionCount,dataSize,maxDataSize );

connectionChecker.startTimer();

}

/* (non-Javadoc)

* @see wet.wired.server.Server#route(java.net.Socket, wet.wired.server.RouterThread)

*/

public void route(Socket socket, RouterThread router) {

try{

Login login = login(socket);

if(login==null)

{

return;

}

String[] args = StringArrayHelper.parseFields( login.getSubdomain(),'.' );

String type = args[0];

String flavour = args[1];

if(type.equals("client"))

{

makeClientConnection(socket,login,flavour);

}

else if(type.equals("server"))

{

makeServerConnection(socket,login,flavour);

}

else

{

socket.close();

}

}

catch(Exception e)

{

try{ socket.close(); }catch(Exception e2){}

}

}

private void makeClientConnection(Socket socket,Login login,String flavour) throws IOException

{

InputStream iStream = socket.getInputStream();

String request = readLine( iStream );

Session session = (Session)sessions.get( request+"."+flavour );

connectSession( login.getUser().getName(),request+"."+flavour,session,socket );

System.out.println("Client.control created. Alias:"+request);

}

private void makeServerConnection(Socket socket,Login login,String flavour) throws IOException

{

Session session = new Session();

session.serverSocket = socket;

session.owner = login.getUser().getName();

sessions.put( login.getUser().getName()+"."+flavour,session );

System.out.println("Server.screen created. Alias:"+login.getUser().getName());

}

private Login login(Socket socket) throws IOException

{

InputStream iStream = socket.getInputStream();

String connectionType = readLine( iStream );

writeLine( "LOGIN",socket.getOutputStream() );

String userName = readLine(iStream);

String password = null;

String[] args = StringArrayHelper.parseFields(userName,':');

if(args.length!=2)

{

logger.log("Hub Server login failed for request "+userName);

writeLine( "BYE",socket.getOutputStream() );

socket.close();

return null;

}

else

{

userName=args[0];

password=args[1];

}

Login login = new Login(alias,userName,password);

if(authenticate(login,connectionType)==false)

{

System.out.println("Login failed:"+login.getResult());

logger.log("Hub Server login failed for "+userName);

writeLine( "BYE",socket.getOutputStream() );

socket.close();

return null;

}

writeLine( "HELLO "+login.getPebble(),socket.getOutputStream() );

logger.log("Hub Server "+userName+" logged in");

login.setSubdomain(connectionType);

return login;

}

/* (non-Javadoc)

* @see wet.wired.server.Server#initialize()

*/

public void initialize() {}

private void connectSession(String user,String alias,Session session,Socket client)

{

session.active=true;

session.alive=true;

session.user = user;

session.clientSocket = client;

try{

session.connection = new SocketConnection(session.clientSocket,session.serverSocket,alias,this);

logger.log("Hub session "+alias+" connected for "+user);

}

catch(Exception e)

{

//XappRootApplication.displayException(e);

try{

session.clientSocket.close();

}catch(Exception e2){}

try{

session.serverSocket.close();

}catch(Exception e2){}

return;

}

if(sessionListener!=null)

{

sessionListener.sessionOpened(session.owner,session.user);

}

}

public void connectionClosed(Connection connection)

{

String alias = connection.getAlias();

System.out.println("Closing connection "+alias);

try{

connection.close();

}

catch(Exception e)

{

e.printStackTrace();

}

Session session = (Session)sessions.get(alias);

if(session==null)

{

return;

}

session.active=false;

session.alive=false;

if(sessionListener!=null)

{

sessionListener.sessionClosed(session.owner,session.user);

}

}

public static String readLine(InputStream iStream) throws IOException

{

int in = iStream.read();

StringBuffer buffer = new StringBuffer();

while(in!=-1 && in!=' ' && buffer.length()<100)

{

if(in!=0) // keep alive byte

{

buffer.append((char)in);

}

in = iStream.read();

}

return buffer.toString();

}

public static void writeLine(String line,OutputStream outputStream) throws IOException

{

outputStream.write( (line+" ").getBytes() );

outputStream.flush();

}

public boolean authenticate(Login login,String subdomain)

{

login.setPebble(login.getPassword());

login = authenticator.login(login);

if(login.isLoggedIn()==true)

{

AccessCheck check = authenticator.userCanAccess(login,alias,subdomain);

if(check.isAllowed()==true)

{

return true;

}

else

{

return false;

}

}

return false;

}

public void downStreamConnectionCreated(StreamConnection arg0) {

// TODO Auto-generated method stub

}

public void sent(byte[] arg0, int arg1, StreamConnection arg2) throws IOException {

// TODO Auto-generated method stub

}

public void upStreamConnectionCreated(StreamConnection arg0) {

// TODO Auto-generated method stub

}

}

SessionListener.java

package org.one.stone.soup.remote.control.hub;

public interface SessionListener {

public void sessionOpened(String owner,String user);

public void sessionClosed(String owner,String user);

public void logData( int sessionCount,long dataSent,long maxDataSize );

}

SERVER:

ControlAdapter.java

package org.one.stone.soup.remote.control.server;

public interface ControlAdapter {

public void keyPress(int code);

public void keyRelease(int code);

public void mouseMove(int x,int y);

public void mousePress(int code);

public void mouseRelease(int code);

}

ControlConnection.java

package org.one.stone.soup.remote.control.server;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import org.one.stone.soup.xml.XmlElement;

import org.one.stone.soup.xml.XmlParser;

import org.one.stone.soup.xml.stream.XmlLoader;

public class ControlConnection implements Runnable{

private OutputStream oStream;

private InputStream iStream;

private Thread thread;

private boolean running = false;

private boolean fullControl = false;

private RemoteControlServer server;

private ControlAdapter adapter;

public ControlConnection(RemoteControlServer server,OutputStream oStream,InputStream iStream,boolean fullControl,ControlAdapter adapter)

{

this.adapter = adapter;

this.fullControl = fullControl;

this.server = server;

this.iStream = iStream;

this.oStream = oStream;

}

public void process()

{

thread = new Thread(this,"Control Thread");

thread.start();

}

public void run()

{

try{

XmlParser parser = XmlLoader.getStandardParser();

XmlElement packet = null;

running = true;

while(running)

{

packet = parser.parseElement(iStream);

if(packet==null)

{

break;

}

//System.out.println("Request:"+packet.toXml());

if(packet.getName().equals("nextFrame"))

{

server.setReadyForFrame();

}

else if(packet.getName().equals("sendKeyFrame"))

{

server.sendKeyFrame();

}

else if(fullControl)

{

if(packet.getName().equals("keyPressed"))

{

adapter.keyPress( Integer.parseInt(packet.getAttributeValueByName("code")) );

}

else if(packet.getName().equals("keyReleased"))

{

adapter.keyRelease( Integer.parseInt(packet.getAttributeValueByName("code")) );

}

else if(packet.getName().equals("mouseMoved"))

{

adapter.mouseMove( Integer.parseInt(packet.getAttributeValueByName("x")),Integer.parseInt(packet.getAttributeValueByName("y")));

}

else if(packet.getName().equals("mousePressed"))

{

adapter.mousePress( Integer.parseInt(packet.getAttributeValueByName("code")) );

}

else if(packet.getName().equals("mouseReleased"))

{

adapter.mouseRelease( Integer.parseInt(packet.getAttributeValueByName("code")) );

}

}

}

running = false;

}

catch(Exception e)

{

e.printStackTrace();

}

try{ iStream.close(); }catch(Exception e){}

server.disconnect();

}

public void sendFrameMarker(boolean fullFrame) throws IOException

{

if(running==false)

{

return;

}

if(fullFrame)

{

oStream.write( "<fullFrame/>".getBytes() );

}

else

{

oStream.write( "<frame/>".getBytes() );

}

oStream.flush();

}

public void stop()

{

try{

running = false;

iStream.close();

}

catch(Exception e){}

/*try{

thread.stop();

}

catch(Exception e)

{}*/

}

}

DesktopControlAdapter.java

package org.one.stone.soup.remote.control.server;

import java.awt.Robot;

public class DesktopControlAdapter implements ControlAdapter {

private Robot robot;

public DesktopControlAdapter()

{

try{

robot = new Robot();

}

catch(Exception e)

{

e.printStackTrace();

}

}

public void keyPress(int code) {

robot.keyPress(code);

}

public void keyRelease(int code) {

robot.keyRelease(code);

}

public void mouseMove(int x, int y) {

robot.mouseMove(x,y);

}

public void mousePress(int code) {

robot.mousePress(code);

}

public void mouseRelease(int code) {

robot.mouseRelease(code);

}

}

JavaControlAdapter.java

package org.one.stone.soup.remote.control.server;

import java.awt.Component;

import java.awt.EventQueue;

import java.awt.Frame;

import java.awt.Point;

import java.awt.Toolkit;

import java.awt.event.KeyEvent;

import java.awt.event.MouseEvent;

import org.one.stone.soup.swing.JRootFrame;

public class JavaControlAdapter implements ControlAdapter {

private class Source

{

public Point position;

public Component component;

}

private EventQueue queue;

private Frame source;

private int x=0;

private int y=0;

private boolean dragging = false;

public JavaControlAdapter(Frame source)

{

this.source = source;

queue = Toolkit.getDefaultToolkit().getSystemEventQueue();

}

public void keyPress(int code) //TODO not working

{

Source clickSource = getClickSource();

KeyEvent event = new KeyEvent(clickSource.component,KeyEvent.KEY_PRESSED,System.currentTimeMillis(),0,code,(char)code);

queue.postEvent(event);

}

public void keyRelease(int code) //TODO not working

{

Source clickSource = getClickSource();

KeyEvent event = new KeyEvent(clickSource.component,KeyEvent.KEY_RELEASED,System.currentTimeMillis(),0,code,(char)code);

queue.postEvent(event);

}

public void mouseMove(int x, int y) {

this.x = x-5;

this.y = y-50;

if(dragging) //TODO not working

{

MouseEvent event = new MouseEvent(source,MouseEvent.MOUSE_DRAGGED,System.currentTimeMillis(),14,x,y,1,false,MouseEvent.BUTTON1);

queue.postEvent(event);

}

else

{

MouseEvent event = new MouseEvent(source,MouseEvent.MOUSE_MOVED,System.currentTimeMillis(),0,x,y,0,false);

queue.postEvent(event);

}

source.repaint(1);

}

public void mousePress(int code) {

Source clickSource = getClickSource();

MouseEvent event = new MouseEvent(clickSource.component,MouseEvent.MOUSE_PRESSED,System.currentTimeMillis(),code,clickSource.position.x,clickSource.position.y,1,false,MouseEvent.BUTTON1);

queue.postEvent(event);

dragging = true;

source.repaint();

}

public void mouseRelease(int code) {

Source clickSource = getClickSource();

MouseEvent event = new MouseEvent(clickSource.component,MouseEvent.MOUSE_RELEASED,System.currentTimeMillis(),code,clickSource.position.x,clickSource.position.y,1,false,MouseEvent.BUTTON1);

queue.postEvent(event);

dragging = false;

source.repaint();

}

private Source getClickSource()

{

Component clickSource = source;

int posX = x;

int posY = y;

Component nextClickSource = ((JRootFrame)source).getContentPane().getComponentAt(posX,posY);

while(nextClickSource!=null && nextClickSource!=clickSource)

{

clickSource = nextClickSource;

Point pos = clickSource.getLocation();

posX=posX-pos.x;

posY=posY-pos.y;

nextClickSource = clickSource.getComponentAt(posX,posY);

}

Source source = new Source();

source.position = new Point(posX,posY);

source.component = clickSource;

return source;

}

}

RemoteControlHubConnection.java

package org.one.stone.soup.remote.control.server;

import java.io.IOException;

import java.net.Socket;

import javax.swing.JOptionPane;

import org.one.stone.soup.io.Connection;

import org.one.stone.soup.net.SocketConnection;

import org.one.stone.soup.remote.control.hub.HubHelper;

import org.one.stone.soup.server.http.client.HttpTunnelConnection;

import org.one.stone.soup.stringhelper.StringGenerator;

public class RemoteControlHubConnection implements Runnable{

private String hubAlias;

private Connection screenConnection;

private Connection controlConnection;

private RemoteControlServer server;

private String hubPassword;

public RemoteControlHubConnection(String alias,String password,RemoteControlServer server)

{

this.server = server;

this.hubAlias = alias;

this.hubPassword = password;

}

/*

* write connection type (screen)

* login

*

* write connection type (control)

* login

*

*/

public void connect(String address,int port) throws IOException

{

connect(null,address,port);

}

public void connect(String tunnelUrl,String address,int port) throws IOException

{

if(tunnelUrl!=null)

{

screenConnection = new HttpTunnelConnection(tunnelUrl,address,port);

}

else

{

screenConnection = new SocketConnection( new Socket(address,port),address+":"+port );

}

//RemoteControlServer.writeLine("server.screen",screenSocket.getOutputStream());

//String pebble = login(screenSocket,hubPassword);

String pebble = HubHelper.login("server.screen",screenConnection.getOutputStream(),screenConnection.getInputStream(),hubAlias,hubPassword);

if(tunnelUrl!=null)

{

controlConnection = new HttpTunnelConnection(tunnelUrl,address,port);

}

else

{

controlConnection = new SocketConnection( new Socket(address,port),address+":"+port );

}

//RemoteControlServer.writeLine("server.control",controlSocket.getOutputStream());

//login(controlSocket,pebble);

if( pebble==null || HubHelper.login("server.control",controlConnection.getOutputStream(),controlConnection.getInputStream(),hubAlias,pebble)==null )

{

throw new IOException("Login failed");

}

new Thread(this,"Hub Connection").start();

}

public void run()

{

try{

//InputStream iStream = screenConnection.getInputStream();

/*String request = RemoteControlServer.readLine( iStream );

if(request.equals("connect"))

{*/

//packet.getAttributeValueByName("alias");

server.route(screenConnection,null);

server.route(controlConnection,null);

//}

}

catch(Exception e){}

}

public void disconnect()

{

try{

screenConnection.close();

}catch(Exception e){}

try{

controlConnection.close();

}catch(Exception e){}

}

}

RemoteControlServer.java

package org.one.stone.soup.remote.control.server;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import javax.swing.JOptionPane;

import org.one.stone.soup.io.Connection;

import org.one.stone.soup.net.SocketConnection;

import org.one.stone.soup.screen.recorder.ScreenRecorder;

import org.one.stone.soup.screen.recorder.ScreenRecorderListener;

import org.one.stone.soup.server.PlainServer;

import org.one.stone.soup.server.RouterThread;

import org.one.stone.soup.stringhelper.StringGenerator;

public class RemoteControlServer extends PlainServer implements ScreenRecorderListener {

private String connectionId;

private String key;

private String requester;

private boolean hasConnection = false;

private boolean autoAccept = false;

private boolean readyForFrame = false;

private int framesInProgress = 0;

private ScreenRecorder screenRecorder;

private RemoteControlServerApplication owner;

private ControlConnection controlConnection;

public RemoteControlServer(RemoteControlServerApplication owner)

{

this.owner = owner;

}

public void setAutoAccept(boolean state)

{

autoAccept = state;

}

/* (non-Javadoc)

* @see wet.wired.server.Server#route(java.net.Socket, wet.wired.server.RouterThread)

*/

public void route(Socket socket, RouterThread routerThread) {

try{

SocketConnection connection = new SocketConnection( socket,socket.getInetAddress().getHostAddress() );

route( connection,routerThread );

}

catch(Exception e)

{

e.printStackTrace();

}

}

public void route(Connection connection, RouterThread routerThread) {

try{

if(hasConnection)

{

System.out.println("Connection Requested for "+connection.getAlias());

if(connection.getAlias().equals(connectionId))

{

String testKey = readLine(connection.getInputStream());

if(!testKey.toString().equals(key))

{

try

{

connection.close();

} catch(Exception e){}

return;

}

System.out.println("Request Key Passed");

String connectionType = readLine(connection.getInputStream());

if(routerThread!=null)

{

routerThread.stopTimer();

}

System.out.println("Connection Requested Type "+connectionType);

openConnection( connectionType.toString(),connection,requester );

System.out.println("Connection created. Type "+connectionType);

}

}

else

{

InputStream iStream = connection.getInputStream();

requester = readLine(iStream);

if( autoAccept==false && JOptionPane.showConfirmDialog(owner.getRootFrame(),"Accept Connection from "+requester)!=JOptionPane.OK_OPTION )

{

try

{

connection.close();

} catch(Exception e){}

return;

}

else

{

key = StringGenerator.generateUniqueId();

connection.getOutputStream().write( (key+' ').getBytes() );

connection.getOutputStream().flush();

owner.setRequester( requester );

}

//int identifier = socket.getInputStream().read();

hasConnection = true;

connectionId = connection.getAlias();

if(routerThread!=null)

{

routerThread.stopTimer();

}

screenRecorder = owner.getScreenRecorder(connection.getOutputStream(),this);

//frameRecorded(); //wait for client frame request

screenRecorder.startRecording();

System.out.println("Screen Recorder Started for "+connectionId);

}

}

catch(Exception e)

{

}

finally

{

}

}

/* (non-Javadoc)

* @see wet.wired.server.Server#initialize()

*/

public void initialize() { }

private void openConnection(String command,Connection connection,String requester)

{

if(command.equals("fullControl"))

{

try{

openControlConnection(connection.getOutputStream(),connection.getInputStream(),requester,true);

}

catch(Exception e){}

}

else

{

try{

openControlConnection(connection.getOutputStream(),connection.getInputStream(),requester,false);

}

catch(Exception e){}

}

}

/* private void openConnection(String command,Socket socket,String requester)

{

if(command.equals("fullControl"))

{

try{

openControlConnection(socket.getOutputStream(),socket.getInputStream(),requester,true);

}

catch(Exception e){}

}

else

{

try{

openControlConnection(socket.getOutputStream(),socket.getInputStream(),requester,false);

}

catch(Exception e){}

}

}*/

private void openControlConnection(OutputStream oStream,InputStream iStream,String requester,boolean fullControl)

{

if( autoAccept==false && fullControl==true)

{

if(JOptionPane.showConfirmDialog(owner.getRootFrame(),"Accept Control by "+requester)!=JOptionPane.OK_OPTION )

{

fullControl=false;

}

}

try

{

controlConnection = new ControlConnection(this,oStream,iStream,fullControl,owner.getControlAdapter());

controlConnection.process();

} catch(Exception e){}

}

public void stop()

{

super.stop();

disconnect();

}

public void disconnect()

{

if(screenRecorder!=null)

{

screenRecorder.stopRecording();

}

screenRecorder = null;

setReadyForFrame();

if(controlConnection!=null)

{

controlConnection.stop();

controlConnection=null;

}

hasConnection=false;

System.out.println("Disconnected");

owner.disconnect();

}

public void setReadyForFrame()

{

readyForFrame=true;

framesInProgress--;

}

public void sendKeyFrame()

{

screenRecorder.sendKeyFrame();

}

public void frameRecorded(boolean fullFrame) throws IOException

{

int count=0;

while( controlConnection==null && count<500)

{

try{ Thread.sleep(10); }catch(Exception e){}

count++;

}

if(count==500)

{

throw new IOException( "Frame timeout" );

}

try{

controlConnection.sendFrameMarker(fullFrame);

}

catch(Exception e)

{

e.printStackTrace();

disconnect();

return;

}

framesInProgress++;

count=0;

while(framesInProgress>2 && screenRecorder.isRecording() && count<500)

{

try{ Thread.sleep(10); }catch(Exception e){}

count++;

}

if(count==500)

{

throw new IOException( "Frame timeout" );

}

readyForFrame=false;

}

public void recordingStopped() {

disconnect();

}

public static String readLine(InputStream iStream) throws IOException

{

int in = iStream.read();

StringBuffer buffer = new StringBuffer();

while(in!=-1 && in!=' ' && buffer.length()<100)

{

if(in!=0) // keep alive byte

{

buffer.append((char)in);

}

in = iStream.read();

}

return buffer.toString();

}

public static void writeLine(String line,OutputStream outputStream) throws IOException

{

outputStream.write( (line+" ").getBytes() );

outputStream.flush();

}

}

RemoteControlServerApplication.java

package org.one.stone.soup.remote.control.server;

import java.awt.Frame;

import java.io.OutputStream;

import org.one.stone.soup.screen.recorder.ScreenRecorder;

import org.one.stone.soup.screen.recorder.ScreenRecorderListener;

public interface RemoteControlServerApplication {

public Frame getRootFrame();

public void disconnect();

public void setRequester(String requester);

public ControlAdapter getControlAdapter();

public ScreenRecorder getScreenRecorder(OutputStream outputStream,ScreenRecorderListener listener);

}

Hope this helps. Thanks.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote