/ README.MD
README.MD
  1  # Welcome to SimpleServer Library!
  2  
  3  ![Maven Central](https://img.shields.io/maven-central/v/ru.zoommax/SimpleServer?style=plastic)
  4  ![GitHub](https://img.shields.io/github/license/ZooMMaX/SimpleServer?style=plastic)
  5  [![GitHub issues](https://img.shields.io/github/issues/ZooMMaX/SimpleServer?style=plastic)](https://github.com/ZooMMaX/SimpleServer/issues)
  6  
  7  SimpleServer is a lightweight Java library that allows for quick and easy usage of an embedded web server. It provides a seamless way to add and remove endpoints on the fly, while offering fast access to request bodies, headers, and parameters. With SimpleServer, you can effortlessly handle POST and GET requests and send responses.
  8  
  9  The goal of this library is to be simple and lightweight.
 10  
 11  It quickly integrates into solutions and does not depend on programming patterns.
 12  
 13  It's convenient!
 14  
 15  ## Key Features and Benefits
 16  
 17  - **Fast and Easy**: SimpleServer simplifies the process of writing small APIs by providing a lightweight solution.
 18  - **Flexible Endpoint Management**: Add or remove endpoints dynamically, allowing for easy customization of your server.
 19  - **Efficient Request Handling**: Access request bodies, headers, and parameters quickly and effortlessly.
 20  - **Convenient POST and GET Implementation**: SimpleServer offers interfaces for fast implementation of POST and GET requests.
 21  - **Returns Responses**: Get the desired responses from your server effortlessly.
 22  - **Annotation-based Implementation**: SimpleServer supports annotation-based implementation for easy and quick setup of endpoints.
 23  - **Documentation Generation**: SimpleServer can generate documentation for your endpoints in the MarkDown format.
 24  
 25  ## Usage
 26  
 27  To get started with SimpleServer, you need to explicitly start the server and then pass the endpoints to it.
 28  
 29  Here's an example of how to use SimpleServer (Deprecated):
 30  
 31  ```java
 32  // Import libraries
 33  
 34  import ru.zoommax.EndPoint;
 35  import ru.zoommax.GetHandler;
 36  import ru.zoommax.PostHandler;
 37  import ru.zoommax.SimpleServer;
 38  
 39  import java.util.HashMap;
 40  
 41  public class Test {
 42      public static void main(String[] args) {
 43          // Initialize the server by specifying the port it will listen on
 44          SimpleServer.init(8080);
 45  
 46          // Create an endpoint that handles GET requests
 47          // Here's an example of an endpoint that simply returns the request it received
 48          EndPoint test = EndPoint.builder().handler(new GetHandler() {
 49              @Override
 50              public String response(String request, HashMap<String, String> requestHeaders, HashMap<String, String> requestParams, String clientIp) {
 51                  // You can access request headers, request parameters, and client IP address here
 52                  // Customize the response based on the request if needed
 53                  return request;
 54              }
 55          }).endPointName("test").build();
 56  
 57          // Add the created endpoint to the server
 58          test.add();
 59  
 60          // Create another endpoint that handles POST requests
 61          // Here's an example of an endpoint that simply returns the request body it received
 62          EndPoint test2 = EndPoint.builder().handler(new PostHandler() {
 63              @Override
 64              public String response(String requestBody, HashMap<String, String> requestHeaders, String clientIp) {
 65                  // You can access request headers, request body, and client IP address here
 66                  // Customize the response based on the request if needed
 67                  return requestBody;
 68              }
 69          }).endPointName("test2").build();
 70  
 71          // Add the second endpoint to the server
 72          test2.add();
 73      }
 74  }
 75  // Additionally, you can pass an HttpHandler to the endpoint builder. GetHandler and PostHandler inherit from HttpHandler.
 76  ```
 77  
 78  Here's an example of how to use SimpleServer (New):
 79  
 80  Annotation-based implementation
 81  
 82  ```java
 83  //Import libraries
 84  import ru.zoommax.SimpleServer;
 85  import ru.zoommax.next.Request;
 86  import ru.zoommax.next.Response;
 87  import ru.zoommax.next.annotation.Endpoint;
 88  import ru.zoommax.next.annotation.InitWebServer;
 89  import ru.zoommax.next.enums.HttpMethod;
 90  
 91  public class AnnotatedStart {
 92      //Initialization of server with port 12345 and 4 threads using annotation InitWebServer
 93      @InitWebServer(port = 12345, threads = 4)
 94      public static void main(String[] args) {
 95          //Start server using SimpleServer.start()
 96          SimpleServer.start();
 97      }
 98  
 99      //Add endpoint using annotation Endpoint
100      @Endpoint(path = "/test", httpMethod = HttpMethod.GET, statusCode = 200, filterContentLength = -1)
101      public Response test(Request request) {
102          //Endpoint logic
103          String body = request.getBodyAsString();
104          //...
105  
106          //Return response
107          return Response.builder()
108                  .bodyAsString(body)
109                  .statusCode(200)
110                  .build();
111      }
112  }
113  ```
114  
115  Annotation-based implementation with extends
116  
117  ```java
118  import ru.zoommax.SimpleServer;
119  import ru.zoommax.next.Request;
120  import ru.zoommax.next.Response;
121  import ru.zoommax.next.annotation.Endpoint;
122  import ru.zoommax.next.annotation.InitWebServer;
123  import ru.zoommax.next.enums.HttpMethod;
124  
125  @InitWebServer(port = 12345, threads = 4)
126  public class AnnotatedStartWithExtends extends SimpleServer {
127      public static void main(String[] args) {
128  
129      }
130  
131      @Endpoint(path = "/test", httpMethod = HttpMethod.GET, statusCode = 200, filterContentLength = -1)
132      public Response test(Request request) {
133          return Response.builder()
134                  .bodyAsString(request.getBodyAsString())
135                  .statusCode(200)
136                  .build();
137      }
138  }
139  ```
140  
141  Not-annotation-based implementation
142  
143  ```java
144  import ru.zoommax.SimpleServer;
145  import ru.zoommax.next.Response;
146  import ru.zoommax.next.handlers.GetHandlerNew;
147  
148  import java.util.HashMap;
149  
150  public class NotAnnotatedStart {
151      //Initialization of server with port 12345 and 4 threads and start it
152      public static void main(String[] args) {
153          SimpleServer.start(12345, 4);
154          test();
155      }
156  
157      //Add endpoint using SimpleServer.addEndpoint()
158      public static void test() {
159          SimpleServer.addEndpoint("/test", new GetHandlerNew() {
160              @Override
161              public Response response(String request, HashMap<String, String> requestHeaders, HashMap<String, String> requestParams, String clientIp) {
162                  //Endpoint logic
163                  String body = request;
164                  //...
165                  return Response.builder()
166                          .bodyAsString(body)
167                          .statusCode(200)
168                          .build();
169              }
170          });
171      }
172  }
173  ```
174  
175  # Generated documentation for the endpoint
176  
177  The documentation is generated in the MarkDown format. All documentation is described in the form of annotations. The title page of the documentation is available at `http(s)://localhost:port/docs`.
178  
179  Example of generated documentation for the endpoint:
180  
181  ```java
182  @InitWebServer(port = 25565, titleHomePage = "Documentation for WalletAPI",
183          descriptionHomePage = "This is a documentation of WalletAPI. You can see all available endpoints and their descriptions.")
184  @CreateDocumentation(value = true)
185  public class API extends SimpleServer {
186      private static CryptoWallet wallet;
187      private static final Logger logger = LoggerFactory.getLogger(API.class);
188  
189      public void start(CryptoWallet wallet) {
190          API.wallet = wallet;
191          SimpleServer.start();
192      }
193  
194      @Endpoint(path = "/api/v1/createInvoice", httpMethod = HttpMethod.GET)
195      @ApiVersion("1.0")
196      @PropertyDoc(name = {"newAddress", "amount", "address"},
197              description = {"Create new address", "Amount", "Address (required if newAddress is false)"},
198              type = {"Boolean", "Double", "String"},
199              required = {true, true, false})
200      @RequestDoc("Create invoice")
201      @ResponseDoc(code = {200}, description = "Invoice created. Returns json with invoice info\n" +
202              "\n" +
203              "Example: \n" +
204              "```json\n" +
205              "{\n" +
206              "   \"UID\": \"123e4567-e89b-12d3-a456-426614174000-1622542800000\",\n" +
207              "   \"address\": \"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa\",\n" +
208              "   \"amount\": 0.01,\n" +
209              "   \"createDate\": 1622542800000,\n" +
210              "   \"expirationDate\": 1622546400000,\n" +
211              "   \"paidDate\": 0,\n" +
212              "   \"status\": \"WAITING\"\n" +
213              "}\n" +
214              "```\n" +
215              "UID - Unique ID of invoice\n" +
216              "\n" +
217              "address - Address to send payment\n" +
218              "\n" +
219              "amount - Amount of invoice\n" +
220              "\n" +
221              "createDate - Date of creation\n" +
222              "\n" +
223              "expirationDate - Date of expiration\n" +
224              "\n" +
225              "paidDate - Date of payment\n" +
226              "\n" +
227              "status - Status of invoice\n" +
228              "\n" +
229              "Statuses: WAITING, PAID, EXPIRED, NULL")
230      public static Response createInvoice(Request request) {
231          logger.debug(request.getParams() + "");
232          InvoicePojo invoicePojo = new InvoicePojo();
233          String body = "";
234          boolean newAddress = request.getParams().get("newAddress") != null && request.getParams().get("newAddress").equals("true");
235          logger.debug("New address: " + newAddress);
236          String address = "";
237          if (newAddress) {
238              address = wallet.getReceiveAddress();
239          } else {
240              address = request.getParams().get("address");
241          }
242          logger.debug("Address: " + address);
243          double amount = request.getParams().get("amount") != null ? Double.parseDouble(request.getParams().get("amount")) : 0;
244          logger.debug("Amount: " + amount);
245          if (amount > 0) {
246              invoicePojo.setUid(UUID.randomUUID() + "-" + System.currentTimeMillis());
247              invoicePojo.setAmount(amount);
248              invoicePojo.setAddress(address);
249              invoicePojo.setCreateDate(System.currentTimeMillis());
250              invoicePojo.setExpirationDate(System.currentTimeMillis() + 3600000);
251              invoicePojo.setStatus(InvoiceStatus.WAITING);
252              if (invoicePojo.insert()) {
253                  ObjectMapper objectMapper = new ObjectMapper();
254                  try {
255                      body = objectMapper.writeValueAsString(invoicePojo);
256                  } catch (Exception e) {
257                      logger.error("Error creating payment", e);
258                  }
259              }
260          }
261          return Response.builder()
262                  .bodyAsString(body)
263                  .statusCode(200)
264                  .build();
265      }
266  }
267  ```
268  
269  ### MD result Example:
270  
271  ---
272  
273  [Back to home](/docs)
274  
275  /api/v1/createInvoice
276  =====================
277  
278  Method: `GET`
279  -------------
280  
281  ### Properties
282  
283  | Name         | Type      | Description                               | Required |
284  | ------------ | --------- | ----------------------------------------- | -------- |
285  | `newAddress` | `Boolean` | Create new address                        | `true`   |
286  | `amount`     | `Double`  | Amount                                    | `true`   |
287  | `address`    | `String`  | Address (required if newAddress is false) | `false`  |
288  
289  ### Request
290  
291  Create invoice
292  
293  ### Response
294  
295  `200`
296  
297  Invoice created. Returns json with invoice info
298  
299  Example:
300  ```json
301  {
302     "UID": "123e4567-e89b-12d3-a456-426614174000-1622542800000",
303     "address": "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
304     "amount": 0.01,
305     "createDate": 1622542800000,
306     "expirationDate": 1622546400000,
307     "paidDate": 0,
308     "status": "WAITING"
309  }
310  ```
311  UID - Unique ID of invoice
312  
313  address - Address to send payment
314  
315  amount - Amount of invoice
316  
317  createDate - Date of creation
318  
319  expirationDate - Date of expiration
320  
321  paidDate - Date of payment
322  
323  status - Status of invoice
324  
325  Statuses: WAITING, PAID, EXPIRED, NULL
326  
327  
328  ---
329  
330  ## Dependency
331  
332  ![dependency maven](https://img.shields.io/badge/DEPENDENCY-Maven-C71A36?style=plastic&logo=apachemaven)
333  ```xml
334  <dependencies>
335      <dependency>
336          <groupId>ru.zoommax</groupId>
337          <artifactId>SimpleServer</artifactId>
338          <version>1.9.5</version>
339      </dependency>
340  </dependencies>
341  ```
342  
343  ![dependency gradle](https://img.shields.io/badge/DEPENDENCY-Gradle-02303A?style=plastic&logo=gradle)
344  ```groovy
345  implementation 'ru.zoommax:SimpleServer:1.9.5'
346  ```
347  
348  That's it! You're now ready to build your small APIs using SimpleServer.
349  
350  Please note that this is just a basic example, and you can explore more advanced features and configurations in the SimpleServer documentation.
351  
352  I'am hope you find SimpleServer helpful for your web server needs. If you have any questions or need further assistance, please don't hesitate to open issue.
353  
354  Happy coding!