Merge remote-tracking branch 'upstream/master'

This commit is contained in:
anuragkumawat
2022-02-25 15:06:07 +05:30
93 changed files with 2116 additions and 25 deletions
@@ -8,4 +8,5 @@ This module contains articles about Java 8 core features
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [[<-- Prev]](/core-java-modules/core-java-8)
@@ -1,17 +1,24 @@
package com.baeldung.game;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.*;
class RockPaperScissorsGame {
private static Map<Integer, String> movesMap = new HashMap<Integer, String>() {{
put(0, "rock");
put(1, "paper");
put(2, "scissors");
}};
enum Move {
ROCK("rock"),
PAPER("paper"),
SCISSORS("scissors");
private String value;
Move(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
@@ -31,7 +38,7 @@ class RockPaperScissorsGame {
break;
}
if (!movesMap.containsValue(playerMove)) {
if (Arrays.stream(Move.values()).noneMatch(x -> x.getValue().equals(playerMove))) {
System.out.println("Your move isn't valid!");
continue;
}
@@ -51,15 +58,15 @@ class RockPaperScissorsGame {
}
private static boolean isPlayerWin(String playerMove, String computerMove) {
return playerMove.equals("rock") && computerMove.equals("scissors")
|| (playerMove.equals("scissors") && computerMove.equals("paper"))
|| (playerMove.equals("paper") && computerMove.equals("rock"));
return playerMove.equals(Move.ROCK.value) && computerMove.equals(Move.SCISSORS.value)
|| (playerMove.equals(Move.SCISSORS.value) && computerMove.equals(Move.PAPER.value))
|| (playerMove.equals(Move.PAPER.value) && computerMove.equals(Move.ROCK.value));
}
private static String getComputerMove() {
Random random = new Random();
int randomNumber = random.nextInt(3);
String computerMove = movesMap.get(randomNumber);
String computerMove = Move.values()[randomNumber].getValue();
System.out.println("Computer move: " + computerMove);
return computerMove;
}
@@ -7,3 +7,4 @@
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)
- [Java Deque vs. Stack](https://www.baeldung.com/java-deque-vs-stack)
- [Collection.toArray(new T[0]) or .toArray(new T[size])](https://www.baeldung.com/java-collection-toarray-methods)
- [Create an Empty Map in Java](https://www.baeldung.com/java-create-empty-map)
@@ -0,0 +1,56 @@
package com.baeldung.maps.initialize;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
public class EmptyMapInitializer {
public static Map<String, String> articleMap;
static {
articleMap = new HashMap<>();
}
public static Map<String, String> createEmptyMap() {
return Collections.emptyMap();
}
public void createMapUsingConstructors() {
Map hashMap = new HashMap();
Map linkedHashMap = new LinkedHashMap();
Map treeMap = new TreeMap();
}
public Map<String, String> createEmptyMapUsingMapsObject() {
Map<String, String> emptyMap = Maps.newHashMap();
return emptyMap;
}
public Map createGenericEmptyMapUsingMapsObject() {
Map genericEmptyMap = Maps.<String, Integer>newHashMap();
return genericEmptyMap;
}
public static Map<String, String> createMapUsingGuava() {
Map<String, String> emptyMapUsingGuava =
Maps.newHashMap(ImmutableMap.of());
return emptyMapUsingGuava;
}
public SortedMap<String, String> createEmptySortedMap() {
SortedMap<String, String> sortedMap = Collections.emptySortedMap();
return sortedMap;
}
public NavigableMap<String, String> createEmptyNavigableMap() {
NavigableMap<String, String> navigableMap = Collections.emptyNavigableMap();
return navigableMap;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.maps.initialize;
import java.util.Map;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class EmptyMapInitializerUnitTest {
@Test(expected=UnsupportedOperationException.class)
public void givenEmptyMap_whenAddingEntries_throwsException() {
Map<String, String> map = EmptyMapInitializer.createEmptyMap();
map.put("key", "value");
}
@Test
public void givenEmptyMap_whenChecked_returnsTrue() {
assertTrue(EmptyMapInitializer.articleMap.isEmpty());
}
@Test
public void givenEmptyMap_whenCreatedUsingGuava_returnsEmptyOrNot() {
Map<String, String> emptyMapUsingGuava =
EmptyMapInitializer.createMapUsingGuava();
assertTrue(emptyMapUsingGuava.isEmpty());
emptyMapUsingGuava.put("key", "value");
assertFalse(emptyMapUsingGuava.isEmpty());
}
}
@@ -10,4 +10,5 @@ This module contains articles about core Java Security
- [HMAC in Java](https://www.baeldung.com/java-hmac)
- [Generating a Secure AES Key in Java](https://www.baeldung.com/java-secure-aes-key)
- [Computing an X509 Certificate’s Thumbprint in Java](https://www.baeldung.com/java-x509-certificate-thumbprint)
- [Error: “trustAnchors parameter must be non-empty”](https://www.baeldung.com/java-trustanchors-parameter-must-be-non-empty)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)
+1
View File
@@ -6,3 +6,4 @@
- [How To Configure Java Heap Size Inside a Docker Container](https://www.baeldung.com/ops/docker-jvm-heap-size)
- [Dockerfile Strategies for Git](https://www.baeldung.com/ops/dockerfile-git-strategies)
- [How to Get Docker-Compose to Always Use the Latest Image](https://www.baeldung.com/ops/docker-compose-latest-image)
- [How to Include Files Outside of Docker’s Build Context](https://www.baeldung.com/ops/docker-include-files-outside-build-context)
@@ -0,0 +1,2 @@
FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf
@@ -0,0 +1,8 @@
events {}
http {
server {
listen 80;
index index.html;
}
}
@@ -0,0 +1,3 @@
FROM nginx:latest
COPY sample-site/html/* /etc/nginx/html/
COPY config/nginx.conf /etc/nginx/nginx.conf
@@ -0,0 +1,2 @@
FROM sample-site-base:latest
COPY html/* /etc/nginx/html/
@@ -0,0 +1,3 @@
FROM nginx:latest
COPY html/* /etc/nginx/html/
COPY config/nginx.conf /etc/nginx/nginx.conf
@@ -0,0 +1,6 @@
mkdir tmp-context
cp -R ../html tmp-context/
cp -R ../../config tmp-context/
cp Dockerfile-script tmp-context/Dockerfile
docker build -t sample-site:latest tmp-context
rm -rf tmp-context
@@ -0,0 +1,10 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Site</title>
</head>
<body>
<h2>Welcome to the first page of the site</h2>
</body>
</html>
@@ -0,0 +1,3 @@
### Relevant Articles:
- [Gradle: sourceCompatiblity vs targetCompatibility](https://www.baeldung.com/gradle-sourcecompatiblity-vs-targetcompatibility)
+1
View File
@@ -7,3 +7,4 @@
- [Update the Value Associated With a Key in a HashMap](https://www.baeldung.com/java-hashmap-update-value-by-key)
- [Java Map – keySet() vs. entrySet() vs. values() Methods](https://www.baeldung.com/java-map-entries-methods)
- [Java IdentityHashMap Class and Its Use Cases](https://www.baeldung.com/java-identityhashmap)
- [How to Invert a Map in Java](https://www.baeldung.com/java-invert-map)
@@ -0,0 +1,59 @@
package com.baeldung.map.invert;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class InvertHashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("first", 1);
map.put("second", 2);
System.out.println(map);
invertMapUsingForLoop(map);
invertMapUsingStreams(map);
invertMapUsingMapper(map);
map.put("two", 2);
invertMapUsingGroupingBy(map);
}
public static <V, K> Map<V, K> invertMapUsingForLoop(Map<K, V> map) {
Map<V, K> inversedMap = new HashMap<V, K>();
for (Entry<K, V> entry : map.entrySet()) {
inversedMap.put(entry.getValue(), entry.getKey());
}
System.out.println(inversedMap);
return inversedMap;
}
public static <V, K> Map<V, K> invertMapUsingStreams(Map<K, V> map) {
Map<V, K> inversedMap = map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey));
System.out.println(inversedMap);
return inversedMap;
}
public static <K, V> Map<V, K> invertMapUsingMapper(Map<K, V> sourceMap) {
Map<V, K> inversedMap = sourceMap.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue));
System.out.println(inversedMap);
return inversedMap;
}
public static <V, K> Map<V, List<K>> invertMapUsingGroupingBy(Map<K, V> map) {
Map<V, List<K>> inversedMap = map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
System.out.println(inversedMap);
return inversedMap;
}
}
@@ -0,0 +1,72 @@
package com.baeldung.map.invert;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class InvertHashMapUnitTest {
Map<String, Integer> sourceMap;
@BeforeEach
void setup() {
sourceMap = new HashMap<>();
sourceMap.put("Sunday", 0);
sourceMap.put("Monday", 1);
sourceMap.put("Tuesday", 2);
sourceMap.put("Wednesday", 3);
sourceMap.put("Thursday", 4);
sourceMap.put("Friday", 5);
sourceMap.put("Saturday", 6);
}
@Test
void givenSourceMap_whenUsingForLoop_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingForLoop(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMap_whenUsingStreams_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingStreams(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMap_whenUsingMapper_returnsInvertedMap() {
Map<Integer, String> inversedMap = InvertHashMapExample.invertMapUsingMapper(sourceMap);
assertNotNull(inversedMap);
assertEquals(sourceMap.size(), inversedMap.size());
assertEquals("Monday", inversedMap.get(1));
}
@Test
void givenSourceMapWithDuplicateValues_whenUsingGroupBy_returnsInvertedMap() {
sourceMap.put("MONDAY", 1);
Map<Integer, List<String>> inversedMap = InvertHashMapExample.invertMapUsingGroupingBy(sourceMap);
assertNotNull(inversedMap);
assertNotEquals(sourceMap.size(), inversedMap.size()); // duplicate keys are merged now
assertEquals(2, inversedMap.get(1).size());
assertTrue(inversedMap.get(1).contains("Monday"));
assertTrue(inversedMap.get(1).contains("MONDAY"));
}
}
+1
View File
@@ -7,3 +7,4 @@ This module contains articles about the Java Native Interface (JNI).
- [Guide to JNI (Java Native Interface)](https://www.baeldung.com/jni)
- [Using JNA to Access Native Dynamic Libraries](https://www.baeldung.com/java-jna-dynamic-libraries)
- [Check if a Java Program Is Running in 64-Bit or 32-Bit JVM](https://www.baeldung.com/java-detect-jvm-64-or-32-bit)
- [How to use JNI’s RegisterNatives() method?](https://www.baeldung.com/jni-registernatives)
+5
View File
@@ -0,0 +1,5 @@
## Servlets
This module contains articles about Servlets.
### Relevant Articles:
+60
View File
@@ -0,0 +1,60 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.javax-servlets</groupId>
<artifactId>javax-servlets-2</artifactId>
<version>1.0-SNAPSHOT</version>
<name>javax-servlets-2</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- File Uploading -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${javax.servlet.jsp-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${org.apache.httpcomponents.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<org.apache.httpcomponents.version>4.5.13</org.apache.httpcomponents.version>
<javax.servlet-api.version>4.0.1</javax.servlet-api.version>
</properties>
</project>
@@ -0,0 +1,80 @@
package com.baeldung.user.check;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* @since 6 de fev de 2022
* @author ulisses
*/
public class User implements Serializable {
private static final long serialVersionUID = 1L;
protected static final HashMap<String, User> DB = new HashMap<>();
static {
DB.put("admin", new User("admin", "password"));
DB.put("user", new User("user", "pass"));
}
private String name;
private String password;
private List<Date> logins = new ArrayList<Date>();
public User(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Date> getLogins() {
return logins;
}
public void setLogins(List<Date> logins) {
this.logins = logins;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
@@ -0,0 +1,46 @@
package com.baeldung.user.check;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter("/user-check/*")
public class UserCheckFilter implements Filter {
public static void forward(HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/user.check" + page)
.forward(request, response);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if (!(req instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
if (!(res instanceof HttpServletResponse)) {
throw new ServletException("Can only process HttpServletResponse");
}
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
request.setAttribute("origin", request.getRequestURI());
if (!request.getRequestURI()
.contains("login") && request.getSession(false) == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
forward(request, response, "/login.jsp");
// we return here so the original servlet is not processed
return;
}
chain.doFilter(request, response);
}
}
@@ -0,0 +1,56 @@
package com.baeldung.user.check;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/user-check/login")
public class UserCheckLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getSession(false) != null) {
response.sendRedirect(request.getContextPath() + "/user-check/home");
return;
}
String referer = (String) request.getAttribute("origin");
request.setAttribute("origin", referer);
UserCheckFilter.forward(request, response, "/login.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key = request.getParameter("name");
String pass = request.getParameter("password");
User user = User.DB.get(key);
if (user == null || !user.getPassword()
.equals(pass)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
request.setAttribute("origin", request.getParameter("origin"));
request.setAttribute("error", "invalid login");
UserCheckFilter.forward(request, response, "/login.jsp");
return;
}
user.getLogins()
.add(new Date());
HttpSession session = request.getSession();
session.setAttribute("user", user);
String origin = request.getParameter("origin");
if (origin == null || origin.contains("login"))
origin = "./";
response.sendRedirect(origin);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.user.check;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/user-check/logout")
public class UserCheckLogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
request.setAttribute("loggedOut", true);
response.sendRedirect("./");
}
}
@@ -0,0 +1,28 @@
package com.baeldung.user.check;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "home", urlPatterns = { "/user-check/", "/user-check", "/user-check/home" })
public class UserCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("user") == null) {
throw new IllegalStateException("user not logged in");
}
User user = (User) session.getAttribute("user");
request.setAttribute("user", user);
UserCheckFilter.forward(request, response, "/home.jsp");
}
}
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,31 @@
<%@ page contentType="text/html;charset=UTF-8" session="false"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<html>
<head>
<title>login success - current session info</title>
</head>
<body>
<section>
<h2>user info</h2>
<div>
<span>name: ${user.name}</span>
</div>
<div>
<span>logins:</span>
<ul>
<c:forEach var="login" items="${user.logins}">
<li>${login}</li>
</c:forEach>
</ul>
</div>
<div>
<a href="${pageContext.request.contextPath}/user-check/logout">
logout
</a>
</div>
</section>
</body>
</html>
@@ -0,0 +1,33 @@
<%@ page contentType="text/html;charset=UTF-8" session="false"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<html>
<head>
<title>login</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user-check/login"
method="POST">
<input type="hidden" name="origin" value="${origin}">
<c:if test="${not empty origin}">
<div>* redirected to login from: ${origin}</div>
</c:if>
<c:if test="${not empty error}">
<div>* error: ${error}</div>
</c:if>
<fieldset>
<legend>credentials</legend>
<label for="name">name</label>
<input type="text" name="name">
<label for="password">password</label>
<input type="password" name="password">
<input type="submit">
</fieldset>
</form>
</body>
</html>

Some files were not shown because too many files have changed in this diff Show More