id
stringlengths
36
36
text
stringlengths
1
1.25M
884b2664-1ecd-4122-a7e9-208bc5b8b5d6
public ServerMessage() { }
afe2789e-f652-4575-a508-e5f9825638ad
public UserBean getUser() { return user; }
b54ecfee-7eff-40c1-964e-218171c9198b
public void setUser(UserBean user) { this.user = user; }
97eec601-b83e-4f60-9875-f4ff576f43e3
public String getCommand() { return command; }
b5b41630-590e-4b21-8d4b-f0600691a1e1
public void setCommand(String command) { this.command = command; }
48056298-bcd6-4c81-ae05-c025085720e7
public static void main(String args[]) { new View(new Model()); }
f8e8fcd1-5af9-40de-80ab-6a6026f7dc4d
public View(Model m) { super.setSize(800,800); super.setDefaultCloseOperation(EXIT_ON_CLOSE); super.setLayout(new GridBagLayout()); this.m = m; super.setResizable(false); super.setLocationRelativeTo(null); control = new Controller(this,m); this.lose = new JFrame(); lose.setSize(400,100); lose.setDefaultCloseOperation(DISPOSE_ON_CLOSE); lose.setResizable(false); lose.setLocationRelativeTo(null); this.loseMessage = new JLabel(); loseMessage.setText("You lose, ending game..."); lose.add(loseMessage); this.win = new JFrame(); win.setSize(400,100); win.setDefaultCloseOperation(DISPOSE_ON_CLOSE); win.setResizable(false); win.setLocationRelativeTo(null); this.winMessage = new JLabel(); winMessage.setText("You win, ending game..."); win.add(winMessage); this.gameRejected = new JFrame(); gameRejected.setSize(400,100); gameRejected.setDefaultCloseOperation(DISPOSE_ON_CLOSE); gameRejected.setResizable(false); gameRejected.setLocationRelativeTo(null); this.rejectedMessage = new JLabel(); rejectedMessage.setText("Invite rejected"); gameRejected.add(rejectedMessage); this.gameStarted = new JFrame(); gameStarted.setSize(400,100); gameStarted.setDefaultCloseOperation(DISPOSE_ON_CLOSE); gameStarted.setResizable(false); gameStarted.setLocationRelativeTo(null); this.startMessage = new JLabel(); startMessage.setText("Invite accepted, game starting in 2 seconds"); gameStarted.add(startMessage); this.tie = new JFrame(); tie.setSize(400,100); tie.setDefaultCloseOperation(DISPOSE_ON_CLOSE); tie.setResizable(false); tie.setLocationRelativeTo(null); this.tieMessage = new JLabel(); tieMessage.setText("Game tied, ending game..."); tie.add(tieMessage); this.initialWindow(); }
77e47696-8023-45fa-981a-606335639bf3
public void setNewBoard() { initial.setVisible(false); initial.dispose(); GridBagConstraints c = new GridBagConstraints(); JButton button; ///////First fow of tictactoe button = new JButton(b00); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 0; c.gridy = 0; //button.setIcon(x); board[0][0] = button; //button.addActionListener(l) button.addActionListener(control); super.add(button, c); button = new JButton(b01); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 1; c.gridy = 0; board[0][1] = button; button.addActionListener(control); super.add(button, c); button = new JButton(b02); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 2; c.gridy = 0; board[0][2] = button; button.addActionListener(control); super.add(button, c); ///////Second row button = new JButton(b10); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 0; c.gridy = 1; board[1][0] = button; button.addActionListener(control); super.add(button, c); button = new JButton(b11); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 1; c.gridy = 1; board[1][1] = button; button.addActionListener(control); super.add(button, c); button = new JButton(b12); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 2; c.gridy = 1; board[1][2] = button; button.addActionListener(control); super.add(button, c); ///////Thid row button = new JButton(b20); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 0; c.gridy = 2; board[2][0] = button; button.addActionListener(control); super.add(button, c); button = new JButton(b21); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 1; c.gridy = 2; board[2][1] = button; button.addActionListener(control); super.add(button, c); button = new JButton(b22); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.25; c.gridx = 2; c.gridy = 2; board[2][2] = button; button.addActionListener(control); super.add(button, c); ///////Fouth row f = new JTextField(); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.05; c.gridx = 0; c.gridy = 3; super.add(f, c); button = new JButton(JOIN); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0.25; c.weighty = 0.05; c.gridx = 1; c.gridy = 3; button.addActionListener(control); super.add(button, c); button = new JButton(LEAVE); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0.25; c.weighty = 0.05; c.gridx = 2; c.gridy = 3; button.addActionListener(control); super.add(button, c); ///////Fifth row for errors error = new JTextField(); c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.05; c.gridx = 0; c.gridy = 4; c.gridwidth = 3; error.setEditable(false); super.add(error,c); //Scroll panel displaying other hosts c.fill = GridBagConstraints.BOTH; c.weightx = 0.25; c.weighty = 0.9; c.gridx = 3; c.gridy = 0; c.gridheight = 4; scrollPanel = new JPanel(); scrollPanel.setLayout(new GridLayout(10,1)); jsp = new JScrollPane(scrollPanel); super.add(jsp,c); jsp.validate(); jsp.repaint(); //Button at bottom right to list online players button = new JButton(LIST); c.weightx = 0.25; c.weighty = 0.05; c.gridx = 4; c.gridy = 4; c.gridheight = 1; c.gridwidth = 1; button.addActionListener(control); super.add(button,c); this.setVisible(true); }
573c22f6-533f-4d9f-a610-ce57c66ff42a
public String getText() { return this.f.getText(); }
5f3868ea-f969-4148-9045-3358c8d415a5
public void updateOnlineUsers(ArrayList<UserBean> onlineUsers) { JButton user; if(onlineUsers == null) { //No users online, clear all buttons and users from the pane scrollPanel.removeAll(); }else { scrollPanel.removeAll(); //Have users to add for(UserBean b: onlineUsers) { user = new JButton("Invite: " + b.getUserName()); user.addActionListener(control); scrollPanel.add(user); System.out.println("Adding " + b.getUserName()); } } scrollPanel.validate(); jsp.repaint(); scrollPanel.repaint(); super.repaint(); }
02c27bb0-81da-499c-ae8b-03bf980ce12c
public void initialWindow() { initial = new JFrame(); initial.setSize(400,100); initial.setDefaultCloseOperation(EXIT_ON_CLOSE); initial.setLayout(new GridBagLayout()); initial.setResizable(false); initial.setLocationRelativeTo(null); GridBagConstraints c = new GridBagConstraints(); JButton button; ins = new JLabel(); ins.setText("Enter the Directory server name or IP"); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 0.5; c.gridx = 0; c.gridy = 0; c.gridwidth = 3; initial.add(ins,c); server = new JTextField(); c.weightx = 0.5; c.weighty = 0.5; c.gridy = 1; c.gridwidth = 1; initial.add(server,c); button = new JButton(OKAY); c.gridx = 1; c.weightx = 0.15; button.addActionListener(control); initial.add(button, c); button = new JButton(CANCEL); c.gridx = 2; button.addActionListener(control); initial.add(button, c); initial.setVisible(true); }
064876d8-4c83-4e5b-bb1e-23394b2a2b4b
public String getServerEntry() { return this.server.getText(); }
1050fc8c-504d-4cba-81df-e34484cfb5a3
public void setInvalidServerError() { System.out.println("Invalid server"); ins.setText("Unable to contact directory server. Try again."); ins.setForeground(Color.RED); }
67f300bb-54ca-4ae9-a217-d027ddb08908
public void setInviteView(String userName) { invite = new JFrame(); invite.setSize(400,100); invite.setDefaultCloseOperation(DISPOSE_ON_CLOSE); invite.setLayout(new GridBagLayout()); invite.setResizable(false); invite.setLocationRelativeTo(null); GridBagConstraints c = new GridBagConstraints(); JButton button; this.inviteMessage = new JLabel(); inviteMessage.setText("Game invite from: " + userName ); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 0.5; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; invite.add(inviteMessage,c); button = new JButton(ACCEPT); c.gridy = 1; c.gridx = 1; c.weightx = 0.15; button.addActionListener(control); invite.add(button, c); button = new JButton(REJECT); c.gridx = 2; button.addActionListener(control); invite.add(button, c); invite.setVisible(true); }
9beaa3f2-e8d2-4411-b3f8-42154a0578d2
public void closeInvite() { invite.setVisible(false); invite.dispose(); }
381e77cf-7d30-4d58-aa9c-193ecd9e9bf7
public void setPieceIcon(int row, int col, int piece) { System.out.println("changing icon: "); JButton toChange = board[row][col]; if(piece == -1) { toChange.setText(""); toChange.setIcon(x); toChange.invalidate(); super.invalidate(); }else { toChange.setText(""); toChange.setIcon(o); toChange.invalidate(); super.invalidate(); } super.validate(); super.repaint(); }
af1d03ee-4796-44ed-998d-e1af13c7ffa2
public void resetGameBoard() { for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { JButton toChange = this.board[i][j]; toChange.setIcon(null); toChange.setText(i + "" + j); } } }
ef2d0047-a025-4a86-8cf5-71c83880f69d
public void setGameStartMessage() { System.out.println("Setting game start message"); gameStarted.setVisible(true); t.restart(); t.start(); }
3dedf492-ac7d-49fe-bd81-d9497a8edda6
public void closeStartWindow() { gameStarted.setVisible(false); }
bb3622e3-ea12-4803-af64-1611edf028c9
public void setGameRejectedMessage() { gameRejected.setVisible(true); t.restart(); t.start(); }
bd9d48f1-de30-4c32-ae93-70f07d488334
public void closeRejectedWindow() { gameRejected.setVisible(false); }
cf1a22b0-a4ce-4a07-9e79-adccce588b95
public void setWinMessage() { System.out.println("Setting win message"); win.setVisible(true); t.restart(); t.start(); }
3b77d87f-7cd6-4562-a566-704098d7a769
public void closeWinWindow() { win.setVisible(false); }
72e560af-4e2d-44c5-8f0c-3f12a6ee039e
public void setLoseMessage() { System.out.println("Setting lose message"); lose.setVisible(true); t.restart(); t.start(); }
ec2a4812-04af-4567-8ae9-9f2f9761c87b
public void closeLoseWindow() { lose.setVisible(false); }
1e065d00-a621-456a-8b95-15730bbb3012
public void setTieMessage() { System.out.println("Setting tie message"); tie.setVisible(true); t.restart(); t.start(); }
21c06d66-f1e7-4179-bed9-e43e29aebee6
public void closeTieWindow() { tie.setVisible(false); }
5f1a31af-d6af-4610-9b6f-a17c12e8ec5f
public void actionPerformed(ActionEvent e) { t.stop(); closeLoseWindow(); closeWinWindow(); closeStartWindow(); closeRejectedWindow(); closeTieWindow(); }
0532f079-aea2-4d1a-8533-55db0fa35ef9
public Controller(View v, Model m) { this.v = v; this.m = m; Thread control = new Thread(this); control.start(); while(serverType == 0) { try { System.out.println("Sleeping"); Thread.sleep(5); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Thread gameData = new Thread(this); gameData.start(); }
d057d70c-b8f9-41e1-b21b-823f8806fc6e
public void actionPerformed(ActionEvent e) { String event = e.getActionCommand(); System.out.println("Event is: " + event); if(event.equals("JOIN")) { //User pressed JOIN if(v.getText().length() == 0) { System.out.println("No name entered"); } m.joinServer(v.getText()); }else if(event.equals("LEAVE")) { //User pressed leave m.leaveServer(); }else if(event.equals("LIST")) { //User pressed LIST onlineUsers = m.listOnlineUsers(); v.updateOnlineUsers(onlineUsers); }else if(event.equals("CANCEL")) { //User canceled initial window, exit application System.exit(0); }else if(event.equals("OKAY")) { //User entered directory server name/IP, model validates directory server //Based on validation start server or display an error if(m.setServer(v.getServerEntry())) { //Server replied and was valid, display the game board v.setNewBoard(); }else { //Server entered was not valid, display an error message v.setInvalidServerError(); } }else if(event.contains("Invite:")) { //User entered invite m.sendInvite(event); }else if(event.equals("ACCEPT")) { //Invite accepted, start a new game System.out.println("Invite accepted, need to send remote user accept"); v.closeInvite(); m.acceptInvite(possibleOpponent, possiblePiece); v.resetGameBoard(); v.setGameStartMessage(); }else if(event.equals("REJECT")) { //Reject user request for game System.out.println("Invite rejected, need to send remote user reject"); v.closeInvite(); }else if(event.equals("00")) { //button press at x,y //Validate move with model and update GUI //Check win conditions, if have win/lose/tie end the game and set message if(m.makeMove(0, 0)) { int p = m.getPiece(); v.setPieceIcon(0, 0, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } }else if(event.equals("01")) { if(m.makeMove(0, 1)) { int p = m.getPiece(); v.setPieceIcon(0, 1, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } }else if(event.equals("02")) { if(m.makeMove(0, 2)) { int p = m.getPiece(); v.setPieceIcon(0, 2, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } }else if(event.equals("10")) { if(m.makeMove(1, 0)) { int p = m.getPiece(); v.setPieceIcon(1, 0, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } }else if(event.equals("11")) { if(m.makeMove(1, 1)) { int p = m.getPiece(); v.setPieceIcon(1, 1, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } }else if(event.equals("12")) { if(m.makeMove(1, 2)) { int p = m.getPiece(); v.setPieceIcon(1, 2, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } }else if(event.equals("20")) { if(m.makeMove(2, 0)) { int p = m.getPiece(); v.setPieceIcon(2, 0, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } }else if(event.equals("21")) { if(m.makeMove(2, 1)) { int p = m.getPiece(); v.setPieceIcon(2, 1, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } }else if(event.equals("22")) { if(m.makeMove(2, 2)) { int p = m.getPiece(); v.setPieceIcon(2, 2, p); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } } }
5998a1b9-a56d-4aab-8435-467563c5c723
public void run() { // TODO Auto-generated method stub if(serverType == 0) { //Control message server System.out.println("Running control server"); runControlServer(); }else if(serverType == 1) { System.out.println("Running game data server"); this.runGameDataServer(); } }
71ee9cb9-f444-4269-85fc-5b42b3a3f8e0
private synchronized void changeServerType() { this.serverType++; }
c3764b0f-3812-4e4e-9327-64072340fb66
public void runControlServer() { try { controlServerSocket= new ServerSocket(controlDataSocketNumber); this.changeServerType(); while(true) { controlSocket = controlServerSocket.accept(); controlInput = new ObjectInputStream(controlSocket.getInputStream()); ClientMessage c = (ClientMessage) controlInput.readObject(); System.out.println("Got client message with command: " + c.getCommand() ); if(c.getCommand().equals("INVITE")) { if(!m.getHaveGame()) { //Dont have a game, may accept or reject this.possibleOpponent = c.getUser(); this.possiblePiece = c.getPiece() * -1; v.setInviteView(c.getUser().getUserName()); }else { //Have a game already, automatically reject m.rejectInvite(c.getUser()); } }else if(c.getCommand().equals("ACCEPT")) { //Accept invite request m.setIsTurn(); m.setHaveGame(); v.resetGameBoard(); v.setGameStartMessage(); System.out.println("Got accept back"); }else if(c.getCommand().equals("REJECT")) { //Rejected invite v.setGameRejectedMessage(); } } } catch (IOException e) { e.printStackTrace(); System.out.println("Could not start open P2P control socket on port 25201, exiting..."); System.exit(-3); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
c75b8c5a-4211-40f1-be3b-4c2c38d49c60
public void runGameDataServer() { try { gameDataServerSocket = new ServerSocket(gameDataSocketNumber); while(true) { System.out.println("Game data server"); gameDataSocket = gameDataServerSocket.accept(); gameInput = new ObjectInputStream(gameDataSocket.getInputStream()); ClientMessage c = (ClientMessage) gameInput.readObject(); System.out.println("Got game data message with command" + c.getCommand()); if(c.getCommand().equals("MOVE")) { m.setIsTurn(); m.setOpBoardMove(c.getRow(), c.getColumn(),c.getPiece()); v.setPieceIcon(c.getRow(), c.getColumn(), c.getPiece()); int win = m.haveWinCondition(); if(win == -1) { m.endGame(); v.setLoseMessage(); }else if(win == 1) { m.endGame(); v.setWinMessage(); }else if(win == -2) { m.endGame(); v.setTieMessage(); } } } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
c9754b0b-e0c8-424b-9997-baa8242f34e4
public P2PServer(int serverType, int socketNumber, View v) { this.serverType = serverType; this.socketNumber = socketNumber; this.v = v; }
2752dc69-3838-41f4-9c79-7c5131c06b43
public synchronized void run() { if(serverType == 0) { //Control runControlServer(); }else if(serverType == 1) { //Game server } }
c1ce9d08-fd2b-4d5e-9626-96d3bb8a17ea
private void runControlServer() { ServerSocket controlSocket; try { controlSocket = new ServerSocket(socketNumber); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
7b37fd03-80ae-47a0-9e82-de9210908716
public UserBean(String hostName, String userName, String ipAddress) { this.hostName = hostName; this.userName = userName; this.ipAddress = ipAddress; }
0e0fef6c-80d0-467f-8669-bae40486d001
public String getHostName() { return this.hostName; }
b94e2e3d-c4fb-408c-af52-2637eb3685ed
public String getUserName() { return this.userName; }
db9c636f-51ce-4d4a-b9c4-cd72c89d3560
public String getIpAddress() { return this.ipAddress; }
d564e231-5ebe-43bd-9a8a-645b9e57c8bb
public DAO() { users = new ArrayList<UserBean>(); }
2106e948-d111-487e-b43e-fdfdff6c7f6e
public void join(UserBean u) throws InterruptedException { while(semaphore.tryAcquire() == false) { Thread.sleep(5); } boolean canAdd = true; for(UserBean b: users) { if(b.getHostName().equals(u.getHostName())) { System.out.println("Already in list"); canAdd = false; } } if(canAdd) { users.add(u); } semaphore.release(); }
8f36cbfc-5a3a-430f-b348-3de8b68ee145
public void leave(UserBean u) { System.out.println("Leaving....."); try{ while(semaphore.tryAcquire() == false) { Thread.sleep(5); } String hostName = u.getHostName(); for(int i = 0; i < users.size(); i++) { System.out.println(hostName); if(users.get(i).getHostName().equals(hostName)) { users.set(i, null); break; } } users.removeAll(Collections.singleton(null)); }catch(Exception e) { System.out.println("Error leaving"); } semaphore.release(); }
9d1c8a4c-dc4d-40dd-8665-f8c274f70226
public ArrayList<UserBean> list() { ArrayList<UserBean> toReturn = new ArrayList<UserBean>(); try{ while(semaphore.tryAcquire()) { Thread.sleep(5); } toReturn.addAll(users); }catch(Exception e) { System.out.println("Error listing"); } semaphore.release(); return toReturn; }
7630c057-abde-497c-8185-89aafa940efa
public static void main(String args[]) throws IOException { //Server Parameters DAO d = new DAO(); try { ServerSocket mainSocket = new ServerSocket(socketNumber); while(true) { Socket socket = mainSocket.accept(); Responder r = new Responder(socket,d); r.start(); } }catch(Exception e) { System.out.println(e.getMessage()); } }
10517e51-ffe0-456f-b667-03b1bd88da8b
public Responder(Socket socket, DAO dataAccess) { this.dataAccess = dataAccess; try{ this.socket = socket; this.output = new ObjectOutputStream(socket.getOutputStream()); this.input = new ObjectInputStream(socket.getInputStream()); }catch(Exception e) { System.out.println(e.getMessage()); } }
abf68db8-bb18-4121-81d6-7da3518e6093
public void run() { ServerMessage m; try { m = (ServerMessage) input.readObject(); String message = m.getCommand(); if(message.equals("JOIN")) { //Add to the list of users this.dataAccess.join(m.getUser()); System.out.println("got join request"); }else if(message.equals("LEAVE")) { //Remove from list of users this.dataAccess.leave(m.getUser()); System.out.println("got leave request"); }else if(message.equals("LIST")) { //Returns a list of online users System.out.println("Got list request"); ArrayList<UserBean> toSend = this.dataAccess.list(); output.writeObject(toSend); }else if(message.equals("TEST")) { //Responds to connection tests when a client starts System.out.println("Got connection test msg"); output.writeObject("ACTIVE"); } socket.close(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); System.out.println("Class not found exception"); } catch (IOException e1) { e1.printStackTrace(); }catch (InterruptedException e) { e.printStackTrace(); } }
bc5458e6-6150-40c2-a364-d273c78264b4
public DirectoryServer(int socketNumber) throws IOException { directorySocket = new ServerSocket(socketNumber); directorySocket.close(); System.out.println("Done"); }
89a82f2d-9ddb-41ed-94b1-9aedbefa788e
public static void main(String[] args) throws IOException { /**************************************************************************************** * The following block of code only configures the OPTIONAL log4j. * This configuration displays the full WIRE (headers + content) of the HTTP transaction. ***************************************************************************************/ Logger log = Logger.getLogger(GetMMSDeliveryStatus.class.getName()); PropertyConfigurator.configure("log4j.properties"); /**************************************************** * Credentials: * requestId = resource ID from the SendMMS response * senderAddress = MMS Access Code * apiURL = Endpoint URL for your request * token = Token provided by RetrieveToken API *****************************************************/ String requestId = ""; String senderAddress = ""; String token = ""; String apiURL = "https://x.smart.com.ph/1/messaging/outbound/" + senderAddress + "/requests/" + requestId + "/deliveryInfos"; String authorization = "Bearer " + token; // This will be the value of your authorization header //Initialize Apache's HttpClient through an HttpClientBuilder. HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); HttpGet get = new HttpGet(apiURL); //Set the following headers to your request get.addHeader("Content-Type", "application/json"); get.addHeader("Accept","application/json"); get.addHeader("Authorization", authorization); try { HttpResponse response = client.execute(get); // Execute the HttpGet // A successful response is HTTP 200 OK // which will include the delivery receipt. if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } } catch (Exception e) { e.printStackTrace(); } finally { get.releaseConnection(); } }
f085cb68-1142-4f47-93ea-20846393e9b0
public static void main(String[] args) throws IOException { /************************************************************************************ * The following block of code only configures the log4j. This configuration displays * the full WIRE (headers + content) of the HTTP transaction. ***********************************************************************************/ Logger log = Logger.getLogger(SendMMS.class.getName()); PropertyConfigurator.configure("log4j.properties"); /**************************************************** * Credentials: * address = Nominated Mobile Number * senderAddress = MMS Access Code * apiURL = Endpoint URL for your request * token = Token provided by RetrieveToken API * Parameters: * subject = subject of your MMS message * attachmentJPG = your attachment * jsonRequest = the text body of your request *****************************************************/ String address = "tel:"; String senderAddress = ""; String subject = ""; File attachmentJPG = new File("src\\Smart_Logo.jpg"); String token = "tQg1GqXsjqWSGlaA7nbVMUkWcAlV"; String apiURL = "https://x.smart.com.ph/1/messaging/outbound/" + senderAddress + "/requests"; String jsonRequest = "{\"outboundMessageRequest\":{\"address\":\"" + address + "\",\"senderAddress\":\"" + senderAddress+ "\",\"outboundMMSMessage\":{\"subject\":\""+ subject +"\"}}}"; String authorization = "Bearer " + token; // This will be the value of your authorization header //Initialize Apache's HttpClient through an HttpClientBuilder. HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); //Note that my builder disables redirecting to the specified "Location" header of the response. //This is because I want to manually load that location to the browser. HttpPost post = new HttpPost(apiURL); //Set the following headers to your request post.addHeader("Accept","application/json"); post.addHeader("Authorization", authorization); post.addHeader("MIME-Version", "1.0"); /********************************************************** * Create the body and set it to your request. * Since an MMS contains a message and an attachment, * create a Multipart Entity and add the message * and the attachment as two separate parts: * -JSON request * --must have a part name of "root-fields: * --must have a content type of 'applicatin/json' * --must have a charset of UTF-8 * -Attachment * --must have a part name of "Attachments" * --must have a content type equivalent to its file type * --must set a valid file name *********************************************************/ MultipartEntityBuilder reqEntityBuilder = MultipartEntityBuilder.create(); reqEntityBuilder.addBinaryBody("root-fields", new ByteArrayInputStream(jsonRequest.getBytes()), ContentType.create("application/json", Charset.forName("UTF-8")), null); reqEntityBuilder.addBinaryBody("Attachments", new FileInputStream(attachmentJPG), ContentType.create("image/jpg"), attachmentJPG.getName()); HttpEntity reqEntity = reqEntityBuilder.build(); post.setEntity(reqEntity); try { HttpResponse response = client.execute(post); // Execute the HttpPost // A successful response is HTTP 201 Created // which will include a response body. // Use the resource reference ID to // to retrieve the delivery receipt. if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } } catch (Exception e) { e.printStackTrace(); } finally { post.releaseConnection(); } }
1ac1ce6f-da75-4b07-add3-a00a8cda1d64
public static void main(String[] args) { /**************************************************************************************** * The following block of code only configures the OPTIONAL log4j. * This configuration displays the full WIRE (headers + content) of the HTTP transaction. ***************************************************************************************/ Logger log = Logger.getLogger(GetSMSDeliveryStatus.class.getName()); PropertyConfigurator.configure("log4j.properties"); /**************************************************** * Credentials: * requestId = resource ID from the SendSMS response * senderAddress = SMS Access Code * apiURL = Endpoint URL for your request * token = Token provided by RetrieveToken API *****************************************************/ String requestId = ""; String senderAddress = ""; String token = ""; String apiURL = "https://x.smart.com.ph/1/smsmessaging/outbound/" + senderAddress +"/requests/" + requestId + "/deliveryInfos"; String authorization = "Bearer " + token; // This will be the value of your authorization header //Initialize Apache's HttpClient through an HttpClientBuilder. HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); HttpGet get = new HttpGet(apiURL); //Set the following headers to your request get.addHeader("Content-Type", "application/json"); get.addHeader("Accept","application/json"); get.addHeader("Authorization", authorization); try { HttpResponse response = client.execute(get); // Execute the HttpGet // A successful response is HTTP 200 OK // which will include the delivery receipt. if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } } catch (Exception e) { e.printStackTrace(); } finally { get.releaseConnection(); } }
050401c0-403c-4002-8a1d-75474ad0db29
public static void main(String[] args) { /************************************************************************************ * The following block of code only configures the log4j. This configuration displays * the full WIRE (headers + content) of the HTTP transaction. ***********************************************************************************/ Logger log = Logger.getLogger(SendSms.class.getName()); PropertyConfigurator.configure("log4j.properties"); /**************************************************** * Credentials: * address = Nominated Mobile Number * senderAddress = SMS Access Code * apiURL = Endpoint URL for your request * token = Token provided by RetrieveToken API * Parameters * message = Your test message *****************************************************/ String address = "tel:"; String senderAddress = ""; String message = ""; String token = ""; String authorization = "Bearer " + token; // This will be the value of your authorization header String apiURL = "https://x.smart.com.ph/1/smsmessaging/outbound/" + senderAddress + "/requests"; //Initialize Apache's HttpClient through an HttpClientBuilder. HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); HttpPost post = new HttpPost(apiURL); //Set the following headers to your request post.addHeader("Content-Type", "application/json"); post.addHeader("Accept","application/json"); post.addHeader("Authorization", authorization); //Create the body and set it to your request StringEntity jsonrequest = new StringEntity("{\"outboundSMSMessageRequest\":{\"address\":\"" + address + "\",\"senderAddress\": \"" + senderAddress + "\",\"outboundSMSTextMessage\":{\"message\":\"" + message + "\"}}}", "UTF-8"); post.setEntity(jsonrequest); try { HttpResponse response = client.execute(post); // Execute the HttpPost // A successful response is HTTP 201 Created // which will include a response body. // Use the resource reference ID to // to retrieve the delivery receipt. if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } } catch (Exception e) { e.printStackTrace(); } finally { post.releaseConnection(); } }
f773d3c4-b6ef-4826-aacd-967bf2d391e0
public static void main(String[] args) throws ParseException, IOException { /************************************************************************************ * The following block of code only configures the log4j. This configuration displays * the full WIRE (headers + content) of the HTTP transaction. ***********************************************************************************/ Logger log = Logger.getLogger(RetrieveToken.class.getName()); PropertyConfigurator.configure("log4j.properties"); /*********************************************************************************** * Credentials: * clientId = Consumer Key * clientSecret = Consumer Secret Key * callbackURL = Callback URL * apiURL = Endpoint URL for your request * auth_code = {code} parameter from * https://(callback_URL)/?scope=SMS+MMS&state=null&code=(auth_code) ***********************************************************************************/ String clientId = ""; String clientSecret = ""; String callbackURL = "http://www.smart.com.ph"; String apiURL = "https://x.smart.com.ph/oauth/token"; String auth_code = ""; // Important: The auth_code is retrieved once you "Allow" your app to use // the credentials. In order to allow your app, you must follow the Location // link on your AuthorizeApp response. //Initialize Apache's HttpClient through an HttpClientBuilder. HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); //Create the "body" and set it as a URL Encoded entity. List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add((new BasicNameValuePair("client_id", clientId))); parameters.add((new BasicNameValuePair("client_secret", clientSecret))); parameters.add((new BasicNameValuePair("redirect_uri", callbackURL))); parameters.add((new BasicNameValuePair("scope", "SMS+MMS"))); // scope = the allowed function(s) provided to your credential parameters.add((new BasicNameValuePair("grant_type", "authorization_code"))); // grant_type = whether you are requesting for an auth_code token // or a refresh_token if your auth_code has expired. parameters.add((new BasicNameValuePair("code", auth_code))); HttpPost method = new HttpPost(apiURL); method.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); UrlEncodedFormEntity body = new UrlEncodedFormEntity(parameters, "UTF-8"); method.setEntity(body); try { HttpResponse response = client.execute(method); // Execute the HttpGet // A successful response is HTTP 200 OK // which will include a header named "Location" // Use the value of that header to allow your app // and retrieve the AuthCode. if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } } catch (Exception e) { System.out.println(e); } finally { method.releaseConnection(); } }
5de9e5b1-33d6-4864-bd9b-c2217d2c149a
public static void main(String[] args) { /************************************************************************************ * The following block of code only configures the log4j. This configuration displays * the full WIRE (headers + content) of the HTTP transaction. ***********************************************************************************/ Logger log = Logger.getLogger(AuthorizeApp.class.getName()); PropertyConfigurator.configure("log4j.properties"); /********************************************* * Credentials: * clientId = Consumer Key * clientSecret = Consumer Secret Key * callbackURL = Callback URL * apiURL = Endpoint URL for your request *********************************************/ String clientId = ""; String clientSecret = ""; String callbackURL = "http://www.smart.com.ph"; String apiURL = "https://x.smart.com.ph/oauth/authorize?response_type=code&client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=" + callbackURL+ "&scope=SMS+MMS"; //Initialize Apache's HttpClient through an HttpClientBuilder. HttpClient client = HttpClientBuilder.create().disableRedirectHandling().build(); //Note that my builder disables redirecting to the specified "Location" header of the response. //This is because I want to manually load that location to the browser. HttpGet method = new HttpGet(apiURL); try { HttpResponse response = client.execute(method); // Execute the HttpGet // A successful response is HTTP 302 Found // which will include a header named "Location" // Use the value of that header to allow your app // and retrieve the AuthCode. if (response.getStatusLine().getStatusCode() != 302) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); } }
25a69405-9413-42c1-a887-c637a40da973
public AlreadyRegisteredException(Identifier id) { super("Peer with ID " + id + " is already registered"); }
b94e6e7b-2bd8-45bc-bce7-8bf9152a48ba
public DataGenerator(int batchSize) { this.entries = new HashMap<String, String>(); this.pointer = 0; this.batchsize = batchSize; this.initialize(); }
746721af-de37-4546-a93b-38cc106eeb1f
private void initialize() { BufferedReader reader = null; String line; String[] members; try { reader = new BufferedReader(new FileReader(DATA_FILENAME)); while ((line = reader.readLine()) != null) { members = line.split(SEPARATOR); this.entries.put(members[0], members[1]); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } this.restaurants = Arrays.asList( this.entries.keySet().toArray(new String[0])); }
da0bcce9-c4e1-460c-ae0b-3dc4a8a347a2
public Map<String, String> getNewData() { Map<String, String> newData = new HashMap<String, String>(); int start = this.pointer; String restaurant; String dailySpecial; for (int i = 0 ; i < this.batchsize ; i++) { restaurant = this.restaurants.get((start + i) % this.entries.size()); dailySpecial = this.entries.get(restaurant); newData.put(restaurant, dailySpecial); } this.pointer = (start + this.batchsize) % this.entries.size(); return newData; }
7c55a949-614b-476d-b630-c0c08fe8dc9c
public static Tracker getTracker() { return tracker; }
7c53b861-bdd0-4ffb-9d1e-0b8361987c10
public static void main(String[] args) throws Exception { // A tracker is created new TrackerImpl(RMI_REGISTRY_PORT); Tracker tracker = (Tracker) Naming.lookup("rmi://localhost:" + RMI_REGISTRY_PORT + "/tracker"); // A Chord network is initialized createNetwork(tracker); // All the peers in the network are listed Thread.sleep((long) (Math.log(NB_PEERS) * 1000)); System.out.println("\nTurn around after first stabilization"); turnAround(tracker.getRandomPeer()); Thread.sleep((long) (Math.log(NB_PEERS) * 1000)); System.out.println("\nTurn around after second stabilization"); turnAround(tracker.getRandomPeer()); // A GuideMichelin is created. It will use the Chord network guideMichelin = new GuideMichelinImpl(tracker); // Some data are added to the {@link GuideMichelin} DataGenerator dataGenerator = new DataGenerator(10); Map<String, String> newData; for (int i = 0; i < 10; i++) { newData = dataGenerator.getNewData(); for (Entry<String, String> entry : newData.entrySet()) { guideMichelin.put(entry.getKey(), entry.getValue()); } } // The peers are listed again with the data they store Thread.sleep(2000); System.out.println("\nTurn around after adding data"); turnAround(tracker.getRandomPeer()); // Some data are requested from the GuideMichelin String[] restaurants = {"Le Bistrot Gourmand", "Auberge de la Madone", "toto"}; for (String restaurant : restaurants) { System.out.println("\nRestaurant '" + restaurant + "' - Daily special: '" + guideMichelin.get(restaurant) + "'"); } // Défini les réplicasts setReplicat(tracker.getRandomPeer()); // Met à jour les réplicats tracker.getRandomPeer().update(); System.out.println("Vérification des réplicats...OK"); // révérification des réplicats tracker.getRandomPeer().update(); /** * /!\ TEST /!\ * */ Recherche.testRecherche(tracker.getRandomPeer()); test.TestCoherance.test(tracker.getRandomPeer()); Mort.test(tracker.getRandomPeer()); }
be3620d3-8a4d-4e16-9443-ad8ffa17cf08
private static void createNetwork(Tracker tracker) throws RemoteException, AlreadyRegisteredException { for (int i = 0; i < NB_PEERS; i++) { Peer p = new PeerImpl(new Identifier(i * 100)); if (i == 0) { System.out.println("Ring created by " + p.getId()); p.create(); p.setTracker(tracker); } else { // The new peer is inserted in the network using a random peer // that already belongs to the network. This random peer is // retrieved thanks to the tracker. Peer randomPeer = tracker.getRandomPeer(); System.out.println("Added " + p.getId() + " from " + randomPeer.getId() + " that points to " + randomPeer.getSuccessor().getId()); p.setTracker(tracker); p.join(randomPeer); } tracker.register(p); } }
d9a2bb41-56b9-47be-85de-2f3b1abd80ed
private static void turnAround(Peer landmarkPeer) throws RemoteException { System.out.println( "\nStarted turn around from " + landmarkPeer.getId()); Peer nextPeer = landmarkPeer; do { nextPeer = nextPeer.getSuccessor(); System.out.println("Visited " + nextPeer.describe()); } while (!nextPeer.equals(landmarkPeer)); }
bab73d74-82f9-4814-bbbe-cdf3b88f6910
private static void setReplicat(Peer landmarkPeer) throws RemoteException { Peer nextPeer = landmarkPeer; do { nextPeer = nextPeer.getSuccessor(); nextPeer.saveReplicat(); } while ((!nextPeer.equals(landmarkPeer))); }
d2c782e4-8334-4358-8cae-7937056fd5a1
public static GuideMichelin getGuideMichelin() { return guideMichelin; }
08250992-d6d8-4bb4-b09e-663d21d32cdd
public GuideMichelinImpl(Tracker tracker) { this.tracker = tracker; }
9ca71cbc-9c0b-49c7-8543-2aba8b4412cb
@Override public void put(String restaurant, String dailySpecial) throws RemoteException { // Storing an entry in our peer-to-peer network simply consist in // asking the peer that is responsible for the restaurant key to store // the couple (restaurant, daily special) this.findIndexer(restaurant).put(restaurant, dailySpecial); }
aaeaaefa-30b2-4a74-9eff-77b5cc67606d
@Override public String get(String restaurant) throws RemoteException { // Getting a content in our peer-to-peer network simply consist in // asking the peer that is responsible for the restaurant key to return // its associated value return this.findIndexer(restaurant).get(restaurant); }
a18d361a-099e-433b-a9e8-a428e314f767
private final Peer findIndexer(String restaurant) throws RemoteException { return this.tracker.getRandomPeer().findSuccessor(new Key(restaurant)); }
81464e47-0391-415b-ab2c-11ceadab2c33
void put(String restaurant, String dailySpecial) throws RemoteException;
523f57ff-f087-4f93-8a56-2ab9f7bd8f2a
String get(String restaurant) throws RemoteException;
469127c1-b857-442f-ae57-67d34f7ca055
public Key(String value) { this(value.getBytes()); }
9acda904-5925-4259-b311-fdae26ccc11b
private Key(byte[] bytes) { super(toIntegerRestrictedToInterval(bytes, NB_BITS) * 100); }
de8848f8-5d17-4ed5-aa47-8b9cab25018e
private static int toIntegerRestrictedToInterval(byte[] bytes, int intervalSize) { return (new BigInteger(computeSHA1(bytes)).abs().intValue() % intervalSize + intervalSize) % intervalSize; }
6a8646ba-0a7b-4e28-b475-050438cc03cc
private static byte[] computeSHA1(byte[] bytes) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return md.digest(bytes); }
a303d92b-7a48-461e-89c8-fa08505583bb
void create() throws RemoteException;
d2b6a081-15d5-4a6d-8ad5-ec9678fd5e73
void join(Peer landmarkPeer) throws RemoteException;
cac5ee54-5602-4341-a902-ef8a10fcb224
Peer findSuccessor(Identifier id) throws RemoteException;
fac1b9c6-cbe7-4c5b-90c0-a08c80326f2c
Identifier getId() throws RemoteException;
daf59c09-7266-45df-ba0f-0efd20a52ae2
Peer getPredecessor() throws RemoteException;
fc79d660-59c9-4b08-8f40-f1cf51f95318
Peer getSuccessor() throws RemoteException;
9b3ca4bf-8946-4c29-8b35-e13ebc890dc1
void setPredecessor(Peer peer) throws RemoteException;
43efbe13-fd63-4b39-9069-0ec653b91a1f
void setSuccessor(Peer peer) throws RemoteException;
f3e147d6-9625-4fd3-bcbe-cd6213285615
void stabilize() throws RemoteException;
1ee8f550-34f5-497d-906d-6ac078efe30c
void notify(Peer peer) throws RemoteException;
f18021fd-178a-4ba8-91cb-6dbdf274851c
void put(String restaurant, String dailySpecial) throws RemoteException;
49d9aaef-0c94-4e64-8c47-6002c6df5881
String get(String restaurant) throws RemoteException;
49df3832-bfae-4b59-91d6-5698f6a090b9
String describe() throws RemoteException;
f7114dfc-1c10-4ee2-93fa-7363234da5a1
void die() throws RemoteException;
063ba807-c4b0-41e2-bec3-b724b1d027ae
public void setSuccessorofSuccessor(Peer peer) throws RemoteException;
da08556f-880f-44e0-bb23-7bcd3fbd9361
public Tracker getTracker() throws RemoteException;
1c2eeac0-357c-45d1-b956-b1bac66f4d5d
public void setTracker(Tracker tracker) throws RemoteException;
19a821c6-9e91-4b51-9e00-99c7492711bd
public String returnKey() throws RemoteException;
ad63caa5-6017-4f67-882a-54520c7bbd25
public String returnValue() throws RemoteException;
b359b2a0-be02-4123-ba1d-91c63634bf8a
public void saveReplicat() throws RemoteException;
fd03a622-3131-4acb-8d05-2604e80ca8f8
public void printReplicat() throws RemoteException;
81338c46-74c5-474e-bd30-8d2ce741222e
public void update() throws RemoteException;
0c65f433-e256-47c4-9789-9677dfecc4d1
public boolean chercheValeurKeyReplicat(String recherche) throws RemoteException;
846399fc-55fa-4568-99f0-4ce010f7f817
public Map<String, String> getDirectory() throws RemoteException;
3cb48b27-253b-44bd-b543-3b77b8e22b76
public void setDirectory(Map<String, String> directoryReplicat) throws RemoteException;