Skip to content
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
45 changes: 45 additions & 0 deletions 2-0-servlet-api/2-0-1-date-servlet-api/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# <img src="https://raw.githubusercontent.com/bobocode-projects/resources/master/image/logo_transparent_background.png" height=50/>Welcome Date Servlet
Your first acquaintance with Servlets, JSP and servlet Container 👀

[Servlets are the Java platform technology of choice for extending and enhancing Web servers.](https://www.oracle.com/java/technologies/servlet-technology.html)

### Pre-conditions ❗
You're supposed to be familiar with [Java Fundamentals](https://github.com/bobocode-projects/java-fundamentals-course)

### Objectives
* **install** [Apache Tomcat Container](https://tomcat.apache.org/download-90.cgi) if you didn't ✅

-*Servlets don’t have any main() method. Instead, are used Containers to control Servlets.
Containers are other Java applications such as Tomcat, GlassFish or Jetty. You have to install one of it if you didn't.
We suggest to use Tomcat as more lightweight and easier in configuration.*
* ⚙ **configure a Container** depending on your environment ✅
- [IntelliJ IDEA:](https://www.jetbrains.com/help/idea/run-debug-configuration-tomcat-server.html)
1. Create a new server configuration:

**Run** ▶ **Edit configurations...** ▶ (➕)Add New Configuration ▶ Tomcat Server (Local)
2. Configure or choose Application Server in **Run/Debug Configurations**:

**Server** tab ▶ **Configure** ▶ (➕)**Add Application Server** ▶ Add a path to folder with Tomcat
3. Deploy welcome-servlet application into Container in **Run/Debug Configurations**:

**Deployment** tab ▶ (➕)Artifact ▶ `welcome-servlet:war exploded` ▶ ❗ Clear **Application Context** field

- Eclipse
- Open Eclipse Java EE (Enterprise edition ) environment. Click on Servers tab at bottom. Click on No servers are available.
- A dialog box will appear. Select Tomcat 9.0 server folder. Click Next.
- Browse to Apache Tomcat 9.0 folder select it. Click Finish.
* **create a new Servlet** with a name `DateServlet` ✅
1. Create a new class `DateServlet` in the same package
2. Extend the class from `HttpServlet`
3. Annotate the class as `@WebServlet` with parameter `"/date""` to create a path to the servlet.
4. Override `doGet` method to return present date in the response using `LocalDate.now()`.
* **run `DateServletTest`** to check your code ✅
* **run configured server** ✅
- If everything is configured properly, the server should run `WelcomeServlet` on [http://localhost:8080/](http://localhost:8080/)
* **send request to `DateServlet`** using [http://localhost:8080/date](http://localhost:8080/date) URL in order to get present date ✅

### Related Materials ℹ️
todo

---
#### 🆕 First time here? – [See Introduction](https://github.com/bobocode-projects/java-fundamentals-course/tree/main/0-0-intro#introduction)
46 changes: 46 additions & 0 deletions 2-0-servlet-api/2-0-1-date-servlet-api/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>2-0-servlet-api</artifactId>
<groupId>com.bobocode</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>2-0-1-date-servlet-api</artifactId>
<packaging>war</packaging>

<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.0</version>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.bobocode.servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* To create a servlet you have to extend your class from {@link HttpServlet}.
* Also add annotation {@link WebServlet} with parameter to map a path for URL.
*/
@WebServlet("/")
public class WelcomeServlet extends HttpServlet {

/**
* This method is overridden from {@link HttpServlet} class.
* It called by the server (container) to allow servlets to handle GET requests.
*
* @param request an {@link HttpServletRequest} object that contains the request
* the client has made of the servlet.
* @param response an {@link HttpServletResponse} object that contains the response
* the servlet sends to the client.
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body align=\"center\">");
out.println("<img src=\"https://raw.githubusercontent.com/bobocode-projects/resources/2a3cf642ed8e5d2cc48c6d0dd9dfcdf220cb377c/image/logo_white.svg\" " +
"alt=\"Bobocode\" width=\"500\">");
out.println("<h1>" + "Good job! This page is a response of <code>WelcomeServlet</code> object." + "</h1>");
out.println("<h2>" + "You should create your own class <code>DateServlet</code> which returns " +
"current date as a response on <code>/date</code> path.<br> Use <code>LocalDate.now()</code> " +
"to get current date." + "</h2>");
out.println("</body></html>");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.bobocode;

import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.reflections.Reflections;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.Optional;
import java.util.Set;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;


@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ExtendWith(MockitoExtension.class)
public class DateServletTest {

@Mock
private HttpServletRequest request;

@Mock
private HttpServletResponse response;

@Mock
private ServletOutputStream outputStream;

private Object dateServletObject;
private Class<?> dateServletClass;

public static final String SERVLET_PACKAGE = "com.bobocode.servlet";
public static final String DATE_SERVLET = "DateServlet";
Reflections reflections;

@BeforeEach
public void init() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException,
InstantiationException {
reflections = new Reflections(SERVLET_PACKAGE);
dateServletClass = Class.forName(SERVLET_PACKAGE + "." + DATE_SERVLET);
dateServletObject = dateServletClass.getConstructors()[0].newInstance();
}

@Test
@Order(1)
void dateServletClassExists() throws ClassNotFoundException {
Class.forName(SERVLET_PACKAGE + "." + DATE_SERVLET);
}

@Test
@Order(2)
void dateServletExtendsHttpServlet() {

Set<Class<? extends HttpServlet>> httpServlets =
reflections.getSubTypesOf(HttpServlet.class);

Optional<String> anyDateHttpServlet = httpServlets.stream()
.map(Class::getSimpleName)
.filter(servlet -> servlet.equals(DATE_SERVLET))
.findAny();
assertThat(anyDateHttpServlet).isNotEmpty();
}

@Test
@Order(3)
void dateServletIsMarkedAsWebServlet() {
Set<Class<?>> servlets =
reflections.getTypesAnnotatedWith(WebServlet.class);
Optional<String> anyMarkedDateServlet = servlets.stream()
.map(Class::getSimpleName)
.filter(servlet -> servlet.equals(DATE_SERVLET))
.findAny();
assertThat(anyMarkedDateServlet).isNotEmpty();
}

@Test
@Order(4)
void dateServletIsMarkedWithProperPath() throws ClassNotFoundException {
String[] value = Class.forName(SERVLET_PACKAGE + "." + DATE_SERVLET)
.getAnnotation(WebServlet.class).value();
assertThat(value).contains("/date");
}

@Test
@Order(5)
void dateServletReturnsDateInResponse() throws IOException, NoSuchMethodException, InvocationTargetException,
IllegalAccessException {
Method doGetMethod = getDoGetMethod();

StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
when(response.getWriter()).thenReturn(printWriter);

doGetMethod.invoke(dateServletObject, request, response);
assertThat(stringWriter.getBuffer().toString()).contains(LocalDate.now().toString());
}

private Method getDoGetMethod() throws NoSuchMethodException {
return dateServletClass
.getMethod("doGet", HttpServletRequest.class, HttpServletResponse.class);
}
}
14 changes: 14 additions & 0 deletions 2-0-servlet-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,19 @@
<modelVersion>4.0.0</modelVersion>

<artifactId>2-0-servlet-api</artifactId>
<packaging>pom</packaging>
<modules>
<module>2-0-1-date-servlet-api</module>
</modules>


<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>

</project>
26 changes: 25 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,29 @@
<maven.compiler.target>11</maven.compiler.target>
</properties>


<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.18.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.12</version>
</dependency>
</dependencies>
</project>