commit
						88f832b6b7
					
				
							
								
								
									
										6
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										6
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @ -42,3 +42,9 @@ spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties | ||||
| *.springBeans | ||||
| 
 | ||||
| 20171220-JMeter.csv | ||||
| 
 | ||||
| .factorypath | ||||
| dependency-reduced-pom.xml | ||||
| *.so | ||||
| *.dylib | ||||
| *.dll | ||||
|  | ||||
							
								
								
									
										3
									
								
								.gitmodules
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										3
									
								
								.gitmodules
									
									
									
									
										vendored
									
									
								
							| @ -1,3 +0,0 @@ | ||||
| [submodule "testgitrepo"] | ||||
| 	path = testgitrepo | ||||
| 	url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/ | ||||
| @ -22,3 +22,6 @@ | ||||
| - [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words) | ||||
| - [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations) | ||||
| - [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum) | ||||
| - [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic) | ||||
| - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) | ||||
| - [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element) | ||||
|  | ||||
| @ -10,7 +10,7 @@ public class MonteCarloTreeSearch { | ||||
| 
 | ||||
|     private static final int WIN_SCORE = 10; | ||||
|     private int level; | ||||
|     private int oponent; | ||||
|     private int opponent; | ||||
| 
 | ||||
|     public MonteCarloTreeSearch() { | ||||
|         this.level = 3; | ||||
| @ -32,11 +32,11 @@ public class MonteCarloTreeSearch { | ||||
|         long start = System.currentTimeMillis(); | ||||
|         long end = start + 60 * getMillisForCurrentLevel(); | ||||
| 
 | ||||
|         oponent = 3 - playerNo; | ||||
|         opponent = 3 - playerNo; | ||||
|         Tree tree = new Tree(); | ||||
|         Node rootNode = tree.getRoot(); | ||||
|         rootNode.getState().setBoard(board); | ||||
|         rootNode.getState().setPlayerNo(oponent); | ||||
|         rootNode.getState().setPlayerNo(opponent); | ||||
| 
 | ||||
|         while (System.currentTimeMillis() < end) { | ||||
|             // Phase 1 - Selection | ||||
| @ -93,7 +93,7 @@ public class MonteCarloTreeSearch { | ||||
|         State tempState = tempNode.getState(); | ||||
|         int boardStatus = tempState.getBoard().checkStatus(); | ||||
| 
 | ||||
|         if (boardStatus == oponent) { | ||||
|         if (boardStatus == opponent) { | ||||
|             tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE); | ||||
|             return boardStatus; | ||||
|         } | ||||
|  | ||||
| @ -0,0 +1,52 @@ | ||||
| package com.baeldung.algorithms.romannumerals; | ||||
| 
 | ||||
| import java.util.List; | ||||
| 
 | ||||
| class RomanArabicConverter { | ||||
| 
 | ||||
|     public static int romanToArabic(String input) { | ||||
|         String romanNumeral = input.toUpperCase(); | ||||
|         int result = 0; | ||||
|          | ||||
|         List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues(); | ||||
| 
 | ||||
|         int i = 0; | ||||
| 
 | ||||
|         while ((romanNumeral.length() > 0) && (i < romanNumerals.size())) { | ||||
|             RomanNumeral symbol = romanNumerals.get(i); | ||||
|             if (romanNumeral.startsWith(symbol.name())) { | ||||
|                 result += symbol.getValue(); | ||||
|                 romanNumeral = romanNumeral.substring(symbol.name().length()); | ||||
|             } else { | ||||
|                 i++; | ||||
|             } | ||||
|         } | ||||
|         if (romanNumeral.length() > 0) { | ||||
|             throw new IllegalArgumentException(input + " cannot be converted to a Roman Numeral"); | ||||
|         } | ||||
| 
 | ||||
|         return result; | ||||
|     } | ||||
| 
 | ||||
|     public static String arabicToRoman(int number) { | ||||
|         if ((number <= 0) || (number > 4000)) { | ||||
|             throw new IllegalArgumentException(number + " is not in range (0,4000]"); | ||||
|         } | ||||
| 
 | ||||
|         List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues(); | ||||
| 
 | ||||
|         int i = 0; | ||||
|         StringBuilder sb = new StringBuilder(); | ||||
| 
 | ||||
|         while (number > 0 && i < romanNumerals.size()) { | ||||
|             RomanNumeral currentSymbol = romanNumerals.get(i); | ||||
|             if (currentSymbol.getValue() <= number) { | ||||
|                 sb.append(currentSymbol.name()); | ||||
|                 number -= currentSymbol.getValue(); | ||||
|             } else { | ||||
|                 i++; | ||||
|             } | ||||
|         } | ||||
|         return sb.toString(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,26 @@ | ||||
| package com.baeldung.algorithms.romannumerals; | ||||
| 
 | ||||
| import java.util.Arrays; | ||||
| import java.util.Comparator; | ||||
| import java.util.List; | ||||
| import java.util.stream.Collectors; | ||||
| 
 | ||||
| enum RomanNumeral { | ||||
|     I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000); | ||||
| 
 | ||||
|     private int value; | ||||
| 
 | ||||
|     RomanNumeral(int value) { | ||||
|         this.value = value; | ||||
|     } | ||||
| 
 | ||||
|     public int getValue() { | ||||
|         return value; | ||||
|     } | ||||
|      | ||||
|     public static List<RomanNumeral> getReverseSortedValues() { | ||||
|         return Arrays.stream(values()) | ||||
|           .sorted(Comparator.comparing((RomanNumeral e) -> e.value).reversed()) | ||||
|           .collect(Collectors.toList()); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,29 @@ | ||||
| package com.baeldung.algorithms.romannumerals; | ||||
| 
 | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class RomanArabicConverterUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() { | ||||
| 
 | ||||
|         String roman2018 = "MMXVIII"; | ||||
| 
 | ||||
|         int result = RomanArabicConverter.romanToArabic(roman2018); | ||||
| 
 | ||||
|         assertThat(result).isEqualTo(2018); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() { | ||||
| 
 | ||||
|         int arabic1999 = 1999; | ||||
| 
 | ||||
|         String result = RomanArabicConverter.arabicToRoman(arabic1999); | ||||
| 
 | ||||
|         assertThat(result).isEqualTo("MCMXCIX"); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
							
								
								
									
										3
									
								
								antlr/README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										3
									
								
								antlr/README.md
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,3 @@ | ||||
| ### Relevant Articles:  | ||||
| 
 | ||||
| - [Java with ANTLR](http://www.baeldung.com/java-antlr) | ||||
							
								
								
									
										66
									
								
								antlr/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										66
									
								
								antlr/pom.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,66 @@ | ||||
| <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/maven-v4_0_0.xsd"> | ||||
|     <modelVersion>4.0.0</modelVersion> | ||||
|     <artifactId>antlr</artifactId> | ||||
|     <name>antlr</name> | ||||
| 
 | ||||
|     <parent> | ||||
|         <groupId>com.baeldung</groupId> | ||||
|         <artifactId>parent-modules</artifactId> | ||||
|         <version>1.0.0-SNAPSHOT</version> | ||||
|     </parent> | ||||
| 
 | ||||
|     <build> | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <groupId>org.antlr</groupId> | ||||
|                 <artifactId>antlr4-maven-plugin</artifactId> | ||||
|                 <version>${antlr.version}</version> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <goals> | ||||
|                             <goal>antlr4</goal> | ||||
|                         </goals> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|             <plugin> | ||||
|                 <groupId>org.codehaus.mojo</groupId> | ||||
|                 <artifactId>build-helper-maven-plugin</artifactId> | ||||
|                 <version>${mojo.version}</version> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <phase>generate-sources</phase> | ||||
|                         <goals> | ||||
|                             <goal>add-source</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <sources> | ||||
|                                 <source>${basedir}/target/generated-sources/antlr4</source> | ||||
|                             </sources> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
|     <dependencies> | ||||
| 		<dependency> | ||||
| 			<groupId>org.antlr</groupId> | ||||
| 			<artifactId>antlr4-runtime</artifactId> | ||||
| 			<version>${antlr.version}</version> | ||||
| 		</dependency> | ||||
|         <dependency> | ||||
|             <groupId>junit</groupId> | ||||
|             <artifactId>junit</artifactId> | ||||
|             <version>${junit.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
|     <properties> | ||||
|         <java.version>1.8</java.version> | ||||
|         <antlr.version>4.7.1</antlr.version> | ||||
|         <junit.version>4.12</junit.version> | ||||
|         <mojo.version>3.0.0</mojo.version> | ||||
|     </properties> | ||||
| </project> | ||||
							
								
								
									
										1775
									
								
								antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										1775
									
								
								antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4
									
									
									
									
									
										Normal file
									
								
							
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							
							
								
								
									
										16
									
								
								antlr/src/main/antlr4/com/baeldung/antlr/Log.g4
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								antlr/src/main/antlr4/com/baeldung/antlr/Log.g4
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,16 @@ | ||||
| grammar Log; | ||||
| 
 | ||||
| log : entry+; | ||||
| entry : timestamp ' ' level ' ' message CRLF; | ||||
| timestamp : DATE ' ' TIME; | ||||
| level : 'ERROR' | 'INFO' | 'DEBUG'; | ||||
| message : (TEXT | ' ')+; | ||||
| 
 | ||||
| fragment DIGIT : [0-9]; | ||||
| fragment TWODIGIT : DIGIT DIGIT; | ||||
| fragment LETTER : [A-Za-z]; | ||||
| 
 | ||||
| DATE : TWODIGIT TWODIGIT '-' LETTER LETTER LETTER '-' TWODIGIT; | ||||
| TIME : TWODIGIT ':' TWODIGIT ':' TWODIGIT; | ||||
| TEXT : LETTER+; | ||||
| CRLF : '\r'? '\n' | '\r'; | ||||
| @ -0,0 +1,28 @@ | ||||
| package com.baeldung.antlr.java; | ||||
| 
 | ||||
| import com.baeldung.antlr.Java8BaseListener; | ||||
| import com.baeldung.antlr.Java8Parser; | ||||
| import org.antlr.v4.runtime.tree.TerminalNode; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.Collections; | ||||
| import java.util.List; | ||||
| 
 | ||||
| public class UppercaseMethodListener extends Java8BaseListener { | ||||
| 
 | ||||
|     private List<String> errors = new ArrayList<String>(); | ||||
| 
 | ||||
|     @Override | ||||
|     public void enterMethodDeclarator(Java8Parser.MethodDeclaratorContext ctx) { | ||||
|         TerminalNode node = ctx.Identifier(); | ||||
|         String methodName = node.getText(); | ||||
| 
 | ||||
|         if (Character.isUpperCase(methodName.charAt(0))){ | ||||
|             errors.add(String.format("Method %s is uppercased!", methodName)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public List<String> getErrors(){ | ||||
|         return Collections.unmodifiableList(errors); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										51
									
								
								antlr/src/main/java/com/baeldung/antlr/log/LogListener.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										51
									
								
								antlr/src/main/java/com/baeldung/antlr/log/LogListener.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,51 @@ | ||||
| package com.baeldung.antlr.log; | ||||
| 
 | ||||
| import com.baeldung.antlr.LogBaseListener; | ||||
| import com.baeldung.antlr.LogParser; | ||||
| import com.baeldung.antlr.log.model.LogLevel; | ||||
| import com.baeldung.antlr.log.model.LogEntry; | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.format.DateTimeFormatter; | ||||
| import java.util.ArrayList; | ||||
| import java.util.Collections; | ||||
| import java.util.List; | ||||
| import java.util.Locale; | ||||
| 
 | ||||
| public class LogListener extends LogBaseListener { | ||||
| 
 | ||||
|     private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER | ||||
|             = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss", Locale.ENGLISH); | ||||
| 
 | ||||
|     private List<LogEntry> entries = new ArrayList<>(); | ||||
|     private LogEntry currentLogEntry; | ||||
| 
 | ||||
|     @Override | ||||
|     public void enterEntry(LogParser.EntryContext ctx) { | ||||
|         this.currentLogEntry = new LogEntry(); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void exitEntry(LogParser.EntryContext ctx) { | ||||
|         entries.add(currentLogEntry); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void enterTimestamp(LogParser.TimestampContext ctx) { | ||||
|         currentLogEntry.setTimestamp(LocalDateTime.parse(ctx.getText(), DEFAULT_DATETIME_FORMATTER)); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void enterMessage(LogParser.MessageContext ctx) { | ||||
|         currentLogEntry.setMessage(ctx.getText()); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void enterLevel(LogParser.LevelContext ctx) { | ||||
|         currentLogEntry.setLevel(LogLevel.valueOf(ctx.getText())); | ||||
|     } | ||||
| 
 | ||||
|     public List<LogEntry> getEntries() { | ||||
|         return Collections.unmodifiableList(entries); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,35 @@ | ||||
| package com.baeldung.antlr.log.model; | ||||
| 
 | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| 
 | ||||
| public class LogEntry { | ||||
| 
 | ||||
|     private LogLevel level; | ||||
|     private String message; | ||||
|     private LocalDateTime timestamp; | ||||
| 
 | ||||
|     public LogLevel getLevel() { | ||||
|         return level; | ||||
|     } | ||||
| 
 | ||||
|     public void setLevel(LogLevel level) { | ||||
|         this.level = level; | ||||
|     } | ||||
| 
 | ||||
|     public String getMessage() { | ||||
|         return message; | ||||
|     } | ||||
| 
 | ||||
|     public void setMessage(String message) { | ||||
|         this.message = message; | ||||
|     } | ||||
| 
 | ||||
|     public LocalDateTime getTimestamp() { | ||||
|         return timestamp; | ||||
|     } | ||||
| 
 | ||||
|     public void setTimestamp(LocalDateTime timestamp) { | ||||
|         this.timestamp = timestamp; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,5 @@ | ||||
| package com.baeldung.antlr.log.model; | ||||
| 
 | ||||
| public enum LogLevel { | ||||
|     DEBUG, INFO, ERROR | ||||
| } | ||||
| @ -0,0 +1,30 @@ | ||||
| package com.baeldung.antlr; | ||||
| 
 | ||||
| import com.baeldung.antlr.java.UppercaseMethodListener; | ||||
| import org.antlr.v4.runtime.CharStreams; | ||||
| import org.antlr.v4.runtime.CommonTokenStream; | ||||
| import org.antlr.v4.runtime.tree.ParseTree; | ||||
| import org.antlr.v4.runtime.tree.ParseTreeWalker; | ||||
| import org.junit.Test; | ||||
| import static org.hamcrest.CoreMatchers.is; | ||||
| import static org.hamcrest.MatcherAssert.assertThat; | ||||
| 
 | ||||
| public class JavaParserUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenOneMethodStartsWithUpperCase_thenOneErrorReturned() throws Exception{ | ||||
| 
 | ||||
|         String javaClassContent = "public class SampleClass { void DoSomething(){} }"; | ||||
|         Java8Lexer java8Lexer = new Java8Lexer(CharStreams.fromString(javaClassContent)); | ||||
|         CommonTokenStream tokens = new CommonTokenStream(java8Lexer); | ||||
|         Java8Parser java8Parser = new Java8Parser(tokens); | ||||
|         ParseTree tree = java8Parser.compilationUnit(); | ||||
|         ParseTreeWalker walker = new ParseTreeWalker(); | ||||
|         UppercaseMethodListener uppercaseMethodListener = new UppercaseMethodListener(); | ||||
|         walker.walk(uppercaseMethodListener, tree); | ||||
| 
 | ||||
|         assertThat(uppercaseMethodListener.getErrors().size(), is(1)); | ||||
|         assertThat(uppercaseMethodListener.getErrors().get(0), | ||||
|                 is("Method DoSomething is uppercased!")); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.antlr; | ||||
| 
 | ||||
| import static org.hamcrest.CoreMatchers.is; | ||||
| import static org.hamcrest.MatcherAssert.assertThat; | ||||
| 
 | ||||
| import com.baeldung.antlr.log.LogListener; | ||||
| import com.baeldung.antlr.log.model.LogLevel; | ||||
| import com.baeldung.antlr.log.model.LogEntry; | ||||
| import org.antlr.v4.runtime.CharStreams; | ||||
| import org.antlr.v4.runtime.CommonTokenStream; | ||||
| import org.antlr.v4.runtime.tree.ParseTreeWalker; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| 
 | ||||
| 
 | ||||
| public class LogParserUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLogContainsOneErrorLogEntry_thenOneErrorIsReturned() throws Exception { | ||||
|         String logLines = "2018-May-05 14:20:21 DEBUG entering awesome method\r\n" + | ||||
|                 "2018-May-05 14:20:24 ERROR Bad thing happened\r\n"; | ||||
|         LogLexer serverLogLexer = new LogLexer(CharStreams.fromString(logLines)); | ||||
|         CommonTokenStream tokens = new CommonTokenStream( serverLogLexer ); | ||||
|         LogParser logParser = new LogParser(tokens); | ||||
|         ParseTreeWalker walker = new ParseTreeWalker(); | ||||
|         LogListener logWalker = new LogListener(); | ||||
|         walker.walk(logWalker, logParser.log()); | ||||
| 
 | ||||
|         assertThat(logWalker.getEntries().size(), is(2)); | ||||
|         LogEntry error = logWalker.getEntries().get(1); | ||||
|         assertThat(error.getLevel(), is(LogLevel.ERROR)); | ||||
|         assertThat(error.getMessage(), is("Bad thing happened")); | ||||
|         assertThat(error.getTimestamp(), is(LocalDateTime.of(2018,5,5,14,20,24))); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										57
									
								
								apache-meecrowave/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										57
									
								
								apache-meecrowave/pom.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,57 @@ | ||||
| <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</groupId> | ||||
|     <artifactId>apache-meecrowave</artifactId> | ||||
|     <version>0.0.1</version> | ||||
|     <name>apache-meecrowave</name> | ||||
|     <description>A sample REST API application with Meecrowave</description> | ||||
| 
 | ||||
|     <properties> | ||||
|         <maven.compiler.source>1.8</maven.compiler.source> | ||||
|         <maven.compiler.target>1.8</maven.compiler.target> | ||||
|     </properties> | ||||
|     <dependencies> | ||||
|         <!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-core --> | ||||
|         <dependency> | ||||
|             <groupId>org.apache.meecrowave</groupId> | ||||
|             <artifactId>meecrowave-core</artifactId> | ||||
|             <version>1.2.1</version> | ||||
|         </dependency> | ||||
|         <!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-jpa --> | ||||
|         <dependency> | ||||
|             <groupId>org.apache.meecrowave</groupId> | ||||
|             <artifactId>meecrowave-jpa</artifactId> | ||||
|             <version>1.2.1</version> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>com.squareup.okhttp3</groupId> | ||||
|             <artifactId>okhttp</artifactId> | ||||
|             <version>3.10.0</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.apache.meecrowave</groupId> | ||||
|             <artifactId>meecrowave-junit</artifactId> | ||||
|             <version>1.2.0</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|         <!-- https://mvnrepository.com/artifact/junit/junit --> | ||||
|         <dependency> | ||||
|             <groupId>junit</groupId> | ||||
|             <artifactId>junit</artifactId> | ||||
|             <version>4.10</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
| 
 | ||||
|     </dependencies> | ||||
|     <build> | ||||
|         <plugins> | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.meecrowave</groupId> | ||||
|                 <artifactId>meecrowave-maven-plugin</artifactId> | ||||
|                 <version>1.2.1</version> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
| </project> | ||||
| @ -0,0 +1,30 @@ | ||||
| package com.baeldung.meecrowave; | ||||
| 
 | ||||
| public class Article { | ||||
|     private String name; | ||||
|     private String author; | ||||
| 
 | ||||
|     public Article() { | ||||
|     } | ||||
| 
 | ||||
|     public Article(String name, String author) { | ||||
|         this.author = author; | ||||
|         this.name = name; | ||||
|     } | ||||
| 
 | ||||
|     public String getName() { | ||||
|         return name; | ||||
|     } | ||||
| 
 | ||||
|     public void setName(String name) { | ||||
|         this.name = name; | ||||
|     } | ||||
| 
 | ||||
|     public String getAuthor() { | ||||
|         return author; | ||||
|     } | ||||
| 
 | ||||
|     public void setAuthor(String author) { | ||||
|         this.author = author; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,32 @@ | ||||
| package com.baeldung.meecrowave; | ||||
| 
 | ||||
| import javax.enterprise.context.RequestScoped; | ||||
| import javax.inject.Inject; | ||||
| import javax.ws.rs.GET; | ||||
| import javax.ws.rs.POST; | ||||
| import javax.ws.rs.Path; | ||||
| import javax.ws.rs.core.Response; | ||||
| import javax.ws.rs.core.Response.Status; | ||||
| 
 | ||||
| @RequestScoped | ||||
| @Path("article") | ||||
| public class ArticleEndpoints { | ||||
| 
 | ||||
|     @Inject | ||||
|     ArticleService articleService; | ||||
| 
 | ||||
|     @GET | ||||
|     public Response getArticle() { | ||||
|         return Response.ok() | ||||
|             .entity(new Article("name", "author")) | ||||
|             .build(); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     @POST | ||||
|     public Response createArticle(Article article) { | ||||
|         return Response.status(Status.CREATED) | ||||
|             .entity(articleService.createArticle(article)) | ||||
|             .build(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,10 @@ | ||||
| package com.baeldung.meecrowave; | ||||
| 
 | ||||
| import javax.enterprise.context.ApplicationScoped; | ||||
| 
 | ||||
| @ApplicationScoped | ||||
| public class ArticleService { | ||||
|     public Article createArticle(Article article) { | ||||
|         return article; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,16 @@ | ||||
| package com.baeldung.meecrowave; | ||||
| 
 | ||||
| import org.apache.meecrowave.Meecrowave; | ||||
| 
 | ||||
| public class Server { | ||||
|     public static void main(String[] args) { | ||||
|         final Meecrowave.Builder builder = new Meecrowave.Builder(); | ||||
|         builder.setScanningPackageIncludes("com.baeldung.meecrowave"); | ||||
|         builder.setJaxrsMapping("/api/*"); | ||||
|         builder.setJsonpPrettify(true); | ||||
| 
 | ||||
|         try (Meecrowave meecrowave = new Meecrowave(builder)) { | ||||
|             meecrowave.bake().await(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,41 @@ | ||||
| package com.baeldung.meecrowave; | ||||
| 
 | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| import java.io.IOException; | ||||
| 
 | ||||
| import org.apache.meecrowave.Meecrowave; | ||||
| import org.apache.meecrowave.junit.MonoMeecrowave; | ||||
| import org.apache.meecrowave.testing.ConfigurationInject; | ||||
| import org.junit.BeforeClass; | ||||
| import org.junit.Test; | ||||
| import org.junit.runner.RunWith; | ||||
| 
 | ||||
| import okhttp3.OkHttpClient; | ||||
| import okhttp3.Request; | ||||
| import okhttp3.Response; | ||||
| 
 | ||||
| @RunWith(MonoMeecrowave.Runner.class) | ||||
| public class ArticleEndpointsTest { | ||||
|      | ||||
|     @ConfigurationInject | ||||
|     private Meecrowave.Builder config; | ||||
|     private static OkHttpClient client; | ||||
|      | ||||
|     @BeforeClass | ||||
|     public static void setup() { | ||||
|         client = new OkHttpClient(); | ||||
|     } | ||||
|      | ||||
|    @Test | ||||
|     public void whenRetunedArticle_thenCorrect() throws IOException { | ||||
|         final String base = "http://localhost:"+config.getHttpPort(); | ||||
|          | ||||
|         Request request = new Request.Builder() | ||||
|           .url(base+"/article") | ||||
|           .build(); | ||||
|         Response response = client.newCall(request).execute(); | ||||
|         assertEquals(200,  response.code()); | ||||
|     } | ||||
| } | ||||
| @ -12,7 +12,7 @@ import org.apache.solr.common.SolrDocumentList; | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class SolrJavaIntegrationTest { | ||||
| public class SolrJavaLiveTest { | ||||
| 
 | ||||
|     private SolrJavaIntegration solrJavaIntegration; | ||||
| 
 | ||||
							
								
								
									
										3
									
								
								aws-lambda/README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										3
									
								
								aws-lambda/README.md
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,3 @@ | ||||
| ### Relevant Articles:  | ||||
| - [Using AWS Lambda with API Gateway](http://www.baeldung.com/aws-lambda-api-gateway) | ||||
| - [Introduction to AWS Serverless Application Model](http://www.baeldung.com/aws-serverless) | ||||
							
								
								
									
										99
									
								
								aws-lambda/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										99
									
								
								aws-lambda/pom.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,99 @@ | ||||
| <?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>parent-modules</artifactId> | ||||
|         <groupId>com.baeldung</groupId> | ||||
|         <version>1.0.0-SNAPSHOT</version> | ||||
|     </parent> | ||||
|     <modelVersion>4.0.0</modelVersion> | ||||
| 
 | ||||
|     <groupId>com.baeldung</groupId> | ||||
|     <artifactId>aws-lambda</artifactId> | ||||
|     <version>0.1.0-SNAPSHOT</version> | ||||
|     <packaging>jar</packaging> | ||||
|     <name>aws-lambda</name> | ||||
| 
 | ||||
|     <dependencies> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>com.amazonaws</groupId> | ||||
|             <artifactId>aws-java-sdk-dynamodb</artifactId> | ||||
|             <version>1.11.241</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>com.amazonaws</groupId> | ||||
|             <artifactId>aws-java-sdk-core</artifactId> | ||||
|             <version>1.11.241</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>com.amazonaws</groupId> | ||||
|             <artifactId>aws-lambda-java-core</artifactId> | ||||
|             <version>${aws-lambda-java-core.version}</version> | ||||
|             <exclusions> | ||||
|                 <exclusion> | ||||
|                     <artifactId>commons-logging</artifactId> | ||||
|                     <groupId>commons-logging</groupId> | ||||
|                 </exclusion> | ||||
|             </exclusions> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>com.amazonaws</groupId> | ||||
|             <artifactId>aws-lambda-java-events</artifactId> | ||||
|             <version>${aws-lambda-java-events.version}</version> | ||||
|             <exclusions> | ||||
|                 <exclusion> | ||||
|                     <artifactId>commons-logging</artifactId> | ||||
|                     <groupId>commons-logging</groupId> | ||||
|                 </exclusion> | ||||
|             </exclusions> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>com.google.code.gson</groupId> | ||||
|             <artifactId>gson</artifactId> | ||||
|             <version>${gson.version}</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>commons-io</groupId> | ||||
|             <artifactId>commons-io</artifactId> | ||||
|             <version>${commons-io.version}</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>com.googlecode.json-simple</groupId> | ||||
|             <artifactId>json-simple</artifactId> | ||||
|             <version>${json-simple.version}</version> | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
|     <build> | ||||
|     <plugins> | ||||
|     <plugin> | ||||
|         <groupId>org.apache.maven.plugins</groupId> | ||||
|         <artifactId>maven-shade-plugin</artifactId> | ||||
|         <version>${maven-shade-plugin.version}</version> | ||||
|         <configuration> | ||||
|             <createDependencyReducedPom>false</createDependencyReducedPom> | ||||
|         </configuration> | ||||
|         <executions> | ||||
|             <execution> | ||||
|                 <phase>package</phase> | ||||
|                 <goals> | ||||
|                     <goal>shade</goal> | ||||
|                 </goals> | ||||
|             </execution> | ||||
|         </executions> | ||||
|     </plugin> | ||||
|     </plugins> | ||||
|     </build> | ||||
|     <properties> | ||||
|         <json-simple.version>1.1.1</json-simple.version> | ||||
|         <org.json.version>20180130</org.json.version> | ||||
|         <commons-io.version>2.5</commons-io.version> | ||||
|         <aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version> | ||||
|         <aws-lambda-java-core.version>1.2.0</aws-lambda-java-core.version> | ||||
|         <gson.version>2.8.2</gson.version> | ||||
|         <aws-java-sdk-core.version>1.11.241</aws-java-sdk-core.version> | ||||
|         <maven-shade-plugin.version>3.0.0</maven-shade-plugin.version> | ||||
|         <maven-dependency-plugin.version>2.10</maven-dependency-plugin.version> | ||||
|     </properties> | ||||
| </project> | ||||
							
								
								
									
										60
									
								
								aws-lambda/sam-templates/template-implicit.yaml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										60
									
								
								aws-lambda/sam-templates/template-implicit.yaml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,60 @@ | ||||
| AWSTemplateFormatVersion: '2010-09-09' | ||||
| Transform: 'AWS::Serverless-2016-10-31' | ||||
| Description: Baeldung Serverless Application Model Example with Implicit API Definition | ||||
| Globals: | ||||
|   Api: | ||||
|     EndpointConfiguration: REGIONAL | ||||
|     Name: "TestAPI" | ||||
| Resources: | ||||
|   PersonTable: | ||||
|     Type: AWS::Serverless::SimpleTable | ||||
|     Properties: | ||||
|       PrimaryKey: | ||||
|           Name: id | ||||
|           Type: Number | ||||
|       TableName: Person | ||||
|   StorePersonFunction: | ||||
|     Type: AWS::Serverless::Function | ||||
|     Properties: | ||||
|       Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleRequest | ||||
|       Runtime: java8 | ||||
|       Timeout: 15 | ||||
|       MemorySize: 512 | ||||
|       CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar | ||||
|       Policies: | ||||
|         - DynamoDBCrudPolicy: | ||||
|             TableName: !Ref PersonTable | ||||
|       Environment: | ||||
|         Variables: | ||||
|           TABLE_NAME: !Ref PersonTable | ||||
|       Events: | ||||
|         StoreApi: | ||||
|           Type: Api | ||||
|           Properties: | ||||
|             Path: /persons | ||||
|             Method: PUT | ||||
|   GetPersonByHTTPParamFunction: | ||||
|     Type: AWS::Serverless::Function | ||||
|     Properties: | ||||
|       Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByParam | ||||
|       Runtime: java8 | ||||
|       Timeout: 15 | ||||
|       MemorySize: 512 | ||||
|       CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar | ||||
|       Policies: | ||||
|         - DynamoDBReadPolicy: | ||||
|             TableName: !Ref PersonTable | ||||
|       Environment: | ||||
|         Variables: | ||||
|           TABLE_NAME: !Ref PersonTable | ||||
|       Events: | ||||
|         GetByPathApi: | ||||
|           Type: Api | ||||
|           Properties: | ||||
|             Path: /persons/{id} | ||||
|             Method: GET | ||||
|         GetByQueryApi: | ||||
|           Type: Api | ||||
|           Properties: | ||||
|             Path: /persons | ||||
|             Method: GET | ||||
							
								
								
									
										112
									
								
								aws-lambda/sam-templates/template-inline-swagger.yaml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										112
									
								
								aws-lambda/sam-templates/template-inline-swagger.yaml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,112 @@ | ||||
| AWSTemplateFormatVersion: '2010-09-09' | ||||
| Transform: 'AWS::Serverless-2016-10-31' | ||||
| Description: Baeldung Serverless Application Model Example with Inline Swagger API Definition | ||||
| Resources: | ||||
|   PersonTable: | ||||
|     Type: AWS::Serverless::SimpleTable | ||||
|     Properties: | ||||
|       PrimaryKey: | ||||
|           Name: id | ||||
|           Type: Number | ||||
|       TableName: Person | ||||
|   StorePersonFunction: | ||||
|     Type: AWS::Serverless::Function | ||||
|     Properties: | ||||
|       Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleRequest | ||||
|       Runtime: java8 | ||||
|       Timeout: 15 | ||||
|       MemorySize: 512 | ||||
|       CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar | ||||
|       Policies: | ||||
|         - DynamoDBCrudPolicy: | ||||
|             TableName: !Ref PersonTable | ||||
|       Environment: | ||||
|         Variables: | ||||
|           TABLE_NAME: !Ref PersonTable | ||||
|       Events: | ||||
|         StoreApi: | ||||
|           Type: Api | ||||
|           Properties: | ||||
|             Path: /persons | ||||
|             Method: PUT | ||||
|             RestApiId: | ||||
|                 Ref: MyApi | ||||
|   GetPersonByHTTPParamFunction: | ||||
|     Type: AWS::Serverless::Function | ||||
|     Properties: | ||||
|       Handler: com.baeldung.lambda.apigateway.APIDemoHandler::handleGetByParam | ||||
|       Runtime: java8 | ||||
|       Timeout: 15 | ||||
|       MemorySize: 512 | ||||
|       CodeUri: ../target/aws-lambda-0.1.0-SNAPSHOT.jar | ||||
|       Policies: | ||||
|         - DynamoDBReadPolicy: | ||||
|             TableName: !Ref PersonTable | ||||
|       Environment: | ||||
|         Variables: | ||||
|           TABLE_NAME: !Ref PersonTable | ||||
|       Events: | ||||
|         GetByPathApi: | ||||
|           Type: Api | ||||
|           Properties: | ||||
|             Path: /persons/{id} | ||||
|             Method: GET | ||||
|             RestApiId: | ||||
|                 Ref: MyApi | ||||
|         GetByQueryApi: | ||||
|           Type: Api | ||||
|           Properties: | ||||
|             Path: /persons | ||||
|             Method: GET | ||||
|             RestApiId: | ||||
|                 Ref: MyApi | ||||
|   MyApi: | ||||
|     Type: AWS::Serverless::Api | ||||
|     Properties: | ||||
|       StageName: test | ||||
|       EndpointConfiguration: REGIONAL | ||||
|       DefinitionBody: | ||||
|         swagger: "2.0" | ||||
|         info: | ||||
|           title: "TestAPI" | ||||
|         paths: | ||||
|           /persons: | ||||
|             get: | ||||
|               parameters: | ||||
|               - name: "id" | ||||
|                 in: "query" | ||||
|                 required: true | ||||
|                 type: "string" | ||||
|               x-amazon-apigateway-request-validator: "Validate query string parameters and\ | ||||
|                 \ headers" | ||||
|               x-amazon-apigateway-integration: | ||||
|                 uri: | ||||
|                   Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetPersonByHTTPParamFunction.Arn}/invocations | ||||
|                 responses: {} | ||||
|                 httpMethod: "POST" | ||||
|                 type: "aws_proxy" | ||||
|             put: | ||||
|               x-amazon-apigateway-integration: | ||||
|                 uri: | ||||
|                   Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${StorePersonFunction.Arn}/invocations | ||||
|                 responses: {} | ||||
|                 httpMethod: "POST" | ||||
|                 type: "aws_proxy" | ||||
|           /persons/{id}: | ||||
|             get: | ||||
|               parameters: | ||||
|               - name: "id" | ||||
|                 in: "path" | ||||
|                 required: true | ||||
|                 type: "string" | ||||
|               responses: {} | ||||
|               x-amazon-apigateway-integration: | ||||
|                 uri: | ||||
|                   Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetPersonByHTTPParamFunction.Arn}/invocations | ||||
|                 responses: {} | ||||
|                 httpMethod: "POST" | ||||
|                 type: "aws_proxy" | ||||
|         x-amazon-apigateway-request-validators: | ||||
|           Validate query string parameters and headers: | ||||
|             validateRequestParameters: true | ||||
|             validateRequestBody: false | ||||
| @ -0,0 +1,121 @@ | ||||
| package com.baeldung.lambda.apigateway; | ||||
| 
 | ||||
| import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; | ||||
| import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; | ||||
| import com.amazonaws.services.dynamodbv2.document.*; | ||||
| import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec; | ||||
| import com.amazonaws.services.lambda.runtime.Context; | ||||
| import com.amazonaws.services.lambda.runtime.RequestStreamHandler; | ||||
| import com.baeldung.lambda.apigateway.model.Person; | ||||
| import org.json.simple.JSONObject; | ||||
| import org.json.simple.parser.JSONParser; | ||||
| import org.json.simple.parser.ParseException; | ||||
| 
 | ||||
| import java.io.*; | ||||
| 
 | ||||
| public class APIDemoHandler implements RequestStreamHandler { | ||||
| 
 | ||||
|     private JSONParser parser = new JSONParser(); | ||||
|     private static final String DYNAMODB_TABLE_NAME = System.getenv("TABLE_NAME"); | ||||
| 
 | ||||
|     @Override | ||||
|     public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { | ||||
| 
 | ||||
|         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); | ||||
|         JSONObject responseJson = new JSONObject(); | ||||
| 
 | ||||
|         AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); | ||||
|         DynamoDB dynamoDb = new DynamoDB(client); | ||||
| 
 | ||||
|         try { | ||||
|             JSONObject event = (JSONObject) parser.parse(reader); | ||||
| 
 | ||||
|             if (event.get("body") != null) { | ||||
| 
 | ||||
|                 Person person = new Person((String) event.get("body")); | ||||
| 
 | ||||
|                 dynamoDb.getTable(DYNAMODB_TABLE_NAME) | ||||
|                     .putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId()) | ||||
|                         .withString("name", person.getName()))); | ||||
|             } | ||||
| 
 | ||||
|             JSONObject responseBody = new JSONObject(); | ||||
|             responseBody.put("message", "New item created"); | ||||
| 
 | ||||
|             JSONObject headerJson = new JSONObject(); | ||||
|             headerJson.put("x-custom-header", "my custom header value"); | ||||
| 
 | ||||
|             responseJson.put("statusCode", 200); | ||||
|             responseJson.put("headers", headerJson); | ||||
|             responseJson.put("body", responseBody.toString()); | ||||
| 
 | ||||
|         } catch (ParseException pex) { | ||||
|             responseJson.put("statusCode", 400); | ||||
|             responseJson.put("exception", pex); | ||||
|         } | ||||
| 
 | ||||
|         OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); | ||||
|         writer.write(responseJson.toString()); | ||||
|         writer.close(); | ||||
|     } | ||||
| 
 | ||||
|     public void handleGetByParam(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { | ||||
| 
 | ||||
|         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); | ||||
|         JSONObject responseJson = new JSONObject(); | ||||
| 
 | ||||
|         AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); | ||||
|         DynamoDB dynamoDb = new DynamoDB(client); | ||||
| 
 | ||||
|         Item result = null; | ||||
|         try { | ||||
|             JSONObject event = (JSONObject) parser.parse(reader); | ||||
|             JSONObject responseBody = new JSONObject(); | ||||
| 
 | ||||
|             if (event.get("pathParameters") != null) { | ||||
| 
 | ||||
|                 JSONObject pps = (JSONObject) event.get("pathParameters"); | ||||
|                 if (pps.get("id") != null) { | ||||
| 
 | ||||
|                     int id = Integer.parseInt((String) pps.get("id")); | ||||
|                     result = dynamoDb.getTable(DYNAMODB_TABLE_NAME) | ||||
|                         .getItem("id", id); | ||||
|                 } | ||||
| 
 | ||||
|             } else if (event.get("queryStringParameters") != null) { | ||||
| 
 | ||||
|                 JSONObject qps = (JSONObject) event.get("queryStringParameters"); | ||||
|                 if (qps.get("id") != null) { | ||||
| 
 | ||||
|                     int id = Integer.parseInt((String) qps.get("id")); | ||||
|                     result = dynamoDb.getTable(DYNAMODB_TABLE_NAME) | ||||
|                         .getItem("id", id); | ||||
|                 } | ||||
|             } | ||||
|             if (result != null) { | ||||
| 
 | ||||
|                 Person person = new Person(result.toJSON()); | ||||
|                 responseBody.put("Person", person); | ||||
|                 responseJson.put("statusCode", 200); | ||||
|             } else { | ||||
| 
 | ||||
|                 responseBody.put("message", "No item found"); | ||||
|                 responseJson.put("statusCode", 404); | ||||
|             } | ||||
| 
 | ||||
|             JSONObject headerJson = new JSONObject(); | ||||
|             headerJson.put("x-custom-header", "my custom header value"); | ||||
| 
 | ||||
|             responseJson.put("headers", headerJson); | ||||
|             responseJson.put("body", responseBody.toString()); | ||||
| 
 | ||||
|         } catch (ParseException pex) { | ||||
|             responseJson.put("statusCode", 400); | ||||
|             responseJson.put("exception", pex); | ||||
|         } | ||||
| 
 | ||||
|         OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); | ||||
|         writer.write(responseJson.toString()); | ||||
|         writer.close(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,38 @@ | ||||
| package com.baeldung.lambda.apigateway.model; | ||||
| 
 | ||||
| import com.google.gson.Gson; | ||||
| import com.google.gson.GsonBuilder; | ||||
| 
 | ||||
| public class Person { | ||||
| 
 | ||||
|     private int id; | ||||
|     private String name; | ||||
| 
 | ||||
|     public Person(String json) { | ||||
|         Gson gson = new Gson(); | ||||
|         Person request = gson.fromJson(json, Person.class); | ||||
|         this.id = request.getId(); | ||||
|         this.name = request.getName(); | ||||
|     } | ||||
| 
 | ||||
|     public String toString() { | ||||
|         final Gson gson = new GsonBuilder().setPrettyPrinting().create(); | ||||
|         return gson.toJson(this); | ||||
|     } | ||||
| 
 | ||||
|     public int getId() { | ||||
|         return id; | ||||
|     } | ||||
| 
 | ||||
|     public void setId(int id) { | ||||
|         this.id = id; | ||||
|     } | ||||
| 
 | ||||
|     public String getName() { | ||||
|         return name; | ||||
|     } | ||||
| 
 | ||||
|     public void setName(String name) { | ||||
|         this.name = name; | ||||
|     } | ||||
| } | ||||
| @ -3,8 +3,8 @@ | ||||
| 	xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"  | ||||
| 	xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"> | ||||
| 	<description>Baeldung custom PMD rules</description> | ||||
| 	<rule name="UnitTestMustFollowNamingConventionRule" message="Test class name doesn't follow the naming convention" class="org.baeldung.pmd.UnitTestNamingConventionRule"> | ||||
| 	<rule name="UnitTestMustFollowNamingConventionRule" message="Unit test class names need to end in 'UnitTest', integration tests with 'IntegrationTest', etc " class="org.baeldung.pmd.UnitTestNamingConventionRule"> | ||||
| 		<description>Test does not follow Baeldung naming convention</description> | ||||
| 		<priority>3</priority> | ||||
| 	</rule> | ||||
| </ruleset> | ||||
| </ruleset> | ||||
|  | ||||
| @ -1,2 +1,3 @@ | ||||
| ### Relevant Articles: | ||||
| - [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj) | ||||
| - [An Introduction to CDI (Contexts and Dependency Injection) in Java](http://www.baeldung.com/java-ee-cdi) | ||||
|  | ||||
| @ -53,3 +53,6 @@ | ||||
| - [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) | ||||
| - [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) | ||||
| - [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) | ||||
| - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) | ||||
| - [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end) | ||||
| - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) | ||||
|  | ||||
| @ -0,0 +1,54 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import java.time.Duration; | ||||
| import java.time.Instant; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.ZonedDateTime; | ||||
| import java.time.temporal.ChronoUnit; | ||||
| import java.util.Calendar; | ||||
| import java.util.Date; | ||||
| 
 | ||||
| import org.apache.commons.lang3.time.DateUtils; | ||||
| 
 | ||||
| public class AddHoursToDate { | ||||
| 
 | ||||
|     public Date addHoursToJavaUtilDate(Date date, int hours) { | ||||
|         Calendar calendar = Calendar.getInstance(); | ||||
|         calendar.setTime(date); | ||||
|         calendar.add(Calendar.HOUR_OF_DAY, hours); | ||||
|         return calendar.getTime(); | ||||
|     } | ||||
| 
 | ||||
|     public Date addHoursToDateUsingInstant(Date date, int hours) { | ||||
|         return Date.from(date.toInstant() | ||||
|             .plus(Duration.ofHours(hours))); | ||||
|     } | ||||
| 
 | ||||
|     public LocalDateTime addHoursToLocalDateTime(LocalDateTime localDateTime, int hours) { | ||||
|         return localDateTime.plusHours(hours); | ||||
|     } | ||||
| 
 | ||||
|     public LocalDateTime subtractHoursToLocalDateTime(LocalDateTime localDateTime, int hours) { | ||||
|         return localDateTime.minusHours(hours); | ||||
|     } | ||||
| 
 | ||||
|     public ZonedDateTime addHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) { | ||||
|         return zonedDateTime.plusHours(hours); | ||||
|     } | ||||
| 
 | ||||
|     public ZonedDateTime subtractHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) { | ||||
|         return zonedDateTime.minusHours(hours); | ||||
|     } | ||||
| 
 | ||||
|     public Instant addHoursToInstant(Instant instant, int hours) { | ||||
|         return instant.plus(hours, ChronoUnit.HOURS); | ||||
|     } | ||||
| 
 | ||||
|     public Instant subtractHoursToInstant(Instant instant, int hours) { | ||||
|         return instant.minus(hours, ChronoUnit.HOURS); | ||||
|     } | ||||
| 
 | ||||
|     public Date addHoursWithApacheCommons(Date date, int hours) { | ||||
|         return DateUtils.addHours(date, hours); | ||||
|     } | ||||
| } | ||||
| @ -3,6 +3,7 @@ package com.baeldung.datetime; | ||||
| import java.time.DayOfWeek; | ||||
| import java.time.LocalDate; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.LocalTime; | ||||
| import java.time.temporal.ChronoUnit; | ||||
| import java.time.temporal.TemporalAdjusters; | ||||
| 
 | ||||
| @ -43,4 +44,30 @@ class UseLocalDate { | ||||
|         LocalDateTime startofDay = localDate.atStartOfDay(); | ||||
|         return startofDay; | ||||
|     } | ||||
| 
 | ||||
|     LocalDateTime getStartOfDayOfLocalDate(LocalDate localDate) { | ||||
|         LocalDateTime startofDay = LocalDateTime.of(localDate, LocalTime.MIDNIGHT); | ||||
|         return startofDay; | ||||
|     } | ||||
| 
 | ||||
|     LocalDateTime getStartOfDayAtMinTime(LocalDate localDate) { | ||||
|         LocalDateTime startofDay = localDate.atTime(LocalTime.MIN); | ||||
|         return startofDay; | ||||
|     } | ||||
| 
 | ||||
|     LocalDateTime getStartOfDayAtMidnightTime(LocalDate localDate) { | ||||
|         LocalDateTime startofDay = localDate.atTime(LocalTime.MIDNIGHT); | ||||
|         return startofDay; | ||||
|     } | ||||
| 
 | ||||
|     LocalDateTime getEndOfDay(LocalDate localDate) { | ||||
|         LocalDateTime endOfDay = localDate.atTime(LocalTime.MAX); | ||||
|         return endOfDay; | ||||
|     } | ||||
| 
 | ||||
|     LocalDateTime getEndOfDayFromLocalTime(LocalDate localDate) { | ||||
|         LocalDateTime endOfDate = LocalTime.MAX.atDate(localDate); | ||||
|         return endOfDate; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
|  | ||||
| @ -1,6 +1,8 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.LocalTime; | ||||
| import java.time.temporal.ChronoField; | ||||
| 
 | ||||
| public class UseLocalDateTime { | ||||
| 
 | ||||
| @ -8,4 +10,15 @@ public class UseLocalDateTime { | ||||
|         return LocalDateTime.parse(representation); | ||||
|     } | ||||
| 
 | ||||
|     LocalDateTime getEndOfDayFromLocalDateTimeDirectly(LocalDateTime localDateTime) { | ||||
|         LocalDateTime endOfDate = localDateTime.with(ChronoField.NANO_OF_DAY, LocalTime.MAX.toNanoOfDay()); | ||||
|         return endOfDate; | ||||
|     } | ||||
| 
 | ||||
|     LocalDateTime getEndOfDayFromLocalDateTime(LocalDateTime localDateTime) { | ||||
|         LocalDateTime endOfDate = localDateTime.toLocalDate() | ||||
|             .atTime(LocalTime.MAX); | ||||
|         return endOfDate; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
|  | ||||
| @ -1,12 +1,42 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import java.time.LocalDate; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.ZoneId; | ||||
| import java.time.ZonedDateTime; | ||||
| import java.time.temporal.ChronoField; | ||||
| 
 | ||||
| class UseZonedDateTime { | ||||
| 
 | ||||
|     ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { | ||||
|         return ZonedDateTime.of(localDateTime, zoneId); | ||||
|     } | ||||
| 
 | ||||
|     ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) { | ||||
|         ZonedDateTime startofDay = localDate.atStartOfDay() | ||||
|             .atZone(zone); | ||||
|         return startofDay; | ||||
|     } | ||||
| 
 | ||||
|     ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) { | ||||
|         ZonedDateTime startofDay = localDate.atStartOfDay(zone); | ||||
|         return startofDay; | ||||
|     } | ||||
| 
 | ||||
|     ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) { | ||||
|         ZonedDateTime startofDay = zonedDateTime.toLocalDateTime() | ||||
|             .toLocalDate() | ||||
|             .atStartOfDay(zonedDateTime.getZone()); | ||||
|         return startofDay; | ||||
|     } | ||||
| 
 | ||||
|     ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) { | ||||
|         ZonedDateTime startofDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0); | ||||
|         return startofDay; | ||||
|     } | ||||
| 
 | ||||
|     ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) { | ||||
|         ZonedDateTime startofDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0); | ||||
|         return startofDay; | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -0,0 +1,116 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| 
 | ||||
| import java.time.Instant; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.Month; | ||||
| import java.time.ZoneId; | ||||
| import java.time.ZonedDateTime; | ||||
| import java.util.Calendar; | ||||
| import java.util.Date; | ||||
| import java.util.GregorianCalendar; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class AddHoursToDateUnitTest { | ||||
| 
 | ||||
|     private final AddHoursToDate addHoursToDateObj = new AddHoursToDate(); | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenJavaUtilDate_whenPositiveHours_thenAddHours() { | ||||
|         Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); | ||||
|         Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime(); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursToJavaUtilDate(actualDate, 2)).isEqualTo(expectedDate); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenJavaUtilDate_whenNegativeHours_thenMinusHours() { | ||||
|         Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); | ||||
|         Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 3, 0).getTime(); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursToJavaUtilDate(actualDate, -2)).isEqualTo(expectedDate); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenJavaUtilDate_whenUsingToInstantAndPostiveHours_thenAddHours() { | ||||
|         Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); | ||||
|         Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime(); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursToDateUsingInstant(actualDate, 2)).isEqualTo(expectedDate); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenJavaUtilDate_whenUsingToInstantAndNegativeHours_thenAddHours() { | ||||
|         Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); | ||||
|         Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 3, 0).getTime(); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursToDateUsingInstant(actualDate, -2)).isEqualTo(expectedDate); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenLocalDateTime_whenUsingAddHoursToLocalDateTime_thenAddHours() { | ||||
|         LocalDateTime actualDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 5, 0); | ||||
|         LocalDateTime expectedDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 7, 0); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursToLocalDateTime(actualDateTime, 2)).isEqualTo(expectedDateTime); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenLocalDateTime_whenUsingMinusHoursToLocalDateTime_thenMinusHours() { | ||||
|         LocalDateTime actualDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 5, 0); | ||||
|         LocalDateTime expectedDateTime = LocalDateTime.of(2018, Month.JUNE, 25, 3, 0); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.subtractHoursToLocalDateTime(actualDateTime, 2)).isEqualTo(expectedDateTime); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenZonedDateTime_whenUsingAddHoursToZonedDateTime_thenAddHours() { | ||||
|         ZonedDateTime actualZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 5, 0), ZoneId.systemDefault()); | ||||
|         ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 7, 0), ZoneId.systemDefault()); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursToZonedDateTime(actualZonedDateTime, 2)).isEqualTo(expectedZonedDateTime); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenZonedDateTime_whenUsingMinusHoursToZonedDateTime_thenMinusHours() { | ||||
|         ZonedDateTime actualZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 5, 0), ZoneId.systemDefault()); | ||||
|         ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(LocalDateTime.of(2018, Month.JUNE, 25, 3, 0), ZoneId.systemDefault()); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.subtractHoursToZonedDateTime(actualZonedDateTime, 2)).isEqualTo(expectedZonedDateTime); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenJavaUtilDate_whenUsingPositiveHrsAndAddHoursWithApacheCommons_thenAddHours() { | ||||
|         Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); | ||||
|         Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime(); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursWithApacheCommons(actualDate, 2)).isEqualTo(expectedDate); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenJavaUtilDate_whenUsingNegativeHrsAndAddHoursWithApacheCommons_thenMinusHours() { | ||||
|         Date actualDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 7, 0).getTime(); | ||||
|         Date expectedDate = new GregorianCalendar(2018, Calendar.JUNE, 25, 5, 0).getTime(); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursWithApacheCommons(actualDate, -2)).isEqualTo(expectedDate); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenInstant_whenUsingAddHoursToInstant_thenAddHours() { | ||||
|         Instant actualValue = Instant.parse("2018-06-25T05:12:35Z"); | ||||
|         Instant expectedValue = Instant.parse("2018-06-25T07:12:35Z"); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.addHoursToInstant(actualValue, 2)).isEqualTo(expectedValue); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenInstant_whenUsingSubtractHoursToInstant_thenMinusHours() { | ||||
|         Instant actualValue = Instant.parse("2018-06-25T07:12:35Z"); | ||||
|         Instant expectedValue = Instant.parse("2018-06-25T05:12:35Z"); | ||||
| 
 | ||||
|         assertThat(addHoursToDateObj.subtractHoursToInstant(actualValue, 2)).isEqualTo(expectedValue); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -1,13 +1,15 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| import java.time.LocalDate; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.LocalTime; | ||||
| import java.time.Month; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| public class UseLocalDateTimeUnitTest { | ||||
| 
 | ||||
|     UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); | ||||
| @ -19,4 +21,16 @@ public class UseLocalDateTimeUnitTest { | ||||
|         assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") | ||||
|             .toLocalTime()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenLocalDateTime_whenSettingEndOfDay_thenReturnLastMomentOfDay() { | ||||
|         LocalDateTime givenTimed = LocalDateTime.parse("2018-06-23T05:55:55"); | ||||
| 
 | ||||
|         LocalDateTime endOfDayFromGivenDirectly = useLocalDateTime.getEndOfDayFromLocalDateTimeDirectly(givenTimed); | ||||
|         LocalDateTime endOfDayFromGiven = useLocalDateTime.getEndOfDayFromLocalDateTime(givenTimed); | ||||
| 
 | ||||
|         assertThat(endOfDayFromGivenDirectly).isEqualTo(endOfDayFromGiven); | ||||
|         assertThat(endOfDayFromGivenDirectly.toLocalTime()).isEqualTo(LocalTime.MAX); | ||||
|         assertThat(endOfDayFromGivenDirectly.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -1,13 +1,15 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| import java.time.DayOfWeek; | ||||
| import java.time.LocalDate; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.LocalTime; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| public class UseLocalDateUnitTest { | ||||
| 
 | ||||
|     UseLocalDate useLocalDate = new UseLocalDate(); | ||||
| @ -57,4 +59,33 @@ public class UseLocalDateUnitTest { | ||||
|         assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenLocalDate_whenSettingStartOfDay_thenReturnMidnightInAllCases() { | ||||
|         LocalDate given = LocalDate.parse("2018-06-23"); | ||||
| 
 | ||||
|         LocalDateTime startOfDayWithMethod = useLocalDate.getStartOfDay(given); | ||||
|         LocalDateTime startOfDayOfLocalDate = useLocalDate.getStartOfDayOfLocalDate(given); | ||||
|         LocalDateTime startOfDayWithMin = useLocalDate.getStartOfDayAtMinTime(given); | ||||
|         LocalDateTime startOfDayWithMidnight = useLocalDate.getStartOfDayAtMidnightTime(given); | ||||
| 
 | ||||
|         assertThat(startOfDayWithMethod).isEqualTo(startOfDayWithMin) | ||||
|             .isEqualTo(startOfDayWithMidnight) | ||||
|             .isEqualTo(startOfDayOfLocalDate) | ||||
|             .isEqualTo(LocalDateTime.parse("2018-06-23T00:00:00")); | ||||
|         assertThat(startOfDayWithMin.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT); | ||||
|         assertThat(startOfDayWithMin.toString()).isEqualTo("2018-06-23T00:00"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenLocalDate_whenSettingEndOfDay_thenReturnLastMomentOfDay() { | ||||
|         LocalDate given = LocalDate.parse("2018-06-23"); | ||||
| 
 | ||||
|         LocalDateTime endOfDayWithMax = useLocalDate.getEndOfDay(given); | ||||
|         LocalDateTime endOfDayFromLocalTime = useLocalDate.getEndOfDayFromLocalTime(given); | ||||
| 
 | ||||
|         assertThat(endOfDayWithMax).isEqualTo(endOfDayFromLocalTime); | ||||
|         assertThat(endOfDayWithMax.toLocalTime()).isEqualTo(LocalTime.MAX); | ||||
|         assertThat(endOfDayWithMax.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
|  | ||||
| @ -1,6 +1,10 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| 
 | ||||
| import java.time.LocalDate; | ||||
| import java.time.LocalDateTime; | ||||
| import java.time.LocalTime; | ||||
| import java.time.ZoneId; | ||||
| import java.time.ZonedDateTime; | ||||
| 
 | ||||
| @ -17,4 +21,25 @@ public class UseZonedDateTimeUnitTest { | ||||
|         ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); | ||||
|         Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenLocalDateOrZoned_whenSettingStartOfDay_thenReturnMidnightInAllCases() { | ||||
|         LocalDate given = LocalDate.parse("2018-06-23"); | ||||
|         ZoneId zone = ZoneId.of("Europe/Paris"); | ||||
|         ZonedDateTime zonedGiven = ZonedDateTime.of(given, LocalTime.NOON, zone); | ||||
| 
 | ||||
|         ZonedDateTime startOfOfDayWithMethod = zonedDateTime.getStartOfDay(given, zone); | ||||
|         ZonedDateTime startOfOfDayWithShorthandMethod = zonedDateTime.getStartOfDayShorthand(given, zone); | ||||
|         ZonedDateTime startOfOfDayFromZonedDateTime = zonedDateTime.getStartOfDayFromZonedDateTime(zonedGiven); | ||||
|         ZonedDateTime startOfOfDayAtMinTime = zonedDateTime.getStartOfDayAtMinTime(zonedGiven); | ||||
|         ZonedDateTime startOfOfDayAtMidnightTime = zonedDateTime.getStartOfDayAtMidnightTime(zonedGiven); | ||||
| 
 | ||||
|         assertThat(startOfOfDayWithMethod).isEqualTo(startOfOfDayWithShorthandMethod) | ||||
|             .isEqualTo(startOfOfDayFromZonedDateTime) | ||||
|             .isEqualTo(startOfOfDayAtMinTime) | ||||
|             .isEqualTo(startOfOfDayAtMidnightTime); | ||||
|         assertThat(startOfOfDayWithMethod.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT); | ||||
|         assertThat(startOfOfDayWithMethod.toLocalTime() | ||||
|             .toString()).isEqualTo("00:00"); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -0,0 +1,43 @@ | ||||
| package com.baeldung.fileToBase64StringConversion; | ||||
| 
 | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.io.File; | ||||
| import java.io.IOException; | ||||
| import java.util.Base64; | ||||
| 
 | ||||
| import org.apache.commons.io.FileUtils; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class FileToBase64StringConversionUnitTest { | ||||
| 
 | ||||
|     private String inputFilePath = "test_image.jpg"; | ||||
|     private String outputFilePath = "test_image_copy.jpg"; | ||||
| 
 | ||||
|     @Test | ||||
|     public void fileToBase64StringConversion() throws IOException { | ||||
|         //load file from /src/test/resources | ||||
|         ClassLoader classLoader = getClass().getClassLoader(); | ||||
|         File inputFile = new File(classLoader | ||||
|           .getResource(inputFilePath) | ||||
|           .getFile()); | ||||
| 
 | ||||
|         byte[] fileContent = FileUtils.readFileToByteArray(inputFile); | ||||
|         String encodedString = Base64 | ||||
|           .getEncoder() | ||||
|           .encodeToString(fileContent); | ||||
| 
 | ||||
|         //create output file | ||||
|         File outputFile = new File(inputFile | ||||
|           .getParentFile() | ||||
|           .getAbsolutePath() + File.pathSeparator + outputFilePath); | ||||
| 
 | ||||
|         // decode the string and write to file | ||||
|         byte[] decodedBytes = Base64 | ||||
|           .getDecoder() | ||||
|           .decode(encodedString); | ||||
|         FileUtils.writeByteArrayToFile(outputFile, decodedBytes); | ||||
| 
 | ||||
|         assertTrue(FileUtils.contentEquals(inputFile, outputFile)); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										
											BIN
										
									
								
								core-java-8/src/test/resources/test_image.jpg
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										
											BIN
										
									
								
								core-java-8/src/test/resources/test_image.jpg
									
									
									
									
									
										Normal file
									
								
							
										
											Binary file not shown.
										
									
								
							| After Width: | Height: | Size: 2.8 KiB | 
| @ -0,0 +1,80 @@ | ||||
| package com.baeldung.java.list; | ||||
| 
 | ||||
| import java.util.Collections; | ||||
| import java.util.List; | ||||
| import java.util.ListIterator; | ||||
| 
 | ||||
| import org.apache.commons.collections4.iterators.ReverseListIterator; | ||||
| 
 | ||||
| import com.google.common.collect.Lists; | ||||
| 
 | ||||
| /** | ||||
|  * Provides methods for iterating backward over a list. | ||||
|  */ | ||||
| public class ReverseIterator { | ||||
| 
 | ||||
|     /** | ||||
|      * Iterate using the for loop. | ||||
|      * | ||||
|      * @param list the list | ||||
|      */ | ||||
|     public void iterateUsingForLoop(final List<String> list) { | ||||
| 
 | ||||
|         for (int i = list.size(); i-- > 0; ) { | ||||
|             System.out.println(list.get(i)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     /** | ||||
|      * Iterate using the Java {@link ListIterator}. | ||||
|      * | ||||
|      * @param list the list | ||||
|      */ | ||||
|     public void iterateUsingListIterator(final List<String> list) { | ||||
| 
 | ||||
|         final ListIterator listIterator = list.listIterator(list.size()); | ||||
|         while (listIterator.hasPrevious()) { | ||||
|             System.out.println(listIterator.previous()); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     /** | ||||
|      * Iterate using Java {@link Collections} API. | ||||
|      * | ||||
|      * @param list the list | ||||
|      */ | ||||
|     public void iterateUsingCollections(final List<String> list) { | ||||
| 
 | ||||
|         Collections.reverse(list); | ||||
|         for (final String item : list) { | ||||
|             System.out.println(item); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     /** | ||||
|      * Iterate using Apache Commons {@link ReverseListIterator}. | ||||
|      * | ||||
|      * @param list the list | ||||
|      */ | ||||
|     public void iterateUsingApacheReverseListIterator(final List<String> list) { | ||||
| 
 | ||||
|         final ReverseListIterator listIterator = new ReverseListIterator(list); | ||||
|         while (listIterator.hasNext()) { | ||||
|             System.out.println(listIterator.next()); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     /** | ||||
|      * Iterate using Guava {@link Lists} API. | ||||
|      * | ||||
|      * @param list the list | ||||
|      */ | ||||
|     public void iterateUsingGuava(final List<String> list) { | ||||
| 
 | ||||
|         final List<String> reversedList = Lists.reverse(list); | ||||
|         for (final String item : reversedList) { | ||||
|             System.out.println(item); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,87 @@ | ||||
| package com.baeldung.java.list; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| import java.util.Collections; | ||||
| import java.util.List; | ||||
| import java.util.ListIterator; | ||||
| 
 | ||||
| import org.apache.commons.collections4.iterators.ReverseListIterator; | ||||
| import org.apache.commons.lang3.StringUtils; | ||||
| import org.junit.jupiter.api.BeforeEach; | ||||
| import org.junit.jupiter.api.Test; | ||||
| 
 | ||||
| import com.google.common.collect.Lists; | ||||
| 
 | ||||
| public class ReverseIteratorUnitTest { | ||||
| 
 | ||||
|     private final ReverseIterator reverseIterator = new ReverseIterator(); | ||||
| 
 | ||||
|     private List<String> list; | ||||
| 
 | ||||
|     private final String originalString = "ABCDE"; | ||||
| 
 | ||||
|     @BeforeEach | ||||
|     void setUp() { | ||||
| 
 | ||||
|         list = Lists.newArrayList("A", "B", "C", "D", "E"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     void whenIteratingUsingForLoop_thenCorrect() { | ||||
| 
 | ||||
|         String reverseString = ""; | ||||
|         for (int i = list.size(); i-- > 0; ) { | ||||
|             reverseString += list.get(i); | ||||
|         } | ||||
|         assertEquals(reverseString, StringUtils.reverse(originalString)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     void whenIteratingUsingListIterator_thenCorrect() { | ||||
| 
 | ||||
|         String reverseString = ""; | ||||
|         final ListIterator listIterator = list.listIterator(list.size()); | ||||
|         while (listIterator.hasPrevious()) { | ||||
|             reverseString += listIterator.previous(); | ||||
|         } | ||||
|         assertEquals(reverseString, StringUtils.reverse(originalString)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     void whenIteratingUsingCollections_thenCorrect() { | ||||
| 
 | ||||
|         String reverseString = ""; | ||||
|         Collections.reverse(list); | ||||
|         for (final String item : list) { | ||||
|             reverseString += item; | ||||
|         } | ||||
|         assertEquals(reverseString, StringUtils.reverse(originalString)); | ||||
| 
 | ||||
|         assertEquals("E", list.get(0)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     void whenIteratingUsingApacheReverseListIterator_thenCorrect() { | ||||
| 
 | ||||
|         String reverseString = ""; | ||||
|         final ReverseListIterator listIterator = new ReverseListIterator(list); | ||||
|         while (listIterator.hasNext()) { | ||||
|             reverseString += listIterator.next(); | ||||
|         } | ||||
|         assertEquals(reverseString, StringUtils.reverse(originalString)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     void whenIteratingUsingGuava_thenCorrect() { | ||||
| 
 | ||||
|         String reverseString = ""; | ||||
|         final List<String> reversedList = Lists.reverse(list); | ||||
|         for (final String item : reversedList) { | ||||
|             reverseString += item; | ||||
|         } | ||||
|         assertEquals(reverseString, StringUtils.reverse(originalString)); | ||||
| 
 | ||||
|         assertEquals("A", list.get(0)); | ||||
|     } | ||||
| } | ||||
| @ -220,6 +220,7 @@ | ||||
|                     <excludes> | ||||
|                         <exclude>**/*LiveTest.java</exclude> | ||||
|                         <exclude>**/*IntegrationTest.java</exclude> | ||||
|                         <exclude>**/*IntTest.java</exclude> | ||||
|                         <exclude>**/*LongRunningUnitTest.java</exclude> | ||||
|                         <exclude>**/*ManualTest.java</exclude> | ||||
|                     </excludes> | ||||
| @ -289,6 +290,7 @@ | ||||
|                                     </excludes> | ||||
|                                     <includes> | ||||
|                                         <include>**/*IntegrationTest.java</include> | ||||
|                                         <include>**/*IntTest.java</include> | ||||
|                                     </includes> | ||||
|                                 </configuration> | ||||
|                             </execution> | ||||
|  | ||||
| @ -0,0 +1,54 @@ | ||||
| package com.baeldung.symlink; | ||||
| 
 | ||||
| import java.io.IOException; | ||||
| import java.nio.charset.StandardCharsets; | ||||
| import java.nio.file.DirectoryStream; | ||||
| import java.nio.file.Files; | ||||
| import java.nio.file.Path; | ||||
| import java.nio.file.Paths; | ||||
| import static java.nio.file.StandardOpenOption.*; | ||||
| import java.util.stream.IntStream; | ||||
| 
 | ||||
| public class SymLinkExample { | ||||
| 
 | ||||
|     public void createSymbolicLink(Path link, Path target) throws IOException { | ||||
|         if (Files.exists(link)) { | ||||
|             Files.delete(link); | ||||
|         } | ||||
|         Files.createSymbolicLink(link, target); | ||||
|     } | ||||
| 
 | ||||
|     public void createHardLink(Path link, Path target) throws IOException { | ||||
|         if (Files.exists(link)) { | ||||
|             Files.delete(link); | ||||
|         } | ||||
|         Files.createLink(link, target); | ||||
|     } | ||||
| 
 | ||||
|     public Path createTextFile() throws IOException { | ||||
|         byte[] content = IntStream.range(0, 10000) | ||||
|             .mapToObj(i -> i + System.lineSeparator()) | ||||
|             .reduce("", String::concat) | ||||
|             .getBytes(StandardCharsets.UTF_8); | ||||
|         Path filePath = Paths.get(".", "target_link.txt"); | ||||
|         Files.write(filePath, content, CREATE, TRUNCATE_EXISTING); | ||||
|         return filePath; | ||||
|     } | ||||
| 
 | ||||
|     public void printLinkFiles(Path path) throws IOException { | ||||
|         try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { | ||||
|             for (Path file : stream) { | ||||
|                 if (Files.isDirectory(file)) { | ||||
|                     printLinkFiles(file); | ||||
|                 } else if (Files.isSymbolicLink(file)) { | ||||
|                     System.out.format("File link '%s' with target '%s'%n", file, Files.readSymbolicLink(file)); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public static void main(String[] args) throws IOException { | ||||
|         new SymLinkExample().printLinkFiles(Paths.get(".")); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.symlink; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| import java.io.IOException; | ||||
| import java.nio.file.Files; | ||||
| import java.nio.file.Path; | ||||
| import java.nio.file.Paths; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class SymLinkExampleUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenUsingFiles_thenCreateSymbolicLink() throws IOException { | ||||
|         SymLinkExample example = new SymLinkExample(); | ||||
|         Path filePath = example.createTextFile(); | ||||
|         Path linkPath = Paths.get(".", "symbolic_link.txt"); | ||||
|         example.createSymbolicLink(linkPath, filePath); | ||||
|         assertTrue(Files.isSymbolicLink(linkPath)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenUsingFiles_thenCreateHardLink() throws IOException { | ||||
|         SymLinkExample example = new SymLinkExample(); | ||||
|         Path filePath = example.createTextFile(); | ||||
|         Path linkPath = Paths.get(".", "hard_link.txt"); | ||||
|         example.createHardLink(linkPath, filePath); | ||||
|         assertFalse(Files.isSymbolicLink(linkPath)); | ||||
|         assertEquals(filePath.toFile() | ||||
|             .length(), | ||||
|             linkPath.toFile() | ||||
|                 .length()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -14,8 +14,10 @@ import org.slf4j.LoggerFactory; | ||||
| import java.io.*; | ||||
| import java.nio.charset.Charset; | ||||
| import java.nio.charset.StandardCharsets; | ||||
| import java.nio.file.Path; | ||||
| import java.nio.file.StandardCopyOption; | ||||
| import java.util.Scanner; | ||||
| import java.util.UUID; | ||||
| 
 | ||||
| import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; | ||||
| import static org.hamcrest.Matchers.equalTo; | ||||
| @ -111,6 +113,19 @@ public class JavaInputStreamToXUnitTest { | ||||
| 
 | ||||
|         assertThat(writer.toString(), equalTo(originalString)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public final void givenUsingTempFile_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException { | ||||
|         final String originalString = randomAlphabetic(DEFAULT_SIZE); | ||||
|         final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); | ||||
| 
 | ||||
|         // When | ||||
|         Path tempFile = java.nio.file.Files.createTempDirectory("").resolve(UUID.randomUUID().toString() + ".tmp"); | ||||
|         java.nio.file.Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING); | ||||
|         String result = new String(java.nio.file.Files.readAllBytes(tempFile)); | ||||
| 
 | ||||
|         assertThat(result, equalTo(originalString)); | ||||
|     } | ||||
| 
 | ||||
|     // tests - InputStream to byte[] | ||||
| 
 | ||||
|  | ||||
| @ -353,6 +353,7 @@ | ||||
|                                     </excludes> | ||||
|                                     <includes> | ||||
|                                         <include>**/*IntegrationTest.java</include> | ||||
|                                         <include>**/*IntTest.java</include> | ||||
|                                     </includes> | ||||
|                                 </configuration> | ||||
|                             </execution> | ||||
|  | ||||
| @ -160,3 +160,10 @@ | ||||
| - [Guide to the super Java Keyword](http://www.baeldung.com/java-super) | ||||
| - [Guide to the this Java Keyword](http://www.baeldung.com/java-this) | ||||
| - [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays) | ||||
| - [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class) | ||||
| - [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day) | ||||
| - [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time) | ||||
| - [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case) | ||||
| - [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension) | ||||
| - [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object) | ||||
| - [Console I/O in Java](http://www.baeldung.com/java-console-input-output) | ||||
|  | ||||
| @ -10,8 +10,8 @@ | ||||
|     <parent> | ||||
|         <groupId>com.baeldung</groupId> | ||||
|         <artifactId>parent-java</artifactId> | ||||
|     	<version>0.0.1-SNAPSHOT</version> | ||||
|     	<relativePath>../parent-java</relativePath> | ||||
|         <version>0.0.1-SNAPSHOT</version> | ||||
|         <relativePath>../parent-java</relativePath> | ||||
|     </parent> | ||||
| 
 | ||||
|     <dependencies> | ||||
| @ -197,11 +197,11 @@ | ||||
|             <groupId>javax.mail</groupId> | ||||
|             <artifactId>mail</artifactId> | ||||
|             <version>${javax.mail.version}</version> | ||||
|         </dependency> | ||||
|       </dependency> | ||||
|         <dependency> | ||||
|             <groupId>javax.mail</groupId> | ||||
|             <artifactId>mail</artifactId> | ||||
|             <version>1.5.0-b01</version> | ||||
|             <groupId>com.ibm.icu</groupId> | ||||
|             <artifactId>icu4j</artifactId> | ||||
|             <version>${icu4j.version}</version> | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
| 
 | ||||
| @ -222,6 +222,7 @@ | ||||
|                     <excludes> | ||||
|                         <exclude>**/*LiveTest.java</exclude> | ||||
|                         <exclude>**/*IntegrationTest.java</exclude> | ||||
|                         <exclude>**/*IntTest.java</exclude> | ||||
|                         <exclude>**/*LongRunningUnitTest.java</exclude> | ||||
|                         <exclude>**/*ManualTest.java</exclude> | ||||
|                     </excludes> | ||||
| @ -249,6 +250,7 @@ | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-jar-plugin</artifactId> | ||||
|                 <version>${maven-jar-plugin.version}</version> | ||||
|                 <configuration> | ||||
|                     <archive> | ||||
|                         <manifest> | ||||
| @ -287,6 +289,7 @@ | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-shade-plugin</artifactId> | ||||
|                 <version>${maven-shade-plugin.version}</version> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <goals> | ||||
| @ -308,6 +311,7 @@ | ||||
|             <plugin> | ||||
|                 <groupId>com.jolira</groupId> | ||||
|                 <artifactId>onejar-maven-plugin</artifactId> | ||||
|                 <version>${onejar-maven-plugin.version}</version> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <configuration> | ||||
| @ -325,6 +329,7 @@ | ||||
|             <plugin> | ||||
|                 <groupId>org.springframework.boot</groupId> | ||||
|                 <artifactId>spring-boot-maven-plugin</artifactId> | ||||
|                 <version>${spring-boot-maven-plugin.version}</version> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <goals> | ||||
| @ -387,6 +392,7 @@ | ||||
|                                     </excludes> | ||||
|                                     <includes> | ||||
|                                         <include>**/*IntegrationTest.java</include> | ||||
|                                         <include>**/*IntTest.java</include> | ||||
|                                     </includes> | ||||
|                                 </configuration> | ||||
|                             </execution> | ||||
| @ -471,6 +477,11 @@ | ||||
|         <maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version> | ||||
|         <exec-maven-plugin.version>1.6.0</exec-maven-plugin.version> | ||||
|         <javax.mail.version>1.5.0-b01</javax.mail.version> | ||||
|         <maven-jar-plugin.version>3.0.2</maven-jar-plugin.version> | ||||
|         <onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version> | ||||
|         <maven-shade-plugin.version>3.1.1</maven-shade-plugin.version> | ||||
|         <spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version> | ||||
|         <icu4j.version>61.1</icu4j.version> | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
| @ -0,0 +1,26 @@ | ||||
| package com.baeldung.console; | ||||
| 
 | ||||
| import java.io.Console; | ||||
| 
 | ||||
| public class ConsoleConsoleClass { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         Console console = System.console(); | ||||
| 
 | ||||
|         if (console == null) { | ||||
|             System.out.print("No console available"); | ||||
|             return; | ||||
|         } | ||||
| 
 | ||||
|         String progLanguauge = console.readLine("Enter your favourite programming language: "); | ||||
|         console.printf(progLanguauge + " is very interesting!"); | ||||
| 
 | ||||
|         char[] pass = console.readPassword("To finish, enter password: "); | ||||
|          | ||||
|         if ("BAELDUNG".equals(pass.toString().toUpperCase())) | ||||
|             console.printf("Good! Regards!"); | ||||
|         else  | ||||
|             console.printf("Nice try. Regards."); | ||||
| 
 | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,76 @@ | ||||
| package com.baeldung.console; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStreamReader; | ||||
| import java.util.Scanner; | ||||
| import java.util.regex.Pattern; | ||||
| 
 | ||||
| public class ConsoleScannerClass { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         System.out.println("Please enter your name and surname: "); | ||||
| 
 | ||||
|         Scanner scanner = new Scanner(System.in); | ||||
| 
 | ||||
|         String nameSurname = scanner.nextLine(); | ||||
| 
 | ||||
|         System.out.println("Please enter your gender: "); | ||||
| 
 | ||||
|         char gender = scanner.next().charAt(0); | ||||
| 
 | ||||
|         System.out.println("Please enter your age: "); | ||||
| 
 | ||||
|         int age = scanner.nextInt(); | ||||
| 
 | ||||
|         System.out.println("Please enter your height in meters: "); | ||||
| 
 | ||||
|         double height = scanner.nextDouble(); | ||||
| 
 | ||||
|         System.out.println(nameSurname + ", " + age + ", is a great " + (gender == 'm' ? "guy" : "girl") + " with " + height + " meters height" + " and " + (gender == 'm' ? "he" : "she") + " reads Baeldung."); | ||||
| 
 | ||||
|         System.out.print("Have a good"); | ||||
|         System.out.print(" one!"); | ||||
| 
 | ||||
|         System.out.println("\nPlease enter number of years of experience as a developer: "); | ||||
| 
 | ||||
|         BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in)); | ||||
| 
 | ||||
|         int i = 0; | ||||
| 
 | ||||
|         try { | ||||
|             i = Integer.parseInt(buffReader.readLine()); | ||||
|         } catch (NumberFormatException e) { | ||||
|             // TODO Auto-generated catch block | ||||
|             e.printStackTrace(); | ||||
|         } catch (IOException e) { | ||||
|             // TODO Auto-generated catch block | ||||
|             e.printStackTrace(); | ||||
|         } | ||||
| 
 | ||||
|         System.out.println("You are a " + (i > 5 ? "great" : "good") + " developer!"); | ||||
| 
 | ||||
|         int sum = 0, count = 0; | ||||
| 
 | ||||
|         System.out.println("Please enter your college degrees. To finish, enter baeldung website url"); | ||||
| 
 | ||||
|         while (scanner.hasNextInt()) { | ||||
|             int nmbr = scanner.nextInt(); | ||||
|             sum += nmbr; | ||||
|             count++; | ||||
|         } | ||||
|         int mean = sum / count; | ||||
| 
 | ||||
|         System.out.println("Your average degree is " + mean); | ||||
| 
 | ||||
|         if (scanner.hasNext(Pattern.compile("www.baeldung.com"))) | ||||
|             System.out.println("Correct!"); | ||||
|         else | ||||
|             System.out.println("Baeldung website url is www.baeldung.com"); | ||||
| 
 | ||||
|         if (scanner != null) | ||||
|             scanner.close(); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,43 @@ | ||||
| package com.baeldung.customexception; | ||||
| 
 | ||||
| import java.io.File; | ||||
| import java.io.FileNotFoundException; | ||||
| import java.util.Scanner; | ||||
| 
 | ||||
| public class FileManager { | ||||
| 
 | ||||
|     public static String getFirstLine(String fileName) throws IncorrectFileNameException { | ||||
|         try (Scanner file = new Scanner(new File(fileName))) { | ||||
|             if (file.hasNextLine()) { | ||||
|                 return file.nextLine(); | ||||
|             } else { | ||||
|                 throw new IllegalArgumentException("Non readable file"); | ||||
|             } | ||||
|         } catch (FileNotFoundException err) { | ||||
|             if (!isCorrectFileName(fileName)) { | ||||
|                 throw new IncorrectFileNameException("Incorrect filename : " + fileName, err); | ||||
|             } | ||||
|             // Logging etc | ||||
|         } catch (IllegalArgumentException err) { | ||||
|             if (!containsExtension(fileName)) { | ||||
|                 throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err); | ||||
|             } | ||||
|             // Other error cases and logging | ||||
|         } | ||||
|         return "Default First Line"; | ||||
|     } | ||||
| 
 | ||||
|     private static boolean containsExtension(String fileName) { | ||||
|         if (fileName.contains(".txt") || fileName.contains(".doc")) | ||||
|             return true; | ||||
|         return false; | ||||
|     } | ||||
| 
 | ||||
|     private static boolean isCorrectFileName(String fileName) { | ||||
|         if (fileName.equals("wrongFileName.txt")) | ||||
|             return false; | ||||
|         else | ||||
|             return true; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,9 @@ | ||||
| package com.baeldung.customexception; | ||||
| 
 | ||||
| public class IncorrectFileExtensionException extends RuntimeException{ | ||||
|     private static final long serialVersionUID = 1L; | ||||
| 
 | ||||
|     public IncorrectFileExtensionException(String errorMessage, Throwable err) { | ||||
|         super(errorMessage, err); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,9 @@ | ||||
| package com.baeldung.customexception; | ||||
| 
 | ||||
| public class IncorrectFileNameException extends Exception { | ||||
|     private static final long serialVersionUID = 1L; | ||||
|      | ||||
|     public IncorrectFileNameException(String errorMessage, Throwable err) { | ||||
|         super(errorMessage, err); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,30 @@ | ||||
| package com.baeldung.date; | ||||
| 
 | ||||
| import java.text.ParseException; | ||||
| import java.text.SimpleDateFormat; | ||||
| import java.time.LocalDate; | ||||
| import java.util.Calendar; | ||||
| import java.util.Date; | ||||
| 
 | ||||
| public class DateWithoutTime { | ||||
| 
 | ||||
|     public static Date getDateWithoutTimeUsingCalendar() { | ||||
|         Calendar calendar = Calendar.getInstance(); | ||||
|         calendar.set(Calendar.HOUR_OF_DAY, 0); | ||||
|         calendar.set(Calendar.MINUTE, 0); | ||||
|         calendar.set(Calendar.SECOND, 0); | ||||
|         calendar.set(Calendar.MILLISECOND, 0); | ||||
| 
 | ||||
|         return calendar.getTime(); | ||||
|     } | ||||
| 
 | ||||
|     public static Date getDateWithoutTimeUsingFormat() throws ParseException { | ||||
|         SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); | ||||
|         return formatter.parse(formatter.format(new Date())); | ||||
|     } | ||||
| 
 | ||||
|     public static LocalDate getLocalDate() { | ||||
|         return LocalDate.now(); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,28 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import java.util.Calendar; | ||||
| import java.util.Date; | ||||
| 
 | ||||
| public class DateExtractYearMonthDayIntegerValues { | ||||
| 
 | ||||
|     int getYear(Date date) { | ||||
|         Calendar calendar = Calendar.getInstance(); | ||||
|         calendar.setTime(date); | ||||
| 
 | ||||
|         return calendar.get(Calendar.YEAR); | ||||
|     } | ||||
| 
 | ||||
|     int getMonth(Date date) { | ||||
|         Calendar calendar = Calendar.getInstance(); | ||||
|         calendar.setTime(date); | ||||
| 
 | ||||
|         return calendar.get(Calendar.MONTH); | ||||
|     } | ||||
| 
 | ||||
|     int getDay(Date date) { | ||||
|         Calendar calendar = Calendar.getInstance(); | ||||
|         calendar.setTime(date); | ||||
| 
 | ||||
|         return calendar.get(Calendar.DAY_OF_MONTH); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,18 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import java.time.LocalDate; | ||||
| 
 | ||||
| public class LocalDateExtractYearMonthDayIntegerValues { | ||||
| 
 | ||||
|     int getYear(LocalDate localDate) { | ||||
|         return localDate.getYear(); | ||||
|     } | ||||
| 
 | ||||
|     int getMonth(LocalDate localDate) { | ||||
|         return localDate.getMonthValue(); | ||||
|     } | ||||
| 
 | ||||
|     int getDay(LocalDate localDate) { | ||||
|         return localDate.getDayOfMonth(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,18 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| 
 | ||||
| public class LocalDateTimeExtractYearMonthDayIntegerValues { | ||||
| 
 | ||||
|     int getYear(LocalDateTime localDateTime) { | ||||
|         return localDateTime.getYear(); | ||||
|     } | ||||
| 
 | ||||
|     int getMonth(LocalDateTime localDateTime) { | ||||
|         return localDateTime.getMonthValue(); | ||||
|     } | ||||
| 
 | ||||
|     int getDay(LocalDateTime localDateTime) { | ||||
|         return localDateTime.getDayOfMonth(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,18 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import java.time.OffsetDateTime; | ||||
| 
 | ||||
| public class OffsetDateTimeExtractYearMonthDayIntegerValues { | ||||
| 
 | ||||
|     int getYear(OffsetDateTime offsetDateTime) { | ||||
|         return offsetDateTime.getYear(); | ||||
|     } | ||||
| 
 | ||||
|     int getMonth(OffsetDateTime offsetDateTime) { | ||||
|         return offsetDateTime.getMonthValue(); | ||||
|     } | ||||
| 
 | ||||
|     int getDay(OffsetDateTime offsetDateTime) { | ||||
|         return offsetDateTime.getDayOfMonth(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,18 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import java.time.ZonedDateTime; | ||||
| 
 | ||||
| public class ZonedDateTimeExtractYearMonthDayIntegerValues { | ||||
| 
 | ||||
|     int getYear(ZonedDateTime zonedDateTime) { | ||||
|         return zonedDateTime.getYear(); | ||||
|     } | ||||
| 
 | ||||
|     int getMonth(ZonedDateTime zonedDateTime) { | ||||
|         return zonedDateTime.getMonthValue(); | ||||
|     } | ||||
| 
 | ||||
|     int getDay(ZonedDateTime zonedDateTime) { | ||||
|         return zonedDateTime.getDayOfMonth(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,60 @@ | ||||
| package com.baeldung.encrypt; | ||||
| 
 | ||||
| import javax.crypto.*; | ||||
| import javax.crypto.spec.IvParameterSpec; | ||||
| import java.io.*; | ||||
| import java.security.InvalidAlgorithmParameterException; | ||||
| import java.security.InvalidKeyException; | ||||
| import java.security.NoSuchAlgorithmException; | ||||
| 
 | ||||
| class FileEncrypterDecrypter { | ||||
| 
 | ||||
|     private SecretKey secretKey; | ||||
|     private Cipher cipher; | ||||
| 
 | ||||
|     FileEncrypterDecrypter(SecretKey secretKey, String cipher) throws NoSuchPaddingException, NoSuchAlgorithmException { | ||||
|         this.secretKey = secretKey; | ||||
|         this.cipher = Cipher.getInstance(cipher); | ||||
|     } | ||||
| 
 | ||||
|     void encrypt(String content, String fileName) throws InvalidKeyException, IOException { | ||||
|         cipher.init(Cipher.ENCRYPT_MODE, secretKey); | ||||
|         byte[] iv = cipher.getIV(); | ||||
| 
 | ||||
|         try ( | ||||
|                 FileOutputStream fileOut = new FileOutputStream(fileName); | ||||
|                 CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher) | ||||
|         ) { | ||||
|             fileOut.write(iv); | ||||
|             cipherOut.write(content.getBytes()); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     String decrypt(String fileName) throws InvalidAlgorithmParameterException, InvalidKeyException, IOException { | ||||
| 
 | ||||
|         String content; | ||||
| 
 | ||||
|         try (FileInputStream fileIn = new FileInputStream(fileName)) { | ||||
|             byte[] fileIv = new byte[16]; | ||||
|             fileIn.read(fileIv); | ||||
|             cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(fileIv)); | ||||
| 
 | ||||
|             try ( | ||||
|                     CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher); | ||||
|                     InputStreamReader inputReader = new InputStreamReader(cipherIn); | ||||
|                     BufferedReader reader = new BufferedReader(inputReader) | ||||
|                 ) { | ||||
| 
 | ||||
|                 StringBuilder sb = new StringBuilder(); | ||||
|                 String line; | ||||
|                 while ((line = reader.readLine()) != null) { | ||||
|                     sb.append(line); | ||||
|                 } | ||||
|                 content = sb.toString(); | ||||
|             } | ||||
| 
 | ||||
|         } | ||||
|         return content; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,20 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class Arithmetic { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(Arithmetic.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         try { | ||||
|             int result = 30 / 0; // Trying to divide by zero | ||||
|         } catch (ArithmeticException e) { | ||||
|             LOGGER.error("ArithmeticException caught!"); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,24 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class ArrayIndexOutOfBounds { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(ArrayIndexOutOfBounds.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         int[] nums = new int[] { 1, 2, 3 }; | ||||
| 
 | ||||
|         try { | ||||
|             int numFromNegativeIndex = nums[-1]; // Trying to access at negative index | ||||
|             int numFromGreaterIndex = nums[4]; // Trying to access at greater index | ||||
|             int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array | ||||
|         } catch (ArrayIndexOutOfBoundsException e) { | ||||
|             LOGGER.error("ArrayIndexOutOfBoundsException caught"); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| class Animal { | ||||
| 
 | ||||
| } | ||||
| 
 | ||||
| class Dog extends Animal { | ||||
| 
 | ||||
| } | ||||
| 
 | ||||
| class Lion extends Animal { | ||||
| 
 | ||||
| } | ||||
| 
 | ||||
| public class ClassCast { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(ClassCast.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         try { | ||||
|             Animal animalOne = new Dog(); // At runtime the instance is dog | ||||
|             Dog bruno = (Dog) animalOne; // Downcasting | ||||
| 
 | ||||
|             Animal animalTwo = new Lion(); // At runtime the instance is animal | ||||
|             Dog tommy = (Dog) animalTwo; // Downcasting | ||||
|         } catch (ClassCastException e) { | ||||
|             LOGGER.error("ClassCastException caught!"); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,25 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.File; | ||||
| import java.io.FileNotFoundException; | ||||
| import java.io.FileReader; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class FileNotFound { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(FileNotFound.class); | ||||
|      | ||||
|     public static void main(String[] args) { | ||||
|          | ||||
|         BufferedReader reader = null; | ||||
|         try { | ||||
|             reader = new BufferedReader(new FileReader(new File("/invalid/file/location"))); | ||||
|         } catch (FileNotFoundException e) { | ||||
|             LOGGER.error("FileNotFoundException caught!"); | ||||
|         } | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -0,0 +1,28 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class GlobalExceptionHandler { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         Handler globalExceptionHandler = new Handler(); | ||||
|         Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler); | ||||
|         new GlobalExceptionHandler().performArithmeticOperation(10, 0); | ||||
|     } | ||||
| 
 | ||||
|     public int performArithmeticOperation(int num1, int num2) { | ||||
|         return num1/num2; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| 
 | ||||
| class Handler implements Thread.UncaughtExceptionHandler { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(Handler.class); | ||||
| 
 | ||||
|     public void uncaughtException(Thread t, Throwable e) { | ||||
|         LOGGER.info("Unhandled exception caught!"); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,18 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class IllegalArgument { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(IllegalArgument.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         try { | ||||
|             Thread.sleep(-1000); | ||||
|         } catch (InterruptedException e) { | ||||
|             LOGGER.error("IllegalArgumentException caught!"); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,32 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.Iterator; | ||||
| import java.util.List; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class IllegalState { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(IllegalState.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         List<Integer> intList = new ArrayList<>(); | ||||
| 
 | ||||
|         for (int i = 0; i < 10; i++) { | ||||
|             intList.add(i); | ||||
|         } | ||||
| 
 | ||||
|         Iterator<Integer> intListIterator = intList.iterator(); // Initialized with index at -1 | ||||
| 
 | ||||
|         try { | ||||
|             intListIterator.remove(); // IllegalStateException | ||||
|         } catch (IllegalStateException e) { | ||||
|             LOGGER.error("IllegalStateException caught!"); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,28 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| class ChildThread extends Thread { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(ChildThread.class); | ||||
| 
 | ||||
|     public void run() { | ||||
|         try { | ||||
|             Thread.sleep(1000); | ||||
|         } catch (InterruptedException e) { | ||||
|             LOGGER.error("InterruptedException caught!"); | ||||
|         } | ||||
|     } | ||||
|      | ||||
| } | ||||
| 
 | ||||
| public class InterruptedExceptionExample { | ||||
| 
 | ||||
|     public static void main(String[] args) throws InterruptedException { | ||||
|         ChildThread childThread = new ChildThread(); | ||||
|         childThread.start(); | ||||
|         childThread.interrupt(); | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -0,0 +1,25 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import java.net.MalformedURLException; | ||||
| import java.net.URL; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class MalformedURL { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(MalformedURL.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         URL baeldungURL = null; | ||||
| 
 | ||||
|         try { | ||||
|             baeldungURL = new URL("malformedurl"); | ||||
|         } catch (MalformedURLException e) { | ||||
|             LOGGER.error("MalformedURLException caught!"); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class NullPointer { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(NullPointer.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         Person personObj = null; | ||||
| 
 | ||||
|         try { | ||||
|             String name = personObj.personName; // Accessing the field of a null object | ||||
|             personObj.personName = "Jon Doe"; // Modifying the field of a null object | ||||
|         } catch (NullPointerException e) { | ||||
|             LOGGER.error("NullPointerException caught!"); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| class Person { | ||||
| 
 | ||||
|     public String personName; | ||||
| 
 | ||||
|     public String getPersonName() { | ||||
|         return personName; | ||||
|     } | ||||
| 
 | ||||
|     public void setPersonName(String personName) { | ||||
|         this.personName = personName; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,23 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class NumberFormat { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(NumberFormat.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         String str1 = "100ABCD"; | ||||
| 
 | ||||
|         try { | ||||
|             int x = Integer.parseInt(str1); // Converting string with inappropriate format | ||||
|             int y = Integer.valueOf(str1); | ||||
|         } catch (NumberFormatException e) { | ||||
|             LOGGER.error("NumberFormatException caught!"); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,25 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import java.text.DateFormat; | ||||
| import java.text.ParseException; | ||||
| import java.text.SimpleDateFormat; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class ParseExceptionExample { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(ParseExceptionExample.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         DateFormat format = new SimpleDateFormat("MM, dd, yyyy"); | ||||
| 
 | ||||
|         try { | ||||
|             format.parse("01, , 2010"); | ||||
|         } catch (ParseException e) { | ||||
|             LOGGER.error("ParseException caught!"); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,23 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class StringIndexOutOfBounds { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(StringIndexOutOfBounds.class); | ||||
|      | ||||
|     public static void main(String[] args) { | ||||
| 
 | ||||
|         String str = "Hello World"; | ||||
| 
 | ||||
|         try { | ||||
|             char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index | ||||
|             char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string | ||||
|         } catch (StringIndexOutOfBoundsException e) { | ||||
|            LOGGER.error("StringIndexOutOfBoundsException caught"); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,69 @@ | ||||
| package com.baeldung.gregorian.calendar; | ||||
| 
 | ||||
| import java.time.format.DateTimeFormatter; | ||||
| import java.util.Calendar; | ||||
| import java.util.Collections; | ||||
| import java.util.Date; | ||||
| import java.util.GregorianCalendar; | ||||
| import java.util.HashSet; | ||||
| import java.util.Locale; | ||||
| import java.util.Set; | ||||
| import java.util.TimeZone; | ||||
| 
 | ||||
| import javax.xml.datatype.DatatypeConfigurationException; | ||||
| import javax.xml.datatype.DatatypeFactory; | ||||
| import javax.xml.datatype.XMLGregorianCalendar; | ||||
| 
 | ||||
| public class GregorianCalendarExample { | ||||
| 
 | ||||
|     | ||||
|     public Date setMonth(GregorianCalendar calendar, int amount) { | ||||
|         calendar.set(Calendar.MONTH, amount); | ||||
|         return calendar.getTime(); | ||||
|     } | ||||
| 
 | ||||
|     | ||||
|     public Date rollAdd(GregorianCalendar calendar, int amount) { | ||||
|         calendar.roll(GregorianCalendar.MONTH, amount); | ||||
|         return calendar.getTime(); | ||||
|     } | ||||
| 
 | ||||
|     public  boolean isLeapYearExample(int year) { | ||||
|         GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); | ||||
|         return cal.isLeapYear(year); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
| 
 | ||||
|     public Date subtractDays(GregorianCalendar calendar, int daysToSubtract) { | ||||
|         GregorianCalendar cal = calendar; | ||||
|         cal.add(Calendar.DATE, -daysToSubtract); | ||||
|         return cal.getTime(); | ||||
|     } | ||||
| 
 | ||||
|     public Date addDays(GregorianCalendar calendar, int daysToAdd) { | ||||
|         GregorianCalendar cal = calendar; | ||||
|         cal.add(Calendar.DATE, daysToAdd); | ||||
|         return cal.getTime(); | ||||
|     } | ||||
| 
 | ||||
|     public XMLGregorianCalendar toXMLGregorianCalendar(GregorianCalendar calendar) throws DatatypeConfigurationException { | ||||
|         DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); | ||||
|         return datatypeFactory.newXMLGregorianCalendar(calendar); | ||||
|     } | ||||
| 
 | ||||
|     public Date toDate(XMLGregorianCalendar calendar) { | ||||
|         return calendar.toGregorianCalendar() | ||||
|             .getTime(); | ||||
|     } | ||||
| 
 | ||||
|     public int compareDates(GregorianCalendar firstDate, GregorianCalendar secondDate) { | ||||
|         return firstDate.compareTo(secondDate); | ||||
|     } | ||||
| 
 | ||||
|     public String formatDate(GregorianCalendar calendar) { | ||||
|         return calendar.toZonedDateTime() | ||||
|             .format(DateTimeFormatter.ofPattern("d MMM uuuu")); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,18 @@ | ||||
| package com.baeldung.immutableobjects; | ||||
| 
 | ||||
| public final class Currency { | ||||
| 
 | ||||
|     private final String value; | ||||
|      | ||||
|     private Currency(String currencyValue) { | ||||
|         value = currencyValue; | ||||
|     } | ||||
|      | ||||
|     public String getValue() { | ||||
|         return value; | ||||
|     } | ||||
|      | ||||
|     public static Currency of(String value) { | ||||
|         return new Currency(value); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,20 @@ | ||||
| package com.baeldung.immutableobjects; | ||||
| 
 | ||||
| // 4. Immutability in Java | ||||
| public final class Money { | ||||
|     private final double amount; | ||||
|     private final Currency currency; | ||||
| 
 | ||||
|     public Money(double amount, Currency currency) { | ||||
|         this.amount = amount; | ||||
|         this.currency = currency; | ||||
|     } | ||||
| 
 | ||||
|     public Currency getCurrency() { | ||||
|         return currency; | ||||
|     } | ||||
| 
 | ||||
|     public double getAmount() { | ||||
|         return amount; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,8 @@ | ||||
| package com.baeldung.manifest; | ||||
| 
 | ||||
| public class AppExample { | ||||
| 
 | ||||
| 	public static void main(String[] args){ | ||||
| 		System.out.println("AppExample executed!"); | ||||
| 	} | ||||
| } | ||||
| @ -0,0 +1,83 @@ | ||||
| package com.baeldung.manifest; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.BufferedWriter; | ||||
| import java.io.File; | ||||
| import java.io.FileWriter; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStreamReader; | ||||
| 
 | ||||
| public class ExecuteJarFile { | ||||
| 
 | ||||
|     private static final String DELIMITER = " "; | ||||
|     private static final String WORK_PATH = "src/main/java/com/baeldung/manifest"; | ||||
|     private static final String MANIFEST_MF_PATH = WORK_PATH + "/MANIFEST.MF"; | ||||
|     private static final String MAIN_MANIFEST_ATTRIBUTE = "Main-Class: com.baeldung.manifest.AppExample"; | ||||
| 
 | ||||
|     private static final String COMPILE_COMMAND = "javac -d . AppExample.java"; | ||||
|     private static final String CREATE_JAR_WITHOUT_MF_ATT_COMMAND = "jar cvf example.jar com/baeldung/manifest/AppExample.class"; | ||||
|     private static final String CREATE_JAR_WITH_MF_ATT_COMMAND = "jar cvmf MANIFEST.MF example.jar com/baeldung/manifest/AppExample.class"; | ||||
|     private static final String EXECUTE_JAR_COMMAND = "java -jar example.jar"; | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         System.out.println(executeJarWithoutManifestAttribute()); | ||||
|         System.out.println(executeJarWithManifestAttribute()); | ||||
|     } | ||||
| 
 | ||||
|     public static String executeJarWithoutManifestAttribute() { | ||||
|         return executeJar(CREATE_JAR_WITHOUT_MF_ATT_COMMAND); | ||||
|     } | ||||
| 
 | ||||
|     public static String executeJarWithManifestAttribute() { | ||||
|         createManifestFile(); | ||||
|         return executeJar(CREATE_JAR_WITH_MF_ATT_COMMAND); | ||||
|     } | ||||
| 
 | ||||
|     private static void createManifestFile() { | ||||
|         BufferedWriter writer; | ||||
|         try { | ||||
|             writer = new BufferedWriter(new FileWriter(MANIFEST_MF_PATH)); | ||||
|             writer.write(MAIN_MANIFEST_ATTRIBUTE); | ||||
|             writer.newLine(); | ||||
|             writer.close(); | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     private static String executeJar(String createJarCommand) { | ||||
|         executeCommand(COMPILE_COMMAND); | ||||
|         executeCommand(createJarCommand); | ||||
|         return executeCommand(EXECUTE_JAR_COMMAND); | ||||
|     } | ||||
| 
 | ||||
|     private static String executeCommand(String command) { | ||||
|         String output = null; | ||||
|         try { | ||||
|             output = collectOutput(runProcess(command)); | ||||
|         } catch (Exception ex) { | ||||
|             System.out.println(ex); | ||||
|         } | ||||
|         return output; | ||||
|     } | ||||
| 
 | ||||
|     private static String collectOutput(Process process) throws IOException { | ||||
|         StringBuffer output = new StringBuffer(); | ||||
|         BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream())); | ||||
|         String line = ""; | ||||
|         while ((line = outputReader.readLine()) != null) { | ||||
|             output.append(line + "\n"); | ||||
|         } | ||||
|         return output.toString(); | ||||
|     } | ||||
| 
 | ||||
|     private static Process runProcess(String command) throws IOException, InterruptedException { | ||||
|         ProcessBuilder builder = new ProcessBuilder(command.split(DELIMITER)); | ||||
|         builder.directory(new File(WORK_PATH).getAbsoluteFile()); | ||||
|         builder.redirectErrorStream(true); | ||||
|         Process process = builder.start(); | ||||
|         process.waitFor(); | ||||
|         return process; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,68 @@ | ||||
| package com.baeldung.string; | ||||
| 
 | ||||
| import com.ibm.icu.lang.UCharacter; | ||||
| import com.ibm.icu.text.BreakIterator; | ||||
| import org.apache.commons.lang.WordUtils; | ||||
| 
 | ||||
| import java.util.Arrays; | ||||
| import java.util.stream.Collectors; | ||||
| 
 | ||||
| public class TitleCaseConverter { | ||||
| 
 | ||||
|     private static final String WORD_SEPARATOR = " "; | ||||
| 
 | ||||
|     public static String convertToTitleCaseIteratingChars(String text) { | ||||
|         if (text == null || text.isEmpty()) { | ||||
|             return text; | ||||
|         } | ||||
| 
 | ||||
|         StringBuilder converted = new StringBuilder(); | ||||
| 
 | ||||
|         boolean convertNext = true; | ||||
|         for (char ch : text.toCharArray()) { | ||||
|             if (Character.isSpaceChar(ch)) { | ||||
|                 convertNext = true; | ||||
|             } else if (convertNext) { | ||||
|                 ch = Character.toTitleCase(ch); | ||||
|                 convertNext = false; | ||||
|             } else { | ||||
|                 ch = Character.toLowerCase(ch); | ||||
|             } | ||||
|             converted.append(ch); | ||||
|         } | ||||
| 
 | ||||
|         return converted.toString(); | ||||
|     } | ||||
| 
 | ||||
|     public static String convertToTitleCaseSplitting(String text) { | ||||
|         if (text == null || text.isEmpty()) { | ||||
|             return text; | ||||
|         } | ||||
| 
 | ||||
|         return Arrays | ||||
|           .stream(text.split(WORD_SEPARATOR)) | ||||
|           .map(word -> word.isEmpty() | ||||
|             ? word | ||||
|             : Character.toTitleCase(word.charAt(0)) + word | ||||
|               .substring(1) | ||||
|               .toLowerCase()) | ||||
|           .collect(Collectors.joining(WORD_SEPARATOR)); | ||||
|     } | ||||
| 
 | ||||
|     public static String convertToTitleCaseIcu4j(String text) { | ||||
|         if (text == null || text.isEmpty()) { | ||||
|             return text; | ||||
|         } | ||||
| 
 | ||||
|         return UCharacter.toTitleCase(text, BreakIterator.getTitleInstance()); | ||||
|     } | ||||
| 
 | ||||
|     public static String convertToTileCaseWordUtilsFull(String text) { | ||||
|         return WordUtils.capitalizeFully(text); | ||||
|     } | ||||
| 
 | ||||
|     public static String convertToTileCaseWordUtils(String text) { | ||||
|         return WordUtils.capitalize(text); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,29 @@ | ||||
| package com.baeldung.customexception; | ||||
| 
 | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| 
 | ||||
| import java.io.File; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class IncorrectFileExtensionExceptionUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void testWhenCorrectFileExtensionGiven_ReceivesNoException() throws IncorrectFileNameException { | ||||
|         assertThat(FileManager.getFirstLine("correctFileNameWithProperExtension.txt")).isEqualTo("Default First Line"); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = IncorrectFileExtensionException.class) | ||||
|     public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException { | ||||
|         StringBuffer sBuffer = new StringBuffer(); | ||||
|         sBuffer.append("src"); | ||||
|         sBuffer.append(File.separator); | ||||
|         sBuffer.append("test"); | ||||
|         sBuffer.append(File.separator); | ||||
|         sBuffer.append("resources"); | ||||
|         sBuffer.append(File.separator); | ||||
|         sBuffer.append("correctFileNameWithoutProperExtension"); | ||||
|         FileManager.getFirstLine(sBuffer.toString()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,19 @@ | ||||
| package com.baeldung.customexception; | ||||
| 
 | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class IncorrectFileNameExceptionUnitTest { | ||||
| 
 | ||||
|     @Test(expected = IncorrectFileNameException.class) | ||||
|     public void testWhenIncorrectFileNameExceptionThrown_ReceivesIncorrectFileNameException() throws IncorrectFileNameException { | ||||
|         FileManager.getFirstLine("wrongFileName.txt"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException { | ||||
|         assertThat(FileManager.getFirstLine("correctFileName.txt")).isEqualTo("Default First Line"); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,92 @@ | ||||
| package com.baeldung.date; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.text.ParseException; | ||||
| import java.time.LocalDate; | ||||
| import java.time.OffsetDateTime; | ||||
| import java.util.Calendar; | ||||
| import java.util.Date; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertNotEquals; | ||||
| 
 | ||||
| public class DateWithoutTimeUnitTest { | ||||
| 
 | ||||
|     private static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGettingDateWithoutTimeUsingCalendar_thenReturnDateWithoutTime() { | ||||
|         Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingCalendar(); | ||||
| 
 | ||||
|         // first check the time is set to 0 | ||||
|         Calendar calendar = Calendar.getInstance(); | ||||
|         calendar.setTime(dateWithoutTime); | ||||
| 
 | ||||
|         assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); | ||||
|         assertEquals(0, calendar.get(Calendar.MINUTE)); | ||||
|         assertEquals(0, calendar.get(Calendar.SECOND)); | ||||
|         assertEquals(0, calendar.get(Calendar.MILLISECOND)); | ||||
| 
 | ||||
|         // we get the day of the date | ||||
|         int day = calendar.get(Calendar.DAY_OF_MONTH); | ||||
| 
 | ||||
|         // if we add the mills of one day minus 1 we should get the same day | ||||
|         calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1); | ||||
|         assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); | ||||
| 
 | ||||
|         // if we add one full day in millis we should get a different day | ||||
|         calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY); | ||||
|         assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGettingDateWithoutTimeUsingFormat_thenReturnDateWithoutTime() throws ParseException { | ||||
|         Date dateWithoutTime = DateWithoutTime.getDateWithoutTimeUsingFormat(); | ||||
| 
 | ||||
|         // first check the time is set to 0 | ||||
|         Calendar calendar = Calendar.getInstance(); | ||||
|         calendar.setTime(dateWithoutTime); | ||||
| 
 | ||||
|         assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); | ||||
|         assertEquals(0, calendar.get(Calendar.MINUTE)); | ||||
|         assertEquals(0, calendar.get(Calendar.SECOND)); | ||||
|         assertEquals(0, calendar.get(Calendar.MILLISECOND)); | ||||
| 
 | ||||
|         // we get the day of the date | ||||
|         int day = calendar.get(Calendar.DAY_OF_MONTH); | ||||
| 
 | ||||
|         // if we add the mills of one day minus 1 we should get the same day | ||||
|         calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY - 1); | ||||
|         assertEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); | ||||
| 
 | ||||
|         // if we add one full day in millis we should get a different day | ||||
|         calendar.setTimeInMillis(dateWithoutTime.getTime() + MILLISECONDS_PER_DAY); | ||||
|         assertNotEquals(day, calendar.get(Calendar.DAY_OF_MONTH)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGettingLocalDate_thenReturnDateWithoutTime() { | ||||
|         // get the local date | ||||
|         LocalDate localDate = DateWithoutTime.getLocalDate(); | ||||
| 
 | ||||
|         // get the millis of our LocalDate | ||||
|         long millisLocalDate = localDate | ||||
|           .atStartOfDay() | ||||
|           .toInstant(OffsetDateTime | ||||
|             .now() | ||||
|             .getOffset()) | ||||
|           .toEpochMilli(); | ||||
| 
 | ||||
|         Calendar calendar = Calendar.getInstance(); | ||||
|         // if we add the millis of one day minus 1 we should get the same day | ||||
|         calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY - 1); | ||||
|         assertEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH)); | ||||
| 
 | ||||
|         // if we add one full day in millis we should get a different day | ||||
|         calendar.setTimeInMillis(millisLocalDate + MILLISECONDS_PER_DAY); | ||||
|         assertNotEquals(localDate.getDayOfMonth(), calendar.get(Calendar.DAY_OF_MONTH)); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,45 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.hamcrest.CoreMatchers.is; | ||||
| import static org.junit.Assert.assertThat; | ||||
| 
 | ||||
| import java.text.ParseException; | ||||
| import java.text.SimpleDateFormat; | ||||
| import java.util.Date; | ||||
| 
 | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class DateExtractYearMonthDayIntegerValuesUnitTest { | ||||
| 
 | ||||
|     DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues(); | ||||
|      | ||||
|     Date date; | ||||
|      | ||||
|     @Before | ||||
|     public void setup() throws ParseException | ||||
|     { | ||||
|         date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018"); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetYear_thenCorrectYear() | ||||
|     { | ||||
|        int actualYear=extractYearMonthDateIntegerValues.getYear(date); | ||||
|        assertThat(actualYear,is(2018)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetMonth_thenCorrectMonth() | ||||
|     { | ||||
|        int actualMonth=extractYearMonthDateIntegerValues.getMonth(date); | ||||
|        assertThat(actualMonth,is(02)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetDay_thenCorrectDay() | ||||
|     { | ||||
|        int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date); | ||||
|        assertThat(actualDayOfMonth,is(01)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.hamcrest.CoreMatchers.is; | ||||
| import static org.junit.Assert.assertThat; | ||||
| 
 | ||||
| import java.time.LocalDate; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class LocalDateExtractYearMonthDayIntegerValuesUnitTest { | ||||
| 
 | ||||
|     LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues(); | ||||
|      | ||||
|     LocalDate localDate=LocalDate.parse("2007-12-03"); | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetYear_thenCorrectYear() | ||||
|     { | ||||
|        int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate); | ||||
|        assertThat(actualYear,is(2007)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetMonth_thenCorrectMonth() | ||||
|     { | ||||
|        int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate); | ||||
|        assertThat(actualMonth,is(12)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetDay_thenCorrectDay() | ||||
|     { | ||||
|        int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate); | ||||
|        assertThat(actualDayOfMonth,is(03)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.hamcrest.CoreMatchers.is; | ||||
| import static org.junit.Assert.assertThat; | ||||
| 
 | ||||
| import java.time.LocalDateTime; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest { | ||||
| 
 | ||||
|     LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues(); | ||||
|      | ||||
|     LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30"); | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetYear_thenCorrectYear() | ||||
|     { | ||||
|        int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime); | ||||
|        assertThat(actualYear,is(2007)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetMonth_thenCorrectMonth() | ||||
|     { | ||||
|        int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime); | ||||
|        assertThat(actualMonth,is(12)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetDay_thenCorrectDay() | ||||
|     { | ||||
|        int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime); | ||||
|        assertThat(actualDayOfMonth,is(03)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.hamcrest.CoreMatchers.is; | ||||
| import static org.junit.Assert.assertThat; | ||||
| 
 | ||||
| import java.time.OffsetDateTime; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest { | ||||
| 
 | ||||
|     OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues(); | ||||
|      | ||||
|     OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00"); | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetYear_thenCorrectYear() | ||||
|     { | ||||
|        int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime); | ||||
|        assertThat(actualYear,is(2007)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetMonth_thenCorrectMonth() | ||||
|     { | ||||
|        int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime); | ||||
|        assertThat(actualMonth,is(12)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetDay_thenCorrectDay() | ||||
|     { | ||||
|        int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime); | ||||
|        assertThat(actualDayOfMonth,is(03)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.datetime; | ||||
| 
 | ||||
| import static org.hamcrest.CoreMatchers.is; | ||||
| import static org.junit.Assert.assertThat; | ||||
| 
 | ||||
| import java.time.ZonedDateTime; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest { | ||||
| 
 | ||||
|     ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues(); | ||||
|      | ||||
|     ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00"); | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetYear_thenCorrectYear() | ||||
|     { | ||||
|        int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime); | ||||
|        assertThat(actualYear,is(2007)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetMonth_thenCorrectMonth() | ||||
|     { | ||||
|        int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime); | ||||
|        assertThat(actualMonth,is(12)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenGetDay_thenCorrectDay() | ||||
|     { | ||||
|        int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime); | ||||
|        assertThat(actualDayOfMonth,is(03)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,32 @@ | ||||
| package com.baeldung.encrypt; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import javax.crypto.KeyGenerator; | ||||
| import javax.crypto.NoSuchPaddingException; | ||||
| import javax.crypto.SecretKey; | ||||
| import java.io.File; | ||||
| import java.io.IOException; | ||||
| import java.security.InvalidAlgorithmParameterException; | ||||
| import java.security.InvalidKeyException; | ||||
| import java.security.NoSuchAlgorithmException; | ||||
| 
 | ||||
| import static org.hamcrest.Matchers.is; | ||||
| import static org.junit.Assert.assertThat; | ||||
| 
 | ||||
| public class FileEncrypterDecrypterIntegrationTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenStringAndFilename_whenEncryptingIntoFile_andDecryptingFileAgain_thenOriginalStringIsReturned() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException { | ||||
|         String originalContent = "foobar"; | ||||
|         SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); | ||||
| 
 | ||||
|         FileEncrypterDecrypter fileEncrypterDecrypter = new FileEncrypterDecrypter(secretKey, "AES/CBC/PKCS5Padding"); | ||||
|         fileEncrypterDecrypter.encrypt(originalContent, "baz.enc"); | ||||
| 
 | ||||
|         String decryptedContent = fileEncrypterDecrypter.decrypt("baz.enc"); | ||||
|         assertThat(decryptedContent, is(originalContent)); | ||||
| 
 | ||||
|         new File("baz.enc").delete(); // cleanup | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,64 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.junit.After; | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| import org.junit.runner.RunWith; | ||||
| import org.mockito.ArgumentCaptor; | ||||
| import org.mockito.Captor; | ||||
| import org.mockito.Mock; | ||||
| import org.mockito.junit.MockitoJUnitRunner; | ||||
| import org.slf4j.LoggerFactory; | ||||
| import ch.qos.logback.classic.Level; | ||||
| import ch.qos.logback.classic.Logger; | ||||
| import ch.qos.logback.classic.spi.ILoggingEvent; | ||||
| import ch.qos.logback.classic.spi.LoggingEvent; | ||||
| import ch.qos.logback.core.Appender; | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| import static org.mockito.Mockito.verify; | ||||
| 
 | ||||
| @RunWith(MockitoJUnitRunner.class) | ||||
| public class GlobalExceptionHandlerUnitTest { | ||||
| 
 | ||||
|     @Mock | ||||
|     private Appender<ILoggingEvent> mockAppender; | ||||
| 
 | ||||
|     @Captor | ||||
|     private ArgumentCaptor<LoggingEvent> captorLoggingEvent; | ||||
| 
 | ||||
|     @Before | ||||
|     public void setup() { | ||||
|         final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); | ||||
|         logger.addAppender(mockAppender); | ||||
| 
 | ||||
|         Handler globalExceptionHandler = new Handler(); | ||||
|         Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler); | ||||
|     } | ||||
| 
 | ||||
|     @After | ||||
|     public void teardown() { | ||||
|         final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); | ||||
|         logger.detachAppender(mockAppender); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenArithmeticException_thenUseUncaughtExceptionHandler() throws InterruptedException { | ||||
| 
 | ||||
|         Thread globalExceptionHandlerThread = new Thread() { | ||||
|             public void run() { | ||||
|                 GlobalExceptionHandler globalExceptionHandlerObj = new GlobalExceptionHandler(); | ||||
|                 globalExceptionHandlerObj.performArithmeticOperation(99, 0); | ||||
|             } | ||||
|         }; | ||||
| 
 | ||||
|         globalExceptionHandlerThread.start(); | ||||
|         globalExceptionHandlerThread.join(); | ||||
| 
 | ||||
|         verify(mockAppender).doAppend(captorLoggingEvent.capture()); | ||||
|         LoggingEvent loggingEvent = captorLoggingEvent.getValue(); | ||||
| 
 | ||||
|         assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); | ||||
|         assertThat(loggingEvent.getFormattedMessage()).isEqualTo("Unhandled exception caught!"); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -19,8 +19,7 @@ public class ExtensionUnitTest { | ||||
|     public void getExtension_whenStringHandle_thenExtensionIsTrue() { | ||||
|         String expectedExtension = "java"; | ||||
|         Optional<String> actualExtension = extension.getExtensionByStringHandling("Demo.java"); | ||||
|         Assert.assertTrue(actualExtension.isPresent()); | ||||
|         actualExtension.ifPresent(ext -> Assert.assertEquals(expectedExtension,ext)); | ||||
|         Assert.assertEquals(expectedExtension, actualExtension.get()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|  | ||||
Some files were not shown because too many files have changed in this diff Show More
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user