Commit cdeb7efb authored by Vladislav Savchenkov's avatar Vladislav Savchenkov

Create HTTP Server

parent 3181c979
{ {
"db.url": "~", "db.url": "~",
"db.username": "~", "db.username": "~",
"db.password": "~" "db.password": "~",
"server.port": 8080
} }
\ No newline at end of file
<div>
<h2>ID: %s</h2>
<h2>Name: %s</h2>
<h2>Type: %s</h2>
<h2 style="text-decoration: underline">Color:
<span style="color: %s">%s</span>
</h2>
<h2>Volume: %s</h2>
<div>
<br>
\ No newline at end of file
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>cars</title>
</head>
<body>
%s
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
body {font-family: "Times New Roman", Georgia, Serif;}
h1, h2, h3, h4, h5, h6 {
font-family: "Playfair Display";
letter-spacing: 5px;
}
</style>
</head>
<body>
<!-- Navbar (sit on top) -->
<div class="w3-top">
<div class="w3-bar w3-white w3-padding w3-card" style="letter-spacing:4px;">
<a href="#home" class="w3-bar-item w3-button">Gourmet au Catering</a>
<!-- Right-sided navbar links. Hide them on small screens -->
<div class="w3-right w3-hide-small">
<a href="#about" class="w3-bar-item w3-button">About</a>
<a href="#menu" class="w3-bar-item w3-button">Menu</a>
<a href="#contact" class="w3-bar-item w3-button">Contact</a>
</div>
</div>
</div>
<!-- Header -->
<header class="w3-display-container w3-content w3-wide" style="max-width:1600px;min-width:500px" id="home">
<img class="w3-image" src="https://www.w3schools.com/w3images/hamburger.jpg" alt="Hamburger Catering" width="1600" height="800">
<div class="w3-display-bottomleft w3-padding-large w3-opacity">
<h1 class="w3-xxlarge">Le Catering</h1>
</div>
</header>
<!-- Page content -->
<div class="w3-content" style="max-width:1100px">
<!-- About Section -->
<div class="w3-row w3-padding-64" id="about">
<div class="w3-col m6 w3-padding-large w3-hide-small">
<img src="https://www.w3schools.com/w3images/tablesetting2.jpg" class="w3-round w3-image w3-opacity-min" alt="Table Setting" width="600" height="750">
</div>
<div class="w3-col m6 w3-padding-large">
<h1 class="w3-center">About Catering</h1><br>
<h5 class="w3-center">Tradition since 1889</h5>
<p class="w3-large">The Catering was founded in blabla by Mr. Smith in lorem ipsum dolor sit amet, consectetur adipiscing elit consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute iruredolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.We only use <span class="w3-tag w3-light-grey">seasonal</span> ingredients.</p>
<p class="w3-large w3-text-grey w3-hide-medium">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod temporincididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
<hr>
<!-- Menu Section -->
<div class="w3-row w3-padding-64" id="menu">
<div class="w3-col l6 w3-padding-large">
<h1 class="w3-center">Our Menu</h1><br>
<h4>Bread Basket</h4>
<p class="w3-text-grey">Assortment of fresh baked fruit breads and muffins 5.50</p><br>
<h4>Honey Almond Granola with Fruits</h4>
<p class="w3-text-grey">Natural cereal of honey toasted oats, raisins, almonds and dates 7.00</p><br>
<h4>Belgian Waffle</h4>
<p class="w3-text-grey">Vanilla flavored batter with malted flour 7.50</p><br>
<h4>Scrambled eggs</h4>
<p class="w3-text-grey">Scrambled eggs, roasted red pepper and garlic, with green onions 7.50</p><br>
<h4>Blueberry Pancakes</h4>
<p class="w3-text-grey">With syrup, butter and lots of berries 8.50</p>
</div>
<div class="w3-col l6 w3-padding-large">
<img src="https://www.w3schools.com/w3images/tablesetting.jpg" class="w3-round w3-image w3-opacity-min" alt="Menu" style="width:100%">
</div>
</div>
<hr>
<!-- Contact Section -->
<div class="w3-container w3-padding-64" id="contact">
<h1>Contact</h1><br>
<p>We offer full-service catering for any event, large or small. We understand your needs and we will cater the food to satisfy the biggerst criteria of them all, both look and taste. Do not hesitate to contact us.</p>
<p class="w3-text-blue-grey w3-large"><b>Catering Service, 42nd Living St, 43043 New York, NY</b></p>
<p>You can also contact us by phone 00553123-2323 or email catering@catering.com, or you can send us a message here:</p>
<form action="/action_page.php" target="_blank">
<p><input class="w3-input w3-padding-16" type="text" placeholder="Name" required name="Name"></p>
<p><input class="w3-input w3-padding-16" type="number" placeholder="How many people" required name="People"></p>
<p><input class="w3-input w3-padding-16" type="datetime-local" placeholder="Date and time" required name="date" value="2020-11-16T20:00"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Message \ Special requirements" required name="Message"></p>
<p><button class="w3-button w3-light-grey w3-section" type="submit">SEND MESSAGE</button></p>
</form>
</div>
<!-- End page content -->
</div>
<!-- Footer -->
<footer class="w3-center w3-light-grey w3-padding-32">
<p>Powered by <a href="https://www.w3schools.com/w3css/default.asp" title="W3.CSS" target="_blank" class="w3-hover-text-green">w3.css</a></p>
</footer>
</body>
</html>
...@@ -3,6 +3,7 @@ import core.utils.logs.Logger; ...@@ -3,6 +3,7 @@ import core.utils.logs.Logger;
import java.sql.SQLException; import java.sql.SQLException;
public class Main public class Main
{ {
public static void main(String[] args) public static void main(String[] args)
...@@ -10,12 +11,12 @@ public class Main ...@@ -10,12 +11,12 @@ public class Main
try try
{ {
Application application = new Application(); Application application = new Application();
application.run(); application.start();
} }
catch (SQLException exception) catch (Exception exception)
{ {
Logger.error("DB problem: " + exception.getMessage()); Logger.error("Problem: " + exception.getMessage());
System.exit(exception.getErrorCode()); System.exit(101);
} }
} }
} }
\ No newline at end of file
package core; package core;
import core.configuration.ConfigurationMap;
import core.server.Server;
import core.utils.io.ConfigurationReader;
import core.db.repositories.CarRepository; import java.io.IOException;
import core.db.repositories.Repository;
import core.models.Car;
import java.sql.SQLException;
import java.util.List;
public class Application public class Application
{ {
private final Repository<Car> repository; private final Server server;
public Application() throws SQLException public Application() throws IOException
{ {
this.repository = new CarRepository(); ConfigurationMap configuration = ConfigurationReader.get();
int port = configuration.getPort();
this.server = new Server(port);
} }
public void run() throws SQLException public void start()
{ {
List<Car> cars = repository.get(); this.server.start();
System.out.println("\nCars from DB:");
cars.forEach(System.out::println);
Car car = repository.get(1);
System.out.println("\nCar from DB by ID(1):");
System.out.println(car);
} }
} }
...@@ -13,11 +13,15 @@ public class ConfigurationMap ...@@ -13,11 +13,15 @@ public class ConfigurationMap
@SerializedName("db.password") @SerializedName("db.password")
private final String password; private final String password;
public ConfigurationMap(String url, String username, String password) @SerializedName("server.port")
private final int port;
public ConfigurationMap(String url, String username, String password, int port)
{ {
this.url = url; this.url = url;
this.username = username; this.username = username;
this.password = password; this.password = password;
this.port = port;
} }
public String getUrl() public String getUrl()
...@@ -34,4 +38,9 @@ public class ConfigurationMap ...@@ -34,4 +38,9 @@ public class ConfigurationMap
{ {
return password; return password;
} }
public int getPort()
{
return port;
}
} }
...@@ -15,6 +15,17 @@ public class CarRepository extends Repository<Car> ...@@ -15,6 +15,17 @@ public class CarRepository extends Repository<Car>
super(); super();
} }
@Override
public void save(Car car) throws SQLException
{
Statement statement = getStatement();
String query = "INSERT INTO db.cars (name, type, color, volume) VALUES ('%s', '%s', '%s', '%s');";
query = query.formatted(car.getName(), car.getType(), car.getColor(), car.getVolume());
statement.executeUpdate(query);
}
@Override @Override
public Car get(int id) throws SQLException public Car get(int id) throws SQLException
{ {
......
...@@ -15,6 +15,8 @@ public abstract class Repository<T> ...@@ -15,6 +15,8 @@ public abstract class Repository<T>
this.connection = new DBConnection(ConfigurationReader.get()).getInstance(); this.connection = new DBConnection(ConfigurationReader.get()).getInstance();
} }
public abstract void save(T tEntity) throws SQLException;
public abstract T get(int id) throws SQLException; public abstract T get(int id) throws SQLException;
public abstract List<T> get() throws SQLException; public abstract List<T> get() throws SQLException;
......
...@@ -21,6 +21,31 @@ public class Car ...@@ -21,6 +21,31 @@ public class Car
this.volume = volume; this.volume = volume;
} }
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public String getType()
{
return type;
}
public float getVolume()
{
return volume;
}
public String getColor()
{
return color;
}
@Override @Override
public String toString() public String toString()
{ {
......
package core.processor;
import com.sun.net.httpserver.HttpExchange;
import core.utils.io.TemplateReader;
import core.utils.logs.Logger;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
public abstract class Processor
{
protected final TemplateReader reader = new TemplateReader();
public abstract void process(HttpExchange exchange) throws IOException, SQLException;
protected void process(HttpExchange exchange, String response)
{
try(PrintWriter writer = writer(exchange))
{
Logger.info(exchange);
exchange.getResponseHeaders().add("Content-Type", "text/html; charset=utf-8");
exchange.sendResponseHeaders(200, response.length());
writer.write(response);
writer.flush();
}
catch (IOException exception)
{
Logger.error(exception.getMessage());
}
}
private PrintWriter writer(HttpExchange exchange)
{
OutputStream stream = exchange.getResponseBody();
Charset charset = StandardCharsets.UTF_8;
return new PrintWriter(stream, false, charset);
}
}
package core.processor.impl;
import com.sun.net.httpserver.HttpExchange;
import core.db.repositories.CarRepository;
import core.models.Car;
import core.processor.Processor;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
public class CarsProcessor extends Processor
{
private final CarRepository repository;
public CarsProcessor() throws SQLException
{
this.repository = new CarRepository();
}
@Override
public void process(HttpExchange exchange) throws SQLException, IOException
{
String template = reader.read("cars");
String partial = reader.read("car");
StringBuilder builder = new StringBuilder();
List<Car> cars = repository.get();
for (Car car : cars)
{
builder.append(partial.formatted
(
car.getId(),
car.getName(),
car.getType(),
car.getColor(),
car.getColor(),
car.getVolume()
));
}
process(exchange, template.formatted(builder.toString()));
}
}
package core.processor.impl;
import com.sun.net.httpserver.HttpExchange;
import core.processor.Processor;
import java.io.IOException;
public class RootProcessor extends Processor
{
@Override
public void process(HttpExchange exchange) throws IOException
{
String response = reader.read("root");
process(exchange, response);
}
}
package core.server;
/*
CONTROLLER, VIEW, MODEL
CONTROLLER - получить запрос, передать данные из запроса дальше.
SERVICE - получить данные и подготовить их.
REPOSITORY - получить данные из БД.
MODEL - это то, как выглядит таблица из БД в Java.
*/
import com.sun.net.httpserver.HttpServer;
import core.processor.impl.CarsProcessor;
import core.processor.impl.RootProcessor;
import core.utils.logs.Logger;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.sql.SQLException;
public class Server
{
private final int port;
private final HttpServer server;
public Server(int port) throws IOException
{
this.port = port;
this.server = create(port);
}
public void start()
{
this.server.start();
register();
Logger.info("Server started on: http://localhost:" + port);
}
private void register()
{
server.createContext("/", exchange -> new RootProcessor().process(exchange));
server.createContext("/cars", exchange ->
{
try
{
new CarsProcessor().process(exchange);
}
catch (SQLException exception)
{
Logger.error(exception.getMessage());
}
});
}
private HttpServer create(int port) throws IOException
{
HttpServer server = this.server;
if (server == null)
{
synchronized (HttpServer.class)
{
InetSocketAddress socket = new InetSocketAddress("localhost", port);
server = HttpServer.create(socket, port);
}
}
return server;
}
}
package core.utils.io;
import java.io.IOException;
public class TemplateReader
{
private final IOFileReader reader = new IOFileReader();
public String read(String file) throws IOException
{
return reader.read("resources/templates/" + file + ".html");
}
}
package core.utils.logs; package core.utils.logs;
import com.sun.net.httpserver.HttpExchange;
import core.utils.io.IOFileWriter; import core.utils.io.IOFileWriter;
import java.time.LocalDateTime; import java.time.LocalDateTime;
...@@ -11,11 +12,28 @@ public class Logger ...@@ -11,11 +12,28 @@ public class Logger
public static void info(String message) public static void info(String message)
{ {
writer.append(PATH, "INFO - " + LocalDateTime.now() + " - " + message); message = "| INFO - " + LocalDateTime.now() + " - " + message;
System.out.println(message);
writer.append(PATH, message);
} }
public static void error(String message) public static void error(String message)
{ {
writer.append(PATH, "ERROR - " + LocalDateTime.now() + " - " + message); message = "| ERROR - " + LocalDateTime.now() + " - " + message;
System.out.println(message);
writer.append(PATH, message);
}
public static void info(HttpExchange exchange)
{
String message = "%s %s %s".formatted
(
exchange.getRequestURI(),
exchange.getRemoteAddress(),
exchange.getRequestMethod()
);
info(message);
} }
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment