Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions 3 Seminar7/code/Server/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions 6 Seminar7/code/Server/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions 8 Seminar7/code/Server/.idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions 6 Seminar7/code/Server/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
34 changes: 34 additions & 0 deletions 34 Seminar7/code/Server/src/ClientResolver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientResolver implements Runnable {
private Socket clientSocket;
private Store store;

public ClientResolver(Socket socket, Store store)
{
this.clientSocket = socket;
this.store = store;
}

public void run()
{
Scanner in = null;
PrintStream out = null;
try {
in = new Scanner(clientSocket.getInputStream());
out = new PrintStream(clientSocket.getOutputStream());
StreamCommunicator communicator = new StreamCommunicator(in, out);

var server = new ServerHandler(communicator, this.store);
server.startCommunication();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Connection closed.");
} finally {
in.close();
out.close();
}
}
}
76 changes: 76 additions & 0 deletions 76 Seminar7/code/Server/src/Computer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import java.time.LocalDate;

public class Computer {
private int id;
private String brand;
private String model;
private boolean isUsed;
private LocalDate manufacturedDate;
private int quantity;

public Computer() { }

public Computer(String brand, String model, boolean isUsed, LocalDate manufacturedDate, int quantity) {
this.setBrand(brand);
this.setModel(model);
this.setUsed(isUsed);
this.setManufacturedDate(manufacturedDate);
this.setQuantity(quantity);
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}

public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}

public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}

public boolean isUsed() {
return isUsed;
}
public void setUsed(boolean used) {
isUsed = used;
}

public LocalDate getManufacturedDate() {
return manufacturedDate;
}
public void setManufacturedDate(LocalDate manufacturedDate) {
this.manufacturedDate = manufacturedDate;
}

public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Computer: #").append(this.getId()).append("\t")
.append(this.getBrand()).append(" ").append(this.getModel()).append("\t")
.append("Year of manufacturing: ").append(this.getManufacturedDate().toString()).append("\t")
.append("Quantity: ").append(this.getQuantity()).append("\t");
if(this.isUsed()) {
sb.append("Computer is used").append("\t");
}

return sb.toString();
}
}
14 changes: 14 additions & 0 deletions 14 Seminar7/code/Server/src/ComputerBuilder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import java.time.LocalDate;

public class ComputerBuilder {
public static Computer build(StreamCommunicator communicator) {
Computer computer = new Computer();
computer.setBrand(communicator.communicateMessage("Enter brand:"));
computer.setModel(communicator.communicateMessage("Enter model:"));
computer.setManufacturedDate(LocalDate.parse(
communicator.communicateMessage("Enter date (in format: yyyy-mm-dd):")));
computer.setUsed(Boolean.parseBoolean(communicator.communicateMessage("Is used:")));
computer.setQuantity(Integer.parseInt(communicator.communicateMessage("Quantity:")));
return computer;
}
}
29 changes: 29 additions & 0 deletions 29 Seminar7/code/Server/src/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class Main {
private static final int SOCKET_PORT = 5038; //Any random free port

public static void main(String[] args) {
ServerSocket server = null;
Store store = StoreSeeder.getSeededStore();

try {
server = new ServerSocket(SOCKET_PORT);

while (true) {
Socket client = server.accept();
System.out.println("Connection established: " + client.getInetAddress().getHostAddress());

ClientResolver resolver = new ClientResolver(client, store);
new Thread(resolver).start();
}
} catch (SocketException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
45 changes: 45 additions & 0 deletions 45 Seminar7/code/Server/src/ServerHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import java.io.PrintStream;
import java.util.Scanner;

public class ServerHandler {
private StreamCommunicator communicator;
private Store store;

public ServerHandler(StreamCommunicator communicator, Store store) {
this.communicator = communicator;
this.store = store;
}

public void startCommunication() {
int choice = Integer.parseInt(communicator.communicateMessage("Write 1 for administrator and 2 for client"));
switch(choice) {
case 1:
this.communicateAdmin();
break;
case 2:
this.communicateCustomer();
break;
default:
communicator.communicateMessage("Not an option");
}
}

private void communicateAdmin() {
communicator.addMessage("Entering a new computer details.");
Computer computer = ComputerBuilder.build(communicator);
this.store.addComputer(computer);
}

private void communicateCustomer() {
communicator.communicateMessage("Buying a computer.",
this.store.getAvailableComputers(),
"Which computer would you like to buy");
int computerId = Integer.parseInt(communicator.communicateMessage());
int quantity = Integer.parseInt(communicator.communicateMessage("How many?"));
try {
store.sellComputers(computerId, quantity);
} catch (Exception ex) {
communicator.communicateMessage(ex.getMessage());
}
}
}
43 changes: 43 additions & 0 deletions 43 Seminar7/code/Server/src/Store.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import java.util.*;

public class Store {
private List<Computer> availableComputers = Collections.synchronizedList(new ArrayList<>());

public void addComputer(Computer computer) {
computer.setId(this.availableComputers.size());
this.availableComputers.add(computer);
}

public String getAvailableComputers() {
StringBuffer sb = new StringBuffer();
for (var computer : this.availableComputers) {
sb.append(computer);
}

return sb.toString();
}

public void sellComputers(int computerId, int desiredQuantity) {
synchronized (this.availableComputers) {
var computerInStock = this.availableComputers.stream()
.filter(c -> c.getId() == computerId).findFirst();

if (computerInStock.isEmpty()) {
throw new IllegalArgumentException("Computer with id " + computerId + " doesn't exist.");
}

Computer computer = computerInStock.get();
int newQuantity = computer.getQuantity() - desiredQuantity;
if (newQuantity < 0) {
throw new IllegalArgumentException("There are only " + computer.getQuantity() + " computers left."
+ " We cannot sell you " + desiredQuantity);
}

if(newQuantity == 0) {
this.availableComputers.remove(computer);
} else {
computer.setQuantity(newQuantity);
}
}
}
}
17 changes: 17 additions & 0 deletions 17 Seminar7/code/Server/src/StoreSeeder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import java.time.LocalDate;

public class StoreSeeder {
public static Store getSeededStore() {
Store store = new Store();
populate(store);
return store;
}

private static void populate(Store store) {
store.addComputer(new Computer("Lenovo", "T15", false, LocalDate.now(), 5));
store.addComputer(new Computer("Asus", "Zenbook",
true, LocalDate.of(2020, 10, 1), 2));
store.addComputer(new Computer("Apple", "Macbook Pro",
false, LocalDate.of(2021, 10, 31), 30));
}
}
32 changes: 32 additions & 0 deletions 32 Seminar7/code/Server/src/StreamCommunicator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import java.io.PrintStream;
import java.lang.invoke.StringConcatException;
import java.util.*;

public class StreamCommunicator {
private Scanner in;
private PrintStream out;
private List<String> messages;

public StreamCommunicator(Scanner in, PrintStream out) {
this.in = in;
this.out = out;
this.messages = new ArrayList<>();
}

public void addMessage(String message) {
this.messages.add(message);
}

public String communicateMessage() {
var result = this.communicateMessage(this.messages.toArray(String[]::new));
this.messages.clear();
return result;
}

public String communicateMessage(String ...messsages) {
String messageToSend = Arrays.stream(messsages).reduce("",
(String total, String current) -> total + current);
out.println(messageToSend);
return in.nextLine();
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.