Merge remote-tracking branch 'origin/master'
This commit is contained in:
		
						commit
						cd16a66448
					
				| @ -1,6 +1,6 @@ | ||||
| language: java | ||||
| 
 | ||||
| install: travis_wait 60 mvn -q test | ||||
| install: travis_wait 60 mvn -q test -fae | ||||
| 
 | ||||
| before_script: | ||||
|   - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc | ||||
|  | ||||
| @ -39,7 +39,6 @@ | ||||
| 	</dependencies> | ||||
| 
 | ||||
| 	<build> | ||||
| 		<defaultGoal>install</defaultGoal> | ||||
| 		<pluginManagement> | ||||
| 			<plugins> | ||||
| 				<plugin> | ||||
| @ -56,6 +55,17 @@ | ||||
| 					<artifactId>exec-maven-plugin</artifactId> | ||||
| 					<version>${exec-maven-plugin.version}</version> | ||||
| 				</plugin> | ||||
| 
 | ||||
| 				<plugin> | ||||
| 					<groupId>org.apache.maven.plugins</groupId> | ||||
| 					<artifactId>maven-surefire-plugin</artifactId> | ||||
| 					<configuration> | ||||
| 						<excludes> | ||||
| 							<exclude>**/*LongRunningUnitTest.java</exclude> | ||||
| 							<exclude>**/*IntegrationTest.java</exclude> | ||||
| 						</excludes> | ||||
| 					</configuration> | ||||
| 				</plugin> | ||||
| 			</plugins> | ||||
| 		</pluginManagement> | ||||
| 	</build> | ||||
|  | ||||
| @ -0,0 +1,22 @@ | ||||
| package algorithms; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; | ||||
| 
 | ||||
| public class AntColonyOptimizationLongRunningUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void testGenerateRandomMatrix() { | ||||
|         AntColonyOptimization antTSP = new AntColonyOptimization(5); | ||||
|         Assert.assertNotNull(antTSP.generateRandomMatrix(5)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void testStartAntOptimization() { | ||||
|         AntColonyOptimization antTSP = new AntColonyOptimization(5); | ||||
|         Assert.assertNotNull(antTSP.solve()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -1,22 +0,0 @@ | ||||
| package algorithms; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; | ||||
| 
 | ||||
| public class AntColonyOptimizationTest { | ||||
| 
 | ||||
| 	@Test | ||||
| 	public void testGenerateRandomMatrix() { | ||||
| 		AntColonyOptimization antTSP = new AntColonyOptimization(5); | ||||
| 		Assert.assertNotNull(antTSP.generateRandomMatrix(5)); | ||||
| 	} | ||||
| 
 | ||||
| 	@Test | ||||
| 	public void testStartAntOptimization() { | ||||
| 		AntColonyOptimization antTSP = new AntColonyOptimization(5); | ||||
| 		Assert.assertNotNull(antTSP.solve()); | ||||
| 	} | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,16 @@ | ||||
| package algorithms; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; | ||||
| 
 | ||||
| public class BinaryGeneticAlgorithmLongRunningUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void testGA() { | ||||
|         SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); | ||||
|         Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -1,16 +0,0 @@ | ||||
| package algorithms; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; | ||||
| 
 | ||||
| public class BinaryGeneticAlgorithmUnitTest { | ||||
| 
 | ||||
| 	@Test | ||||
| 	public void testGA() { | ||||
| 		SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); | ||||
| 		Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); | ||||
| 	} | ||||
| 
 | ||||
| } | ||||
| @ -11,7 +11,7 @@ import java.util.List; | ||||
| 
 | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class DijkstraAlgorithmTest { | ||||
| public class DijkstraAlgorithmLongRunningUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSPPSolved_thenCorrect() { | ||||
| @ -56,19 +56,29 @@ public class DijkstraAlgorithmTest { | ||||
|         for (Node node : graph.getNodes()) { | ||||
|             switch (node.getName()) { | ||||
|             case "B": | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeB)); | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeB)); | ||||
|                 break; | ||||
|             case "C": | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeC)); | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeC)); | ||||
|                 break; | ||||
|             case "D": | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeD)); | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeD)); | ||||
|                 break; | ||||
|             case "E": | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeE)); | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeE)); | ||||
|                 break; | ||||
|             case "F": | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeF)); | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeF)); | ||||
|                 break; | ||||
|             } | ||||
|         } | ||||
| @ -1,28 +1,27 @@ | ||||
| package algorithms; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| import org.junit.Test; | ||||
| import com.baeldung.automata.*; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| /** | ||||
|  * Tests for {@link RtFiniteStateMachine} | ||||
|  */ | ||||
| public final class RtFiniteStateMachineTest { | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public final class RtFiniteStateMachineLongRunningUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void acceptsSimplePair() { | ||||
|         String json = "{\"key\":\"value\"}"; | ||||
|         FiniteStateMachine machine = this.buildJsonStateMachine(); | ||||
|         for (int i=0;i<json.length();i++) { | ||||
|         for (int i = 0; i < json.length(); i++) { | ||||
|             machine = machine.switchState(String.valueOf(json.charAt(i))); | ||||
|         } | ||||
|         assertTrue(machine.canStop()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void acceptsMorePairs() { | ||||
|         String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; | ||||
|         FiniteStateMachine machine = this.buildJsonStateMachine(); | ||||
|         for (int i=0;i<json.length();i++) { | ||||
|         for (int i = 0; i < json.length(); i++) { | ||||
|             machine = machine.switchState(String.valueOf(json.charAt(i))); | ||||
|         } | ||||
|         assertTrue(machine.canStop()); | ||||
| @ -32,7 +31,7 @@ public final class RtFiniteStateMachineTest { | ||||
|     public void missingColon() { | ||||
|         String json = "{\"key\"\"value\"}"; | ||||
|         FiniteStateMachine machine = this.buildJsonStateMachine(); | ||||
|         for (int i=0;i<json.length();i++) { | ||||
|         for (int i = 0; i < json.length(); i++) { | ||||
|             machine = machine.switchState(String.valueOf(json.charAt(i))); | ||||
|         } | ||||
|     } | ||||
| @ -56,20 +55,12 @@ public final class RtFiniteStateMachineTest { | ||||
|         second.with(new RtTransition("\"", third)); | ||||
|         //Add transitions with chars 0-9 and a-z | ||||
|         for (int i = 0; i < 26; i++) { | ||||
|             if(i<10) { | ||||
|                 third = third.with( | ||||
|                     new RtTransition(String.valueOf(i), third) | ||||
|                 ); | ||||
|                 sixth = sixth.with( | ||||
|                     new RtTransition(String.valueOf(i), sixth) | ||||
|                 ); | ||||
|             if (i < 10) { | ||||
|                 third = third.with(new RtTransition(String.valueOf(i), third)); | ||||
|                 sixth = sixth.with(new RtTransition(String.valueOf(i), sixth)); | ||||
|             } | ||||
|             third = third.with( | ||||
|                 new RtTransition(String.valueOf((char) ('a' + i)), third) | ||||
|             ); | ||||
|             sixth = sixth.with( | ||||
|                 new RtTransition(String.valueOf((char) ('a' + i)), sixth) | ||||
|             ); | ||||
|             third = third.with(new RtTransition(String.valueOf((char) ('a' + i)), third)); | ||||
|             sixth = sixth.with(new RtTransition(String.valueOf((char) ('a' + i)), sixth)); | ||||
|         } | ||||
|         third.with(new RtTransition("\"", fourth)); | ||||
|         fourth.with(new RtTransition(":", fifth)); | ||||
| @ -5,7 +5,7 @@ import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; | ||||
| 
 | ||||
| public class SimulatedAnnealingTest { | ||||
| public class SimulatedAnnealingLongRunningUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void testSimulateAnnealing() { | ||||
| @ -1,28 +0,0 @@ | ||||
| package com.baeldung.algorithms.primechecker; | ||||
| 
 | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.primechecker.BigIntegerPrimeChecker; | ||||
| import com.baeldung.algorithms.primechecker.PrimeChecker; | ||||
| 
 | ||||
| public class BigIntegerPrimeCheckerTest { | ||||
| 
 | ||||
|     BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker(); | ||||
|      | ||||
|     @Test | ||||
|     public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){ | ||||
|         assertTrue(primeChecker.isPrime(13l)); | ||||
|         assertTrue(primeChecker.isPrime(1009L)); | ||||
|         assertTrue(primeChecker.isPrime(74207281L)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){ | ||||
|         assertTrue(!primeChecker.isPrime(50L)); | ||||
|         assertTrue(!primeChecker.isPrime(1001L)); | ||||
|         assertTrue(!primeChecker.isPrime(74207282L)); | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -1,27 +0,0 @@ | ||||
| package com.baeldung.algorithms.primechecker; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.primechecker.BruteForcePrimeChecker; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| public class BruteForcePrimeCheckerTest { | ||||
| 
 | ||||
|     BruteForcePrimeChecker primeChecker = new BruteForcePrimeChecker(); | ||||
|      | ||||
|     @Test | ||||
|     public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){ | ||||
|         assertTrue(primeChecker.isPrime(13)); | ||||
|         assertTrue(primeChecker.isPrime(1009)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){ | ||||
|         assertTrue(!primeChecker.isPrime(50)); | ||||
|         assertTrue(!primeChecker.isPrime(1001)); | ||||
|     } | ||||
|      | ||||
|      | ||||
|      | ||||
| } | ||||
| @ -1,26 +0,0 @@ | ||||
| package com.baeldung.algorithms.primechecker; | ||||
| 
 | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.primechecker.OptimisedPrimeChecker; | ||||
| import com.baeldung.algorithms.primechecker.PrimeChecker; | ||||
| 
 | ||||
| public class OptimisedPrimeCheckerTest { | ||||
| 
 | ||||
|     OptimisedPrimeChecker primeChecker = new OptimisedPrimeChecker(); | ||||
|      | ||||
|     @Test | ||||
|     public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){ | ||||
|         assertTrue(primeChecker.isPrime(13)); | ||||
|         assertTrue(primeChecker.isPrime(1009)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){ | ||||
|         assertTrue(!primeChecker.isPrime(50)); | ||||
|         assertTrue(!primeChecker.isPrime(1001)); | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -0,0 +1,69 @@ | ||||
| package com.baeldung.algorithms.primechecker; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import static org.junit.Assert.assertFalse; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class PrimeCheckerTest { | ||||
| 
 | ||||
|     private final BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker(); | ||||
|      | ||||
|     @Test | ||||
|     public void whenCheckIsPrime_thenTrue(){ | ||||
|         assertTrue(primeChecker.isPrime(13l)); | ||||
|         assertTrue(primeChecker.isPrime(1009L)); | ||||
|         assertTrue(primeChecker.isPrime(74207281L)); | ||||
|     } | ||||
|      | ||||
|     @Test | ||||
|     public void whenCheckIsPrime_thenFalse(){ | ||||
|         assertTrue(!primeChecker.isPrime(50L)); | ||||
|         assertTrue(!primeChecker.isPrime(1001L)); | ||||
|         assertTrue(!primeChecker.isPrime(74207282L)); | ||||
|     } | ||||
| 
 | ||||
|     private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker(); | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenBFCheckIsPrime_thenTrue(){ | ||||
|         assertTrue(bfPrimeChecker.isPrime(13)); | ||||
|         assertTrue(bfPrimeChecker.isPrime(1009)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenBFCheckIsPrime_thenFalse(){ | ||||
|         assertFalse(bfPrimeChecker.isPrime(50)); | ||||
|         assertFalse(bfPrimeChecker.isPrime(1001)); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
|     private final OptimisedPrimeChecker optimisedPrimeChecker = new OptimisedPrimeChecker(); | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenOptCheckIsPrime_thenTrue(){ | ||||
|         assertTrue(optimisedPrimeChecker.isPrime(13)); | ||||
|         assertTrue(optimisedPrimeChecker.isPrime(1009)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenOptCheckIsPrime_thenFalse(){ | ||||
|         assertFalse(optimisedPrimeChecker.isPrime(50)); | ||||
|         assertFalse(optimisedPrimeChecker.isPrime(1001)); | ||||
|     } | ||||
| 
 | ||||
|     private final PrimesPrimeChecker primesPrimeChecker = new PrimesPrimeChecker(); | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPrimesCheckIsPrime_thenTrue() { | ||||
|         assertTrue(primesPrimeChecker.isPrime(13)); | ||||
|         assertTrue(primesPrimeChecker.isPrime(1009)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPrimesCheckIsPrime_thenFalse() { | ||||
|         assertFalse(primesPrimeChecker.isPrime(50)); | ||||
|         assertFalse(primesPrimeChecker.isPrime(1001)); | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -1,25 +0,0 @@ | ||||
| package com.baeldung.algorithms.primechecker; | ||||
| 
 | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.algorithms.primechecker.PrimeChecker; | ||||
| import com.baeldung.algorithms.primechecker.PrimesPrimeChecker; | ||||
| 
 | ||||
| public class PrimesPrimeCheckerTest { | ||||
|     PrimesPrimeChecker primeChecker = new PrimesPrimeChecker(); | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenPrimeNumber_whenCheckIsPrime_thenTrue() { | ||||
|         assertTrue(primeChecker.isPrime(13)); | ||||
|         assertTrue(primeChecker.isPrime(1009)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse() { | ||||
|         assertTrue(!primeChecker.isPrime(50)); | ||||
|         assertTrue(!primeChecker.isPrime(1001)); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -98,3 +98,5 @@ | ||||
| - [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) | ||||
| - [JVM Log Forging](http://www.baeldung.com/jvm-log-forging) | ||||
| - [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe) | ||||
| - [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset) | ||||
| - [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request) | ||||
|  | ||||
| @ -99,6 +99,13 @@ | ||||
|             <scope>provided</scope> | ||||
|         </dependency> | ||||
|          | ||||
| 		<!-- mysql --> | ||||
|         <dependency> | ||||
|             <groupId>mysql</groupId> | ||||
|             <artifactId>mysql-connector-java</artifactId> | ||||
|             <version>${mysql.version}</version> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <!-- test scoped --> | ||||
| 
 | ||||
|         <dependency> | ||||
| @ -135,13 +142,6 @@ | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>org.testng</groupId> | ||||
|             <artifactId>testng</artifactId> | ||||
|             <version>${testng.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>org.mockito</groupId> | ||||
|             <artifactId>mockito-core</artifactId> | ||||
| @ -177,37 +177,6 @@ | ||||
| 				</exclusion> | ||||
| 			</exclusions>         | ||||
| 		</dependency>                | ||||
| 		<!-- JDO --> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>javax.jdo</artifactId> | ||||
| 		    <version>3.2.0-m6</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-core</artifactId> | ||||
| 		    <version>5.1.0-m1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-api-jdo</artifactId> | ||||
| 		    <version>5.1.0-m1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-rdbms</artifactId> | ||||
| 		    <version>5.1.0-m1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-maven-plugin</artifactId> | ||||
| 		    <version>5.0.2</version> | ||||
| 		</dependency>		 | ||||
| 		<dependency> | ||||
| 		    <groupId>com.h2database</groupId> | ||||
| 		    <artifactId>h2</artifactId> | ||||
| 		    <version>1.4.194</version> | ||||
| 		</dependency> | ||||
| 
 | ||||
| 		<dependency> | ||||
| 		    <groupId>org.owasp.esapi</groupId> | ||||
| @ -250,6 +219,7 @@ | ||||
|                         <exclude>**/*IntegrationTest.java</exclude> | ||||
|                         <exclude>**/*LongRunningUnitTest.java</exclude> | ||||
|                         <exclude>**/*ManualTest.java</exclude> | ||||
|                         <exclude>**/JdbcTest.java</exclude> | ||||
|                     </excludes> | ||||
|                     <testFailureIgnore>true</testFailureIgnore> | ||||
|                 </configuration> | ||||
| @ -358,29 +328,6 @@ | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|              | ||||
|             <!-- JDO Plugin --> | ||||
| 
 | ||||
| 			<plugin> | ||||
|                 <groupId>org.datanucleus</groupId> | ||||
|     			<artifactId>datanucleus-maven-plugin</artifactId> | ||||
|     			<version>5.0.2</version> | ||||
|                 <configuration> | ||||
|                     <api>JDO</api> | ||||
|                     <props>${basedir}/datanucleus.properties</props> | ||||
|                     <log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration> | ||||
|                     <verbose>true</verbose> | ||||
|                 </configuration> | ||||
| 				<executions> | ||||
|                 	<execution> | ||||
|                         <phase>process-classes</phase> | ||||
|                         <goals> | ||||
|                             <goal>enhance</goal> | ||||
|                         </goals> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
| 
 | ||||
|         </plugins> | ||||
| 
 | ||||
|     </build> | ||||
| @ -428,6 +375,9 @@ | ||||
|         <org.slf4j.version>1.7.21</org.slf4j.version> | ||||
|         <logback.version>1.1.7</logback.version> | ||||
|          | ||||
|         <!-- mysql --> | ||||
|         <mysql.version>6.0.6</mysql.version> | ||||
| 
 | ||||
|         <!-- util --> | ||||
|         <guava.version>21.0</guava.version> | ||||
|         <commons-lang3.version>3.5</commons-lang3.version> | ||||
|  | ||||
| @ -4,17 +4,10 @@ import java.time.ZonedDateTime; | ||||
| import java.util.Comparator; | ||||
| import java.util.concurrent.ConcurrentNavigableMap; | ||||
| import java.util.concurrent.ConcurrentSkipListMap; | ||||
| import java.util.function.ToLongFunction; | ||||
| 
 | ||||
| public class EventWindowSort { | ||||
|     private final ConcurrentSkipListMap<ZonedDateTime, String> events = new ConcurrentSkipListMap<>(Comparator.comparingLong(new ToLongFunction<ZonedDateTime>() { | ||||
|         @Override | ||||
|         public long applyAsLong(ZonedDateTime value) { | ||||
|             return value | ||||
|               .toInstant() | ||||
|               .toEpochMilli(); | ||||
|         } | ||||
|     })); | ||||
|     private final ConcurrentSkipListMap<ZonedDateTime, String> events | ||||
|             = new ConcurrentSkipListMap<>(Comparator.comparingLong(value -> value.toInstant().toEpochMilli())); | ||||
| 
 | ||||
|     public void acceptEvent(Event event) { | ||||
|         events.put(event.getEventTime(), event.getContent()); | ||||
|  | ||||
| @ -0,0 +1,27 @@ | ||||
| package com.baeldung.concurrent.sleepwait; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| /*** | ||||
|  * Example of waking up a waiting thread | ||||
|  */ | ||||
| public class ThreadA { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(ThreadA.class); | ||||
| 
 | ||||
|     private static final ThreadB b = new ThreadB(); | ||||
| 
 | ||||
|     public static void main(String... args) throws InterruptedException { | ||||
|         b.start(); | ||||
| 
 | ||||
|         synchronized (b) { | ||||
|             while (b.sum == 0) { | ||||
|                 LOG.debug("Waiting for ThreadB to complete..."); | ||||
|                 b.wait(); | ||||
|             } | ||||
| 
 | ||||
|             LOG.debug("ThreadB has completed. Sum from that thread is: " + b.sum); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,20 @@ | ||||
| package com.baeldung.concurrent.sleepwait; | ||||
| 
 | ||||
| /*** | ||||
|  * Example of waking up a waiting thread | ||||
|  */ | ||||
| class ThreadB extends Thread { | ||||
|     int sum; | ||||
| 
 | ||||
|     @Override | ||||
|     public void run() { | ||||
|         synchronized (this) { | ||||
|             int i = 0; | ||||
|             while (i < 100000) { | ||||
|                 sum += i; | ||||
|                 i++; | ||||
|             } | ||||
|             notify(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,29 @@ | ||||
| package com.baeldung.concurrent.sleepwait; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| /*** | ||||
|  * Example of wait() and sleep() methods | ||||
|  */ | ||||
| public class WaitSleepExample { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(WaitSleepExample.class); | ||||
| 
 | ||||
|     private static final Object LOCK = new Object(); | ||||
| 
 | ||||
|     public static void main(String... args) throws InterruptedException { | ||||
|         sleepWaitInSyncronizedBlocks(); | ||||
|     } | ||||
| 
 | ||||
|     private static void sleepWaitInSyncronizedBlocks() throws InterruptedException { | ||||
|         Thread.sleep(1000); // called on the thread | ||||
|         LOG.debug("Thread '" + Thread.currentThread().getName() + "' is woken after sleeping for 1 second"); | ||||
| 
 | ||||
|         synchronized (LOCK) { | ||||
|             LOCK.wait(1000); // called on the object, synchronization required | ||||
|             LOG.debug("Object '" + LOCK + "' is woken after waiting for 1 second"); | ||||
|         } | ||||
|     } | ||||
|      | ||||
| } | ||||
| @ -1,14 +1,19 @@ | ||||
| package com.baeldung.dirmonitoring; | ||||
| 
 | ||||
| import java.io.File; | ||||
| 
 | ||||
| import org.apache.commons.io.monitor.FileAlterationListener; | ||||
| import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; | ||||
| import org.apache.commons.io.monitor.FileAlterationMonitor; | ||||
| import org.apache.commons.io.monitor.FileAlterationObserver; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.io.File; | ||||
| 
 | ||||
| public class DirectoryMonitoringExample { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class); | ||||
| 
 | ||||
| 
 | ||||
|     public static final int POLL_INTERVAL = 500; | ||||
| 
 | ||||
|     public static void main(String[] args) throws Exception { | ||||
| @ -17,17 +22,17 @@ public class DirectoryMonitoringExample { | ||||
|         FileAlterationListener listener = new FileAlterationListenerAdaptor() { | ||||
|             @Override | ||||
|             public void onFileCreate(File file) { | ||||
|                 System.out.println("File: " + file.getName() + " created"); | ||||
|                 LOG.debug("File: " + file.getName() + " created"); | ||||
|             } | ||||
| 
 | ||||
|             @Override | ||||
|             public void onFileDelete(File file) { | ||||
|                 System.out.println("File: " + file.getName() + " deleted"); | ||||
|                 LOG.debug("File: " + file.getName() + " deleted"); | ||||
|             } | ||||
| 
 | ||||
|             @Override | ||||
|             public void onFileChange(File file) { | ||||
|                 System.out.println("File: " + file.getName() + " changed"); | ||||
|                 LOG.debug("File: " + file.getName() + " changed"); | ||||
|             } | ||||
|         }; | ||||
|         observer.addListener(listener); | ||||
|  | ||||
| @ -1,9 +1,14 @@ | ||||
| package com.baeldung.doublecolon; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.function.Function; | ||||
| 
 | ||||
| public class MacbookPro extends Computer { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(MacbookPro.class); | ||||
| 
 | ||||
|     public MacbookPro(int age, String color) { | ||||
|         super(age, color); | ||||
|     } | ||||
| @ -14,12 +19,12 @@ public class MacbookPro extends Computer { | ||||
| 
 | ||||
|     @Override | ||||
|     public void turnOnPc() { | ||||
|         System.out.println("MacbookPro turned on"); | ||||
|         LOG.debug("MacbookPro turned on"); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void turnOffPc() { | ||||
|         System.out.println("MacbookPro turned off"); | ||||
|         LOG.debug("MacbookPro turned off"); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
| @ -27,7 +32,7 @@ public class MacbookPro extends Computer { | ||||
| 
 | ||||
|         Function<Double, Double> function = super::calculateValue; | ||||
|         final Double pcValue = function.apply(initialValue); | ||||
|         System.out.println("First value is:" + pcValue); | ||||
|         LOG.debug("First value is:" + pcValue); | ||||
|         return pcValue + (initialValue / 10); | ||||
| 
 | ||||
|     } | ||||
|  | ||||
| @ -0,0 +1,19 @@ | ||||
| package com.baeldung.dynamicproxy; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.lang.reflect.InvocationHandler; | ||||
| import java.lang.reflect.Method; | ||||
| 
 | ||||
| public class DynamicInvocationHandler implements InvocationHandler { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class); | ||||
| 
 | ||||
|     @Override | ||||
|     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | ||||
|         LOGGER.info("Invoked method: {}", method.getName()); | ||||
| 
 | ||||
|         return 42; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,36 @@ | ||||
| package com.baeldung.dynamicproxy; | ||||
| 
 | ||||
| import java.lang.reflect.InvocationHandler; | ||||
| import java.lang.reflect.Method; | ||||
| import java.util.HashMap; | ||||
| import java.util.Map; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class TimingDynamicInvocationHandler implements InvocationHandler { | ||||
| 
 | ||||
|     private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class); | ||||
|     private final Map<String, Method> methods = new HashMap<>(); | ||||
| 
 | ||||
|     private Object target; | ||||
| 
 | ||||
|     public TimingDynamicInvocationHandler(Object target) { | ||||
|         this.target = target; | ||||
| 
 | ||||
|         for(Method method: target.getClass().getDeclaredMethods()) { | ||||
|             this.methods.put(method.getName(), method); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | ||||
|         long start = System.nanoTime(); | ||||
|         Object result = methods.get(method.getName()).invoke(target, args); | ||||
|         long elapsed = System.nanoTime() - start; | ||||
| 
 | ||||
|         LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed); | ||||
| 
 | ||||
|         return result; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,30 @@ | ||||
| package com.baeldung.exceptions; | ||||
| 
 | ||||
| import org.apache.commons.lang3.exception.ExceptionUtils; | ||||
| 
 | ||||
| import java.io.PrintWriter; | ||||
| import java.io.StringWriter; | ||||
| 
 | ||||
| public class StackTraceToString { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         // Convert a StackTrace to String using core java | ||||
|         try { | ||||
|             throw new NullPointerException(); | ||||
|         } catch (Exception e) { | ||||
|             StringWriter sw = new StringWriter(); | ||||
|             PrintWriter pw = new PrintWriter(sw); | ||||
|             e.printStackTrace(pw); | ||||
| 
 | ||||
|             System.out.println(sw.toString()); | ||||
|         } | ||||
| 
 | ||||
|         // Convert a StackTrace to String using Apache Commons | ||||
|         try { | ||||
|             throw new IndexOutOfBoundsException(); | ||||
|         } catch (Exception e) { | ||||
|             System.out.println(ExceptionUtils.getStackTrace(e)); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,21 @@ | ||||
| package com.baeldung.http; | ||||
| 
 | ||||
| import java.io.UnsupportedEncodingException; | ||||
| import java.net.URLEncoder; | ||||
| import java.util.Map; | ||||
| 
 | ||||
| public class ParameterStringBuilder { | ||||
|     public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException { | ||||
|         StringBuilder result = new StringBuilder(); | ||||
| 
 | ||||
|         for (Map.Entry<String, String> entry : params.entrySet()) { | ||||
|             result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); | ||||
|             result.append("="); | ||||
|             result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); | ||||
|             result.append("&"); | ||||
|         } | ||||
| 
 | ||||
|         String resultString = result.toString(); | ||||
|         return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString; | ||||
|     } | ||||
| } | ||||
| @ -1,6 +1,11 @@ | ||||
| package com.baeldung.java.map; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class MyKey { | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(MyKey.class); | ||||
|      | ||||
|     private String name; | ||||
|     private int id; | ||||
| 
 | ||||
| @ -27,7 +32,7 @@ public class MyKey { | ||||
| 
 | ||||
|     @Override | ||||
|     public int hashCode() { | ||||
|         System.out.println("Calling hashCode()"); | ||||
|         LOG.debug("Calling hashCode()"); | ||||
|         return id; | ||||
|     } | ||||
| 
 | ||||
| @ -38,7 +43,7 @@ public class MyKey { | ||||
| 
 | ||||
|     @Override | ||||
|     public boolean equals(Object obj) { | ||||
|         System.out.println("Calling equals() for key: " + obj); | ||||
|         LOG.debug("Calling equals() for key: " + obj); | ||||
|         if (this == obj) | ||||
|             return true; | ||||
|         if (obj == null) | ||||
|  | ||||
							
								
								
									
										51
									
								
								core-java/src/main/java/com/baeldung/jdbc/Employee.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										51
									
								
								core-java/src/main/java/com/baeldung/jdbc/Employee.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,51 @@ | ||||
| package com.baeldung.jdbc; | ||||
| 
 | ||||
| public class Employee { | ||||
|     private int id; | ||||
|     private String name; | ||||
|     private String position; | ||||
|     private double salary; | ||||
| 
 | ||||
|     public Employee() { | ||||
|     } | ||||
| 
 | ||||
|     public Employee(int id, String name, double salary, String position) { | ||||
|         this.id = id; | ||||
|         this.name = name; | ||||
|         this.salary = salary; | ||||
|         this.position = position; | ||||
|     } | ||||
| 
 | ||||
|     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; | ||||
|     } | ||||
| 
 | ||||
|     public double getSalary() { | ||||
|         return salary; | ||||
|     } | ||||
| 
 | ||||
|     public void setSalary(double salary) { | ||||
|         this.salary = salary; | ||||
|     } | ||||
| 
 | ||||
|     public String getPosition() { | ||||
|         return position; | ||||
|     } | ||||
| 
 | ||||
|     public void setPosition(String position) { | ||||
|         this.position = position; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -1,143 +0,0 @@ | ||||
| package com.baeldung.jdo; | ||||
| 
 | ||||
| import java.util.Collection; | ||||
| import java.util.Iterator; | ||||
| import java.util.List; | ||||
| import java.util.Random; | ||||
| import java.util.logging.Level; | ||||
| import java.util.logging.Logger; | ||||
| 
 | ||||
| import javax.jdo.PersistenceManager; | ||||
| import javax.jdo.PersistenceManagerFactory; | ||||
| import javax.jdo.Query; | ||||
| import javax.jdo.Transaction; | ||||
| 
 | ||||
| import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; | ||||
| import org.datanucleus.metadata.PersistenceUnitMetaData; | ||||
| 
 | ||||
| public class GuideToJDO { | ||||
| 
 | ||||
|     private static final Logger LOGGER = Logger.getLogger(GuideToJDO.class.getName()); | ||||
|     private Random rnd = new Random(); | ||||
|     private PersistenceUnitMetaData pumd; | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         new GuideToJDO(); | ||||
|     } | ||||
| 
 | ||||
|     public GuideToJDO() { | ||||
|         CreateProperties(); | ||||
|         CreateProducts(); | ||||
|         ListProducts(); | ||||
|         UpdateProducts(); | ||||
|         ListProducts(); | ||||
|         DeleteProducts(); | ||||
|         ListProducts(); | ||||
|     } | ||||
| 
 | ||||
|     public void CreateProperties(){ | ||||
|          | ||||
|         pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); | ||||
|         pumd.addClassName("com.baeldung.jdo.Product"); | ||||
|         pumd.setExcludeUnlistedClasses(); | ||||
|         pumd.addProperty("javax.jdo.option.ConnectionDriverName", "org.h2.Driver"); | ||||
|         pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence"); | ||||
|         pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa"); | ||||
|         pumd.addProperty("javax.jdo.option.ConnectionPassword", ""); | ||||
|         pumd.addProperty("datanucleus.autoCreateSchema", "true");         | ||||
|          | ||||
|     } | ||||
|      | ||||
|     public void CreateProducts() { | ||||
|         PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); | ||||
|         PersistenceManager pm = pmf.getPersistenceManager(); | ||||
|         Transaction tx = pm.currentTransaction(); | ||||
|         try { | ||||
|             tx.begin(); | ||||
|             Product product = new Product("Tablet", 80.0); | ||||
|             pm.makePersistent(product); | ||||
|             Product product2 = new Product("Phone", 20.0); | ||||
|             pm.makePersistent(product2); | ||||
|             Product product3 = new Product("Laptop", 200.0); | ||||
|             pm.makePersistent(product3); | ||||
|             for (int i = 0; i < 100; i++) { | ||||
|                 String nam = "Product-" + i; | ||||
|                 double price = rnd.nextDouble(); | ||||
|                 Product productx = new Product(nam, price); | ||||
|                 pm.makePersistent(productx); | ||||
|             } | ||||
|             tx.commit(); | ||||
|         } finally { | ||||
|             if (tx.isActive()) { | ||||
|                 tx.rollback(); | ||||
|             } | ||||
|             pm.close(); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     @SuppressWarnings("rawtypes") | ||||
|     public void UpdateProducts(){ | ||||
|         PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); | ||||
|         PersistenceManager pm = pmf.getPersistenceManager(); | ||||
|         Transaction tx = pm.currentTransaction(); | ||||
|         try { | ||||
|             tx.begin(); | ||||
|             Query query = pm.newQuery(Product.class, "name == \"Phone\""); | ||||
|             Collection result = (Collection) query.execute(); | ||||
|             Product product = (Product) result.iterator().next(); | ||||
|             product.setName("Android Phone"); | ||||
|             tx.commit(); | ||||
|         } finally { | ||||
|             if (tx.isActive()) { | ||||
|                 tx.rollback(); | ||||
|             }    | ||||
|             pm.close(); | ||||
|         } | ||||
|     } | ||||
|      | ||||
|     @SuppressWarnings("rawtypes") | ||||
|     public void DeleteProducts(){ | ||||
|         PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); | ||||
|         PersistenceManager pm = pmf.getPersistenceManager(); | ||||
|         Transaction tx = pm.currentTransaction(); | ||||
|         try { | ||||
|             tx.begin(); | ||||
|             Query query = pm.newQuery(Product.class, "name == \"Android Phone\""); | ||||
|             Collection result = (Collection) query.execute(); | ||||
|             Product product = (Product) result.iterator().next(); | ||||
|             pm.deletePersistent(product); | ||||
|             tx.commit(); | ||||
|         } finally { | ||||
|             if (tx.isActive()) { | ||||
|                 tx.rollback(); | ||||
|             }    | ||||
|             pm.close(); | ||||
|         } | ||||
|     } | ||||
|      | ||||
|     @SuppressWarnings({ "rawtypes", "unchecked" }) | ||||
|     public void ListProducts() { | ||||
|         PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null); | ||||
|         PersistenceManager pm = pmf.getPersistenceManager(); | ||||
|         Transaction tx = pm.currentTransaction(); | ||||
|         try { | ||||
|             tx.begin(); | ||||
| 
 | ||||
|             Query q = pm.newQuery("SELECT FROM " + Product.class.getName() + " WHERE price > 10"); | ||||
|             List<Product> products = (List<Product>) q.execute(); | ||||
|             Iterator<Product> iter = products.iterator(); | ||||
|             while (iter.hasNext()) { | ||||
|                 Product p = iter.next(); | ||||
|                 LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price }); | ||||
|             } | ||||
|             LOGGER.log(Level.INFO, "--------------------------------------------------------------"); | ||||
|             tx.commit(); | ||||
|         } finally { | ||||
|             if (tx.isActive()) { | ||||
|                 tx.rollback(); | ||||
|             } | ||||
| 
 | ||||
|             pm.close(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -1,23 +1,28 @@ | ||||
| package com.baeldung.jmx; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class Game implements GameMBean { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(Game.class); | ||||
| 
 | ||||
|     private String playerName; | ||||
| 
 | ||||
|     @Override | ||||
|     public void playFootball(String clubName) { | ||||
|         System.out.println(this.playerName + " playing football for " + clubName); | ||||
|         LOG.debug(this.playerName + " playing football for " + clubName); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public String getPlayerName() { | ||||
|         System.out.println("Return playerName " + this.playerName); | ||||
|         LOG.debug("Return playerName " + this.playerName); | ||||
|         return playerName; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void setPlayerName(String playerName) { | ||||
|         System.out.println("Set playerName to value " + playerName); | ||||
|         LOG.debug("Set playerName to value " + playerName); | ||||
|         this.playerName = playerName; | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -1,19 +1,20 @@ | ||||
| package com.baeldung.jmx; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import javax.management.*; | ||||
| import java.lang.management.ManagementFactory; | ||||
| import javax.management.InstanceAlreadyExistsException; | ||||
| import javax.management.MBeanRegistrationException; | ||||
| import javax.management.MBeanServer; | ||||
| import javax.management.MalformedObjectNameException; | ||||
| import javax.management.NotCompliantMBeanException; | ||||
| import javax.management.ObjectName; | ||||
| 
 | ||||
| public class JMXTutorialMainlauncher { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); | ||||
| 
 | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         // TODO Auto-generated method stub | ||||
| 
 | ||||
|         System.out.println("This is basic JMX tutorial"); | ||||
|         LOG.debug("This is basic JMX tutorial"); | ||||
|         ObjectName objectName = null; | ||||
|         try { | ||||
|             objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); | ||||
| @ -27,8 +28,8 @@ public class JMXTutorialMainlauncher { | ||||
|         } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { | ||||
|             e.printStackTrace(); | ||||
|         } | ||||
|         System.out.println("Registration for Game mbean with the platform server is successfull"); | ||||
|         System.out.println("Please open jconsole to access Game mbean"); | ||||
|         LOG.debug("Registration for Game mbean with the platform server is successfull"); | ||||
|         LOG.debug("Please open jconsole to access Game mbean"); | ||||
|         while (true) { | ||||
|             // to ensure application does not terminate | ||||
|         } | ||||
|  | ||||
| @ -1,9 +1,16 @@ | ||||
| package com.baeldung.socket; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.io.*; | ||||
| import java.net.*; | ||||
| 
 | ||||
| public class EchoClient { | ||||
| 
 | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class); | ||||
|      | ||||
|     private Socket clientSocket; | ||||
|     private PrintWriter out; | ||||
|     private BufferedReader in; | ||||
| @ -14,7 +21,7 @@ public class EchoClient { | ||||
|             out = new PrintWriter(clientSocket.getOutputStream(), true); | ||||
|             in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); | ||||
|         } catch (IOException e) { | ||||
|             System.out.print(e); | ||||
|             LOG.debug("Error when initializing connection", e); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| @ -34,7 +41,7 @@ public class EchoClient { | ||||
|             out.close(); | ||||
|             clientSocket.close(); | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             LOG.debug("error when closing", e); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
|  | ||||
| @ -1,9 +1,15 @@ | ||||
| package com.baeldung.socket; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.net.*; | ||||
| import java.io.*; | ||||
| 
 | ||||
| public class EchoMultiServer { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class); | ||||
| 
 | ||||
|     private ServerSocket serverSocket; | ||||
| 
 | ||||
|     public void start(int port) { | ||||
| @ -57,7 +63,7 @@ public class EchoMultiServer { | ||||
|                 clientSocket.close(); | ||||
| 
 | ||||
|             } catch (IOException e) { | ||||
|                 e.printStackTrace(); | ||||
|                 LOG.debug(e.getMessage()); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
| @ -1,9 +1,15 @@ | ||||
| package com.baeldung.socket; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.net.*; | ||||
| import java.io.*; | ||||
| 
 | ||||
| public class EchoServer { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class); | ||||
| 
 | ||||
|     private ServerSocket serverSocket; | ||||
|     private Socket clientSocket; | ||||
|     private PrintWriter out; | ||||
| @ -24,7 +30,7 @@ public class EchoServer { | ||||
|                 out.println(inputLine); | ||||
|             } | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             LOG.debug(e.getMessage()); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| @ -36,7 +42,7 @@ public class EchoServer { | ||||
|             clientSocket.close(); | ||||
|             serverSocket.close(); | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             LOG.debug(e.getMessage()); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
|  | ||||
| @ -1,5 +1,8 @@ | ||||
| package com.baeldung.socket; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStreamReader; | ||||
| @ -7,6 +10,9 @@ import java.io.PrintWriter; | ||||
| import java.net.Socket; | ||||
| 
 | ||||
| public class GreetClient { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class); | ||||
| 
 | ||||
|     private Socket clientSocket; | ||||
|     private PrintWriter out; | ||||
|     private BufferedReader in; | ||||
| @ -17,7 +23,7 @@ public class GreetClient { | ||||
|             out = new PrintWriter(clientSocket.getOutputStream(), true); | ||||
|             in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); | ||||
|         } catch (IOException e) { | ||||
| 
 | ||||
|             LOG.debug(e.getMessage()); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| @ -37,7 +43,7 @@ public class GreetClient { | ||||
|             out.close(); | ||||
|             clientSocket.close(); | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             LOG.debug(e.getMessage()); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -1,9 +1,15 @@ | ||||
| package com.baeldung.socket; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.net.*; | ||||
| import java.io.*; | ||||
| 
 | ||||
| public class GreetServer { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(GreetServer.class); | ||||
| 
 | ||||
|     private ServerSocket serverSocket; | ||||
|     private Socket clientSocket; | ||||
|     private PrintWriter out; | ||||
| @ -21,7 +27,7 @@ public class GreetServer { | ||||
|             else | ||||
|                 out.println("unrecognised greeting"); | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             LOG.debug(e.getMessage()); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
| @ -33,7 +39,7 @@ public class GreetServer { | ||||
|             clientSocket.close(); | ||||
|             serverSocket.close(); | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             LOG.debug(e.getMessage()); | ||||
|         } | ||||
| 
 | ||||
|     } | ||||
|  | ||||
| @ -1,9 +1,15 @@ | ||||
| package com.baeldung.stream; | ||||
| 
 | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| public class InfiniteStreams { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(InfiniteStreams.class); | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         doWhileOldWay(); | ||||
| 
 | ||||
| @ -15,7 +21,7 @@ public class InfiniteStreams { | ||||
| 
 | ||||
|         int i = 0; | ||||
|         while (i < 10) { | ||||
|             System.out.println(i); | ||||
|             LOG.debug("{}", i); | ||||
|             i++; | ||||
|         } | ||||
|     } | ||||
|  | ||||
| @ -1,7 +1,11 @@ | ||||
| package com.baeldung.threadlocal; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| public class ThreadLocalWithUserContext implements Runnable { | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalWithUserContext.class); | ||||
|      | ||||
|     private static final ThreadLocal<Context> userContext = new ThreadLocal<>(); | ||||
|     private final Integer userId; | ||||
|     private UserRepository userRepository = new UserRepository(); | ||||
| @ -15,6 +19,6 @@ public class ThreadLocalWithUserContext implements Runnable { | ||||
|     public void run() { | ||||
|         String userName = userRepository.getUserNameForUserId(userId); | ||||
|         userContext.set(new Context(userName)); | ||||
|         System.out.println("thread context for given userId: " + userId + " is: " + userContext.get()); | ||||
|         LOG.debug("thread context for given userId: " + userId + " is: " + userContext.get()); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -1,9 +1,15 @@ | ||||
| package com.baeldung.transferqueue; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.concurrent.TransferQueue; | ||||
| import java.util.concurrent.atomic.AtomicInteger; | ||||
| 
 | ||||
| public class Consumer implements Runnable { | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); | ||||
| 
 | ||||
|      | ||||
|     private final TransferQueue<String> transferQueue; | ||||
|     private final String name; | ||||
|     private final int numberOfMessagesToConsume; | ||||
| @ -19,10 +25,10 @@ public class Consumer implements Runnable { | ||||
|     public void run() { | ||||
|         for (int i = 0; i < numberOfMessagesToConsume; i++) { | ||||
|             try { | ||||
|                 System.out.println("Consumer: " + name + " is waiting to take element..."); | ||||
|                 LOG.debug("Consumer: " + name + " is waiting to take element..."); | ||||
|                 String element = transferQueue.take(); | ||||
|                 longProcessing(element); | ||||
|                 System.out.println("Consumer: " + name + " received element: " + element); | ||||
|                 LOG.debug("Consumer: " + name + " received element: " + element); | ||||
|             } catch (InterruptedException e) { | ||||
|                 e.printStackTrace(); | ||||
|             } | ||||
|  | ||||
| @ -1,10 +1,15 @@ | ||||
| package com.baeldung.transferqueue; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.concurrent.TimeUnit; | ||||
| import java.util.concurrent.TransferQueue; | ||||
| import java.util.concurrent.atomic.AtomicInteger; | ||||
| 
 | ||||
| public class Producer implements Runnable { | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(Producer.class); | ||||
| 
 | ||||
|     private final TransferQueue<String> transferQueue; | ||||
|     private final String name; | ||||
|     private final Integer numberOfMessagesToProduce; | ||||
| @ -20,13 +25,13 @@ public class Producer implements Runnable { | ||||
|     public void run() { | ||||
|         for (int i = 0; i < numberOfMessagesToProduce; i++) { | ||||
|             try { | ||||
|                 System.out.println("Producer: " + name + " is waiting to transfer..."); | ||||
|                 LOG.debug("Producer: " + name + " is waiting to transfer..."); | ||||
|                 boolean added = transferQueue.tryTransfer("A" + i, 4000, TimeUnit.MILLISECONDS); | ||||
|                 if (added) { | ||||
|                     numberOfProducedMessages.incrementAndGet(); | ||||
|                     System.out.println("Producer: " + name + " transferred element: A" + i); | ||||
|                     LOG.debug("Producer: " + name + " transferred element: A" + i); | ||||
|                 } else { | ||||
|                     System.out.println("can not add an element due to the timeout"); | ||||
|                     LOG.debug("can not add an element due to the timeout"); | ||||
|                 } | ||||
|             } catch (InterruptedException e) { | ||||
|                 e.printStackTrace(); | ||||
|  | ||||
							
								
								
									
										6
									
								
								core-java/src/main/resources/log4j.properties
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										6
									
								
								core-java/src/main/resources/log4j.properties
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,6 @@ | ||||
| log4j.rootLogger=DEBUG, A1 | ||||
| 
 | ||||
| log4j.appender.A1=org.apache.log4j.ConsoleAppender | ||||
| 
 | ||||
| log4j.appender.A1.layout=org.apache.log4j.PatternLayout | ||||
| log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n | ||||
| @ -1,14 +1,15 @@ | ||||
| package com.baeldung; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import static org.junit.Assert.*; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| /** | ||||
|  * | ||||
|  * @author paulo.motta | ||||
|  */ | ||||
| public class PrimitiveConversionsJUnitTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(PrimitiveConversionsJUnitTest.class); | ||||
|      | ||||
|     @Test | ||||
|     public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() { | ||||
|         int myInt = 127; | ||||
| @ -60,36 +61,36 @@ public class PrimitiveConversionsJUnitTest { | ||||
|     @Test | ||||
|     public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){ | ||||
|         byte myLargeValueByte = (byte) 130;   //0b10000010 | ||||
|         System.out.println(myLargeValueByte); //0b10000010 -126 | ||||
|         LOG.debug("{}", myLargeValueByte); //0b10000010 -126 | ||||
|         assertEquals( -126, myLargeValueByte); | ||||
|          | ||||
|         int myLargeValueInt = myLargeValueByte; | ||||
|         System.out.println(myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126 | ||||
|         LOG.debug("{}", myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126 | ||||
|         assertEquals( -126, myLargeValueInt); | ||||
|          | ||||
|         char myLargeValueChar = (char) myLargeValueByte; | ||||
|         System.out.println(myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82 | ||||
|         LOG.debug("{}", myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82 | ||||
|         assertEquals(0xFF82, myLargeValueChar); | ||||
|          | ||||
|         myLargeValueInt = myLargeValueChar; | ||||
|         System.out.println(myLargeValueInt); //0b11111111 10000010  65410 | ||||
|         LOG.debug("{}", myLargeValueInt); //0b11111111 10000010  65410 | ||||
|         assertEquals(65410, myLargeValueInt); | ||||
|          | ||||
|         byte myOtherByte = (byte) myLargeValueInt; | ||||
|         System.out.println(myOtherByte); //0b10000010 -126 | ||||
|         LOG.debug("{}", myOtherByte); //0b10000010 -126 | ||||
|         assertEquals( -126, myOtherByte); | ||||
|          | ||||
|          | ||||
|         char myLargeValueChar2 = 130; //This is an int not a byte! | ||||
|         System.out.println(myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082 | ||||
|         LOG.debug("{}", myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082 | ||||
|         assertEquals(0x0082, myLargeValueChar2); | ||||
|          | ||||
|         int myLargeValueInt2 = myLargeValueChar2; | ||||
|         System.out.println(myLargeValueInt2); //0b00000000 10000010  130 | ||||
|         LOG.debug("{}", myLargeValueInt2); //0b00000000 10000010  130 | ||||
|         assertEquals(130, myLargeValueInt2); | ||||
|          | ||||
|         byte myOtherByte2 = (byte) myLargeValueInt2; | ||||
|         System.out.println(myOtherByte2); //0b10000010 -126 | ||||
|         LOG.debug("{}", myOtherByte2); //0b10000010 -126 | ||||
|         assertEquals( -126, myOtherByte2); | ||||
|     } | ||||
|      | ||||
|  | ||||
| @ -1,20 +1,21 @@ | ||||
| package com.baeldung.completablefuture; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.concurrent.*; | ||||
| import java.util.stream.Collectors; | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.util.concurrent.CancellationException; | ||||
| import java.util.concurrent.CompletableFuture; | ||||
| import java.util.concurrent.ExecutionException; | ||||
| import java.util.concurrent.Executors; | ||||
| import java.util.concurrent.Future; | ||||
| import java.util.stream.Collectors; | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class CompletableFutureUnitTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureUnitTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException { | ||||
|         Future<String> completableFuture = calculateAsync(); | ||||
| @ -72,7 +73,7 @@ public class CompletableFutureUnitTest { | ||||
|     public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { | ||||
|         CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); | ||||
| 
 | ||||
|         CompletableFuture<Void> future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s)); | ||||
|         CompletableFuture<Void> future = completableFuture.thenAccept(s -> LOG.debug("Computation returned: " + s)); | ||||
| 
 | ||||
|         future.get(); | ||||
|     } | ||||
| @ -81,7 +82,7 @@ public class CompletableFutureUnitTest { | ||||
|     public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException { | ||||
|         CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello"); | ||||
| 
 | ||||
|         CompletableFuture<Void> future = completableFuture.thenRun(() -> System.out.println("Computation finished.")); | ||||
|         CompletableFuture<Void> future = completableFuture.thenRun(() -> LOG.debug("Computation finished.")); | ||||
| 
 | ||||
|         future.get(); | ||||
|     } | ||||
| @ -111,7 +112,7 @@ public class CompletableFutureUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException { | ||||
|         CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> System.out.println(s1 + s2)); | ||||
|         CompletableFuture.supplyAsync(() -> "Hello").thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|  | ||||
| @ -17,9 +17,8 @@ public class LongAccumulatorTest { | ||||
|     public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException { | ||||
|         //given | ||||
|         ExecutorService executorService = Executors.newFixedThreadPool(8); | ||||
|         LongBinaryOperator higherValueFinder = (currentValue, previousValue) -> currentValue > previousValue ? currentValue : previousValue; | ||||
|         LongAccumulator accumulator = new LongAccumulator(higherValueFinder, 0L); | ||||
| 
 | ||||
|         LongBinaryOperator sum = Long::sum; | ||||
|         LongAccumulator accumulator = new LongAccumulator(sum, 0L); | ||||
|         int numberOfThreads = 4; | ||||
|         int numberOfIncrements = 100; | ||||
| 
 | ||||
| @ -32,10 +31,12 @@ public class LongAccumulatorTest { | ||||
|             executorService.execute(accumulateAction); | ||||
|         } | ||||
| 
 | ||||
| 
 | ||||
|         //then | ||||
|         executorService.awaitTermination(500, TimeUnit.MILLISECONDS); | ||||
|         executorService.shutdown(); | ||||
|         assertEquals(accumulator.get(), 20200); | ||||
| 
 | ||||
| 
 | ||||
|         assertEquals(accumulator.get(), 100); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -0,0 +1,53 @@ | ||||
| package com.baeldung.concurrent.copyonwrite; | ||||
| 
 | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.Iterator; | ||||
| import java.util.LinkedList; | ||||
| import java.util.List; | ||||
| import java.util.concurrent.CopyOnWriteArrayList; | ||||
| 
 | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| 
 | ||||
| 
 | ||||
| public class CopyOnWriteArrayListTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenCopyOnWriteList_whenIterateAndAddElementToUnderneathList_thenShouldNotChangeIterator() { | ||||
|         //given | ||||
|         final CopyOnWriteArrayList<Integer> numbers = | ||||
|                 new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8}); | ||||
| 
 | ||||
|         //when | ||||
|         Iterator<Integer> iterator = numbers.iterator(); | ||||
|         numbers.add(10); | ||||
| 
 | ||||
|         //then | ||||
|         List<Integer> result = new LinkedList<>(); | ||||
|         iterator.forEachRemaining(result::add); | ||||
|         assertThat(result).containsOnly(1, 3, 5, 8); | ||||
| 
 | ||||
|         //and | ||||
|         Iterator<Integer> iterator2 = numbers.iterator(); | ||||
|         List<Integer> result2 = new LinkedList<>(); | ||||
|         iterator2.forEachRemaining(result2::add); | ||||
| 
 | ||||
|         //then | ||||
|         assertThat(result2).containsOnly(1, 3, 5, 8, 10); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = UnsupportedOperationException.class) | ||||
|     public void givenCopyOnWriteList_whenIterateOverItAndTryToRemoveElement_thenShouldThrowException() { | ||||
|         //given | ||||
|         final CopyOnWriteArrayList<Integer> numbers = | ||||
|                 new CopyOnWriteArrayList<>(new Integer[]{1, 3, 5, 8}); | ||||
| 
 | ||||
|         //when | ||||
|         Iterator<Integer> iterator = numbers.iterator(); | ||||
|         while (iterator.hasNext()) { | ||||
|             iterator.remove(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -1,22 +1,22 @@ | ||||
| package com.baeldung.concurrent.future; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.util.concurrent.CancellationException; | ||||
| import java.util.concurrent.ExecutionException; | ||||
| import java.util.concurrent.Executors; | ||||
| import java.util.concurrent.Future; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| import java.util.concurrent.TimeoutException; | ||||
| 
 | ||||
| import org.junit.After; | ||||
| import org.junit.Before; | ||||
| import org.junit.Rule; | ||||
| import org.junit.Test; | ||||
| import org.junit.rules.TestName; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.concurrent.*; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class SquareCalculatorIntegrationTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(SquareCalculatorIntegrationTest.class); | ||||
| 
 | ||||
| public class SquareCalculatorUnitTest { | ||||
| 
 | ||||
|     @Rule | ||||
|     public TestName name = new TestName(); | ||||
| @ -33,7 +33,7 @@ public class SquareCalculatorUnitTest { | ||||
|         Future<Integer> result2 = squareCalculator.calculate(1000); | ||||
| 
 | ||||
|         while (!result1.isDone() || !result2.isDone()) { | ||||
|             System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); | ||||
|             LOG.debug(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); | ||||
| 
 | ||||
|             Thread.sleep(300); | ||||
|         } | ||||
| @ -59,7 +59,7 @@ public class SquareCalculatorUnitTest { | ||||
|         Future<Integer> result2 = squareCalculator.calculate(1000); | ||||
| 
 | ||||
|         while (!result1.isDone() || !result2.isDone()) { | ||||
|             System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); | ||||
|             LOG.debug(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); | ||||
| 
 | ||||
|             Thread.sleep(300); | ||||
|         } | ||||
| @ -89,6 +89,6 @@ public class SquareCalculatorUnitTest { | ||||
| 
 | ||||
|     @After | ||||
|     public void end() { | ||||
|         System.out.println(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start)); | ||||
|         LOG.debug(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start)); | ||||
|     } | ||||
| } | ||||
| @ -1,6 +1,8 @@ | ||||
| package com.baeldung.concurrent.priorityblockingqueue; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.concurrent.PriorityBlockingQueue; | ||||
| @ -9,7 +11,10 @@ import java.util.concurrent.TimeUnit; | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| import static org.assertj.core.util.Lists.newArrayList; | ||||
| 
 | ||||
| public class PriorityBlockingQueueUnitTest { | ||||
| public class PriorityBlockingQueueIntegrationTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(PriorityBlockingQueueIntegrationTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException { | ||||
| @ -32,11 +37,11 @@ public class PriorityBlockingQueueUnitTest { | ||||
|         PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(); | ||||
| 
 | ||||
|         final Thread thread = new Thread(() -> { | ||||
|             System.out.println("Polling..."); | ||||
|             LOG.debug("Polling..."); | ||||
|             while (true) { | ||||
|                 try { | ||||
|                     Integer poll = queue.take(); | ||||
|                     System.out.println("Polled: " + poll); | ||||
|                     LOG.debug("Polled: " + poll); | ||||
|                 } catch (InterruptedException e) { | ||||
|                 } | ||||
|             } | ||||
| @ -44,7 +49,7 @@ public class PriorityBlockingQueueUnitTest { | ||||
|         thread.start(); | ||||
| 
 | ||||
|         Thread.sleep(TimeUnit.SECONDS.toMillis(5)); | ||||
|         System.out.println("Adding to queue"); | ||||
|         LOG.debug("Adding to queue"); | ||||
| 
 | ||||
|         queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7)); | ||||
|         Thread.sleep(TimeUnit.SECONDS.toMillis(1)); | ||||
| @ -13,7 +13,7 @@ import java.util.stream.IntStream; | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class ConcurrentSkipListSetTest { | ||||
| public class ConcurrentSkipListSetIntegrationTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenThreadsProducingEvents_whenGetForEventsFromLastMinute_thenReturnThoseEventsInTheLockFreeWay() throws InterruptedException { | ||||
| @ -0,0 +1,57 @@ | ||||
| package com.baeldung.dynamicproxy; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.lang.reflect.Proxy; | ||||
| import java.util.HashMap; | ||||
| import java.util.Map; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.fail; | ||||
| 
 | ||||
| public class DynamicProxyTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenDynamicProxy_thenPutWorks() { | ||||
|         Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, new DynamicInvocationHandler()); | ||||
| 
 | ||||
|         proxyInstance.put("hello", "world"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenInlineDynamicProxy_thenGetWorksOtherMethodsDoNot() { | ||||
|         Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, (proxy, method, methodArgs) -> { | ||||
| 
 | ||||
|             if (method.getName().equals("get")) { | ||||
|                 return 42; | ||||
|             } else { | ||||
|                 throw new UnsupportedOperationException("Unsupported method: " + method.getName()); | ||||
|             } | ||||
|         }); | ||||
| 
 | ||||
|         int result = (int) proxyInstance.get("hello"); | ||||
| 
 | ||||
|         assertEquals(42, result); | ||||
| 
 | ||||
|         try { | ||||
|             proxyInstance.put("hello", "world"); | ||||
|             fail(); | ||||
|         } catch(UnsupportedOperationException e) { | ||||
|             // expected | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenTimingDynamicProxy_thenMethodInvokationsProduceTiming() { | ||||
|         Map mapProxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { Map.class }, new TimingDynamicInvocationHandler(new HashMap<>())); | ||||
| 
 | ||||
|         mapProxyInstance.put("hello", "world"); | ||||
|         assertEquals("world", mapProxyInstance.get("hello")); | ||||
| 
 | ||||
|         CharSequence csProxyInstance = (CharSequence) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), new Class[] { CharSequence.class }, new TimingDynamicInvocationHandler("Hello World")); | ||||
| 
 | ||||
|         assertEquals('l', csProxyInstance.charAt(2)); | ||||
|         assertEquals(11, csProxyInstance.length()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -1,8 +1,9 @@ | ||||
| package com.baeldung.functionalinterface; | ||||
| 
 | ||||
| import static org.junit.Assert.assertArrayEquals; | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| import com.google.common.util.concurrent.Uninterruptibles; | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.Arrays; | ||||
| import java.util.HashMap; | ||||
| @ -14,12 +15,13 @@ import java.util.function.Supplier; | ||||
| import java.util.stream.Collectors; | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.google.common.util.concurrent.Uninterruptibles; | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| public class FunctionalInterfaceUnitTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(FunctionalInterfaceUnitTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() { | ||||
|         Map<String, Integer> nameMap = new HashMap<>(); | ||||
| @ -65,7 +67,7 @@ public class FunctionalInterfaceUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() { | ||||
|         Thread thread = new Thread(() -> System.out.println("Hello From Another Thread")); | ||||
|         Thread thread = new Thread(() -> LOG.debug("Hello From Another Thread")); | ||||
|         thread.start(); | ||||
|     } | ||||
| 
 | ||||
| @ -93,7 +95,7 @@ public class FunctionalInterfaceUnitTest { | ||||
|     @Test | ||||
|     public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() { | ||||
|         List<String> names = Arrays.asList("John", "Freddy", "Samuel"); | ||||
|         names.forEach(name -> System.out.println("Hello, " + name)); | ||||
|         names.forEach(name -> LOG.debug("Hello, " + name)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -103,7 +105,7 @@ public class FunctionalInterfaceUnitTest { | ||||
|         ages.put("Freddy", 24); | ||||
|         ages.put("Samuel", 30); | ||||
| 
 | ||||
|         ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old")); | ||||
|         ages.forEach((name, age) -> LOG.debug(name + " is " + age + " years old")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|  | ||||
							
								
								
									
										126
									
								
								core-java/src/test/java/com/baeldung/http/HttpRequestTest.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										126
									
								
								core-java/src/test/java/com/baeldung/http/HttpRequestTest.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,126 @@ | ||||
| package com.baeldung.http; | ||||
| 
 | ||||
| import org.apache.commons.lang.StringUtils; | ||||
| import org.junit.Test; | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.DataOutputStream; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStreamReader; | ||||
| import java.net.CookieManager; | ||||
| import java.net.HttpCookie; | ||||
| import java.net.HttpURLConnection; | ||||
| import java.net.URL; | ||||
| import java.util.HashMap; | ||||
| import java.util.List; | ||||
| import java.util.Map; | ||||
| import java.util.Optional; | ||||
| 
 | ||||
| public class HttpRequestTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGetRequest_thenOk() throws IOException { | ||||
|         URL url = new URL("http://example.com"); | ||||
|         HttpURLConnection con = (HttpURLConnection) url.openConnection(); | ||||
|         con.setRequestMethod("GET"); | ||||
| 
 | ||||
|         Map<String, String> parameters = new HashMap<>(); | ||||
|         parameters.put("param1", "val"); | ||||
|         con.setDoOutput(true); | ||||
|         DataOutputStream out = new DataOutputStream(con.getOutputStream()); | ||||
|         out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); | ||||
|         out.flush(); | ||||
|         out.close(); | ||||
| 
 | ||||
|         con.setConnectTimeout(5000); | ||||
|         con.setReadTimeout(5000); | ||||
| 
 | ||||
|         int status = con.getResponseCode(); | ||||
|         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); | ||||
|         String inputLine; | ||||
|         StringBuffer content = new StringBuffer(); | ||||
|         while ((inputLine = in.readLine()) != null) { | ||||
|             content.append(inputLine); | ||||
|         } | ||||
|         in.close(); | ||||
| 
 | ||||
|         assertEquals("status code incorrect", status, 200); | ||||
|         assertTrue("content incorrect", content.toString().contains("Example Domain")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPostRequest_thenOk() throws IOException { | ||||
|         URL url = new URL("http://example.com"); | ||||
|         HttpURLConnection con = (HttpURLConnection) url.openConnection(); | ||||
|         con.setRequestMethod("POST"); | ||||
|         con.setRequestProperty("Content-Type", "application/json"); | ||||
| 
 | ||||
|         Map<String, String> parameters = new HashMap<>(); | ||||
|         parameters.put("param1", "val"); | ||||
|         con.setDoOutput(true); | ||||
|         DataOutputStream out = new DataOutputStream(con.getOutputStream()); | ||||
|         out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); | ||||
|         out.flush(); | ||||
|         out.close(); | ||||
| 
 | ||||
|         int status = con.getResponseCode(); | ||||
|         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); | ||||
|         String inputLine; | ||||
|         StringBuffer content = new StringBuffer(); | ||||
|         while ((inputLine = in.readLine()) != null) { | ||||
|             content.append(inputLine); | ||||
|         } | ||||
|         in.close(); | ||||
| 
 | ||||
|         assertEquals("status code incorrect", status, 200); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGetCookies_thenOk() throws IOException { | ||||
|         URL url = new URL("http://example.com"); | ||||
|         HttpURLConnection con = (HttpURLConnection) url.openConnection(); | ||||
|         con.setRequestMethod("GET"); | ||||
| 
 | ||||
|         CookieManager cookieManager = new CookieManager(); | ||||
|         String cookiesHeader = con.getHeaderField("Set-Cookie"); | ||||
|         Optional<HttpCookie> usernameCookie = null; | ||||
|         if (cookiesHeader != null) { | ||||
|             List<HttpCookie> cookies = HttpCookie.parse(cookiesHeader); | ||||
|             cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie)); | ||||
|             usernameCookie = cookies.stream().findAny().filter(cookie -> cookie.getName().equals("username")); | ||||
|         } | ||||
| 
 | ||||
|         if (usernameCookie == null) { | ||||
|             cookieManager.getCookieStore().add(null, new HttpCookie("username", "john")); | ||||
|         } | ||||
| 
 | ||||
|         con.disconnect(); | ||||
| 
 | ||||
|         con = (HttpURLConnection) url.openConnection(); | ||||
|         con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";")); | ||||
| 
 | ||||
|         int status = con.getResponseCode(); | ||||
| 
 | ||||
|         assertEquals("status code incorrect", status, 200); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenRedirect_thenOk() throws IOException { | ||||
|         URL url = new URL("http://example.com"); | ||||
|         HttpURLConnection con = (HttpURLConnection) url.openConnection(); | ||||
|         con.setRequestMethod("GET"); | ||||
| 
 | ||||
|         con.setInstanceFollowRedirects(true); | ||||
|         int status = con.getResponseCode(); | ||||
| 
 | ||||
|         if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) { | ||||
|             String location = con.getHeaderField("Location"); | ||||
|             URL newUrl = new URL(location); | ||||
|             con = (HttpURLConnection) newUrl.openConnection(); | ||||
|         } | ||||
| 
 | ||||
|         assertEquals("status code incorrect", con.getResponseCode(), 200); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -6,9 +6,10 @@ import java.util.*; | ||||
| import java.util.concurrent.CopyOnWriteArrayList; | ||||
| 
 | ||||
| import static java.util.Arrays.asList; | ||||
| import static org.testng.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| public class ConcurrentModificationExceptionTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception { | ||||
|         ArrayList<Object> array = new ArrayList<>(asList(0, "one", 2, "three")); | ||||
|  | ||||
| @ -8,7 +8,9 @@ import java.util.TreeMap; | ||||
| import java.util.concurrent.*; | ||||
| import java.util.concurrent.atomic.AtomicInteger; | ||||
| 
 | ||||
| import static org.testng.Assert.*; | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertNotEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class ConcurrentNavigableMapManualTests { | ||||
| 
 | ||||
|  | ||||
| @ -1,24 +1,18 @@ | ||||
| package com.baeldung.java.map; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertFalse; | ||||
| import static org.junit.Assert.assertNull; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.util.Collection; | ||||
| import java.util.Comparator; | ||||
| import java.util.ConcurrentModificationException; | ||||
| import java.util.HashMap; | ||||
| import java.util.Iterator; | ||||
| import java.util.LinkedHashMap; | ||||
| import java.util.Map; | ||||
| import java.util.Map.Entry; | ||||
| import java.util.Set; | ||||
| import java.util.TreeMap; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.*; | ||||
| import java.util.Map.Entry; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| public class MapTest { | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(MapTest.class); | ||||
| 
 | ||||
|      | ||||
|     @Test | ||||
|     public void givenHashMap_whenRetrievesKeyset_thenCorrect() { | ||||
|         Map<String, String> map = new HashMap<>(); | ||||
| @ -208,22 +202,22 @@ public class MapTest { | ||||
|         MyKey k2 = new MyKey(2, "secondKey"); | ||||
|         MyKey k3 = new MyKey(2, "thirdKey"); | ||||
| 
 | ||||
|         System.out.println("storing value for k1"); | ||||
|         LOG.debug("storing value for k1"); | ||||
|         map.put(k1, "firstValue"); | ||||
| 
 | ||||
|         System.out.println("storing value for k2"); | ||||
|         LOG.debug("storing value for k2"); | ||||
|         map.put(k2, "secondValue"); | ||||
| 
 | ||||
|         System.out.println("storing value for k3"); | ||||
|         LOG.debug("storing value for k3"); | ||||
|         map.put(k3, "thirdValue"); | ||||
| 
 | ||||
|         System.out.println("retrieving value for k1"); | ||||
|         LOG.debug("retrieving value for k1"); | ||||
|         String v1 = map.get(k1); | ||||
| 
 | ||||
|         System.out.println("retrieving value for k2"); | ||||
|         LOG.debug("retrieving value for k2"); | ||||
|         String v2 = map.get(k2); | ||||
| 
 | ||||
|         System.out.println("retrieving value for k3"); | ||||
|         LOG.debug("retrieving value for k3"); | ||||
|         String v3 = map.get(k3); | ||||
| 
 | ||||
|         assertEquals("firstValue", v1); | ||||
|  | ||||
| @ -1,5 +1,8 @@ | ||||
| package com.baeldung.java.nio2.async; | ||||
| 
 | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStreamReader; | ||||
| @ -10,6 +13,8 @@ import java.util.concurrent.ExecutionException; | ||||
| import java.util.concurrent.Future; | ||||
| 
 | ||||
| public class AsyncEchoClient { | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(AsyncEchoClient.class); | ||||
| 
 | ||||
|     private AsynchronousSocketChannel client; | ||||
|     private Future<Void> future; | ||||
|     private static AsyncEchoClient instance; | ||||
| @ -75,11 +80,11 @@ public class AsyncEchoClient { | ||||
|         client.start(); | ||||
|         BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | ||||
|         String line; | ||||
|         System.out.println("Message to server:"); | ||||
|         LOG.debug("Message to server:"); | ||||
|         while ((line = br.readLine()) != null) { | ||||
|             String response = client.sendMessage(line); | ||||
|             System.out.println("response from server: " + response); | ||||
|             System.out.println("Message to server:"); | ||||
|             LOG.debug("response from server: " + response); | ||||
|             LOG.debug("Message to server:"); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -2,6 +2,8 @@ package com.baeldung.java.nio2.attributes; | ||||
| 
 | ||||
| import org.junit.BeforeClass; | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.io.IOException; | ||||
| import java.nio.file.Files; | ||||
| @ -15,6 +17,10 @@ import static org.junit.Assert.assertFalse; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class BasicAttribsTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     private static final String HOME = System.getProperty("user.home"); | ||||
|     private static BasicFileAttributes basicAttribs; | ||||
| 
 | ||||
| @ -31,9 +37,9 @@ public class BasicAttribsTest { | ||||
|         FileTime modified = basicAttribs.lastModifiedTime(); | ||||
|         FileTime accessed = basicAttribs.lastAccessTime(); | ||||
| 
 | ||||
|         System.out.println("Created: " + created); | ||||
|         System.out.println("Modified: " + modified); | ||||
|         System.out.println("Accessed: " + accessed); | ||||
|         LOG.debug("Created: " + created); | ||||
|         LOG.debug("Modified: " + modified); | ||||
|         LOG.debug("Accessed: " + accessed); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -1,18 +1,18 @@ | ||||
| package com.baeldung.java.set; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.*; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.util.ConcurrentModificationException; | ||||
| import java.util.HashSet; | ||||
| import java.util.Iterator; | ||||
| import java.util.Set; | ||||
| import java.util.TreeSet; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class SetTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(SetTest.class); | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenTreeSet_whenRetrievesObjects_thenNaturalOrder() { | ||||
|         Set<String> set = new TreeSet<>(); | ||||
| @ -44,22 +44,23 @@ public class SetTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenHashSetAndTreeSet_whenAddObjects_thenHashSetIsFaster() { | ||||
| 
 | ||||
|         long hashSetInsertionTime = measureExecution(() -> { | ||||
|             Set<String> set = new HashSet<>(); | ||||
|         long startTime = System.nanoTime(); | ||||
|             set.add("Baeldung"); | ||||
|             set.add("is"); | ||||
|             set.add("Awesome"); | ||||
|         long endTime = System.nanoTime(); | ||||
|         long duration1 = (endTime - startTime); | ||||
|         }); | ||||
| 
 | ||||
|         Set<String> set2 = new TreeSet<>(); | ||||
|         startTime = System.nanoTime(); | ||||
|         set2.add("Baeldung"); | ||||
|         set2.add("is"); | ||||
|         set2.add("Awesome"); | ||||
|         endTime = System.nanoTime(); | ||||
|         long duration2 = (endTime - startTime); | ||||
|         assertTrue(duration1 < duration2); | ||||
|         long treeSetInsertionTime = measureExecution(() -> { | ||||
|             Set<String> set = new TreeSet<>(); | ||||
|             set.add("Baeldung"); | ||||
|             set.add("is"); | ||||
|             set.add("Awesome"); | ||||
|         }); | ||||
| 
 | ||||
|         LOG.debug("HashSet insertion time: {}", hashSetInsertionTime); | ||||
|         LOG.debug("TreeSet insertion time: {}", treeSetInsertionTime); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -86,4 +87,13 @@ public class SetTest { | ||||
|             it.next(); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     private static long measureExecution(Runnable task) { | ||||
|         long startTime = System.nanoTime(); | ||||
|         task.run(); | ||||
|         long endTime = System.nanoTime(); | ||||
|         long executionTime = endTime - startTime; | ||||
|         LOG.debug(String.valueOf(executionTime)); | ||||
|         return executionTime; | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -1,13 +1,17 @@ | ||||
| package com.baeldung.java8; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.List; | ||||
| import java.util.function.Consumer; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class Java8ForEachTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(Java8ForEachTest.class); | ||||
| 
 | ||||
|     @Test | ||||
|     public void compareForEachMethods_thenPrintResults() { | ||||
| 
 | ||||
| @ -19,33 +23,33 @@ public class Java8ForEachTest { | ||||
|         names.add("Ellen"); | ||||
| 
 | ||||
|         // Java 5 - for-loop | ||||
|         System.out.println("--- Enhanced for-loop ---"); | ||||
|         LOG.debug("--- Enhanced for-loop ---"); | ||||
|         for (String name : names) { | ||||
|             System.out.println(name); | ||||
|             LOG.debug(name); | ||||
|         } | ||||
| 
 | ||||
|         // Java 8 - forEach | ||||
|         System.out.println("--- forEach method ---"); | ||||
|         names.forEach(name -> System.out.println(name)); | ||||
|         LOG.debug("--- forEach method ---"); | ||||
|         names.forEach(name -> LOG.debug(name)); | ||||
| 
 | ||||
|         // Anonymous inner class that implements Consumer interface | ||||
|         System.out.println("--- Anonymous inner class ---"); | ||||
|         LOG.debug("--- Anonymous inner class ---"); | ||||
|         names.forEach(new Consumer<String>() { | ||||
|             public void accept(String name) { | ||||
|                 System.out.println(name); | ||||
|                 LOG.debug(name); | ||||
|             } | ||||
|         }); | ||||
| 
 | ||||
|         // Create a Consumer implementation to then use in a forEach method | ||||
|         Consumer<String> consumerNames = name -> { | ||||
|             System.out.println(name); | ||||
|             LOG.debug(name); | ||||
|         }; | ||||
|         System.out.println("--- Implementation of Consumer interface ---"); | ||||
|         LOG.debug("--- Implementation of Consumer interface ---"); | ||||
|         names.forEach(consumerNames); | ||||
| 
 | ||||
|         // Print elements using a Method Reference | ||||
|         System.out.println("--- Method Reference ---"); | ||||
|         names.forEach(System.out::println); | ||||
|         LOG.debug("--- Method Reference ---"); | ||||
|         names.forEach(LOG::debug); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -2,6 +2,8 @@ package com.baeldung.java8; | ||||
| 
 | ||||
| import org.junit.Assert; | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.io.PrintWriter; | ||||
| import java.io.StringWriter; | ||||
| @ -10,6 +12,9 @@ import java.util.Scanner; | ||||
| 
 | ||||
| public class JavaTryWithResourcesLongRunningUnitTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(JavaTryWithResourcesLongRunningUnitTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     private static final String TEST_STRING_HELLO_WORLD = "Hello World"; | ||||
|     private Date resource1Date, resource2Date; | ||||
| 
 | ||||
| @ -52,32 +57,32 @@ public class JavaTryWithResourcesLongRunningUnitTest { | ||||
| 
 | ||||
|     class AutoCloseableResourcesFirst implements AutoCloseable { | ||||
|         public AutoCloseableResourcesFirst() { | ||||
|             System.out.println("Constructor -> AutoCloseableResources_First"); | ||||
|             LOG.debug("Constructor -> AutoCloseableResources_First"); | ||||
|         } | ||||
| 
 | ||||
|         public void doSomething() { | ||||
|             System.out.println("Something -> AutoCloseableResources_First"); | ||||
|             LOG.debug("Something -> AutoCloseableResources_First"); | ||||
|         } | ||||
| 
 | ||||
|         @Override | ||||
|         public void close() throws Exception { | ||||
|             System.out.println("Closed AutoCloseableResources_First"); | ||||
|             LOG.debug("Closed AutoCloseableResources_First"); | ||||
|             resource1Date = new Date(); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     class AutoCloseableResourcesSecond implements AutoCloseable { | ||||
|         public AutoCloseableResourcesSecond() { | ||||
|             System.out.println("Constructor -> AutoCloseableResources_Second"); | ||||
|             LOG.debug("Constructor -> AutoCloseableResources_Second"); | ||||
|         } | ||||
| 
 | ||||
|         public void doSomething() { | ||||
|             System.out.println("Something -> AutoCloseableResources_Second"); | ||||
|             LOG.debug("Something -> AutoCloseableResources_Second"); | ||||
|         } | ||||
| 
 | ||||
|         @Override | ||||
|         public void close() throws Exception { | ||||
|             System.out.println("Closed AutoCloseableResources_Second"); | ||||
|             LOG.debug("Closed AutoCloseableResources_Second"); | ||||
|             resource2Date = new Date(); | ||||
|             Thread.sleep(10000); | ||||
|         } | ||||
|  | ||||
| @ -1,6 +1,4 @@ | ||||
| package com.baeldung.java8.comparator; | ||||
| /*     | ||||
| 
 | ||||
| import lombok.AllArgsConstructor; | ||||
| import lombok.Data; | ||||
| import lombok.EqualsAndHashCode; | ||||
| @ -22,4 +20,3 @@ public class Employee implements Comparable<Employee>{ | ||||
|     } | ||||
|      | ||||
| } | ||||
| */ | ||||
| @ -1,5 +1,4 @@ | ||||
| package com.baeldung.java8.comparator; | ||||
| /* | ||||
| import java.util.Arrays; | ||||
| import java.util.Comparator; | ||||
| 
 | ||||
| @ -164,5 +163,3 @@ public class Java8ComparatorTest { | ||||
| 
 | ||||
| 
 | ||||
| } | ||||
| 
 | ||||
| */ | ||||
| @ -2,6 +2,8 @@ package com.baeldung.java8.lambda.exceptions; | ||||
| 
 | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.io.IOException; | ||||
| import java.util.Arrays; | ||||
| @ -11,6 +13,9 @@ import static com.baeldung.java8.lambda.exceptions.LambdaExceptionWrappers.*; | ||||
| 
 | ||||
| public class LambdaExceptionWrappersTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     private List<Integer> integers; | ||||
| 
 | ||||
|     @Before | ||||
| @ -20,12 +25,12 @@ public class LambdaExceptionWrappersTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenNoExceptionFromLambdaWrapper_thenSuccess() { | ||||
|         integers.forEach(lambdaWrapper(i -> System.out.println(50 / i))); | ||||
|         integers.forEach(lambdaWrapper(i -> LOG.debug("{}", 50 / i))); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenNoExceptionFromConsumerWrapper_thenSuccess() { | ||||
|         integers.forEach(consumerWrapper(i -> System.out.println(50 / i), ArithmeticException.class)); | ||||
|         integers.forEach(consumerWrapper(i -> LOG.debug("{}", 50 / i), ArithmeticException.class)); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = RuntimeException.class) | ||||
|  | ||||
| @ -3,6 +3,8 @@ package com.baeldung.java8.optional; | ||||
| import com.baeldung.optional.Modem; | ||||
| import com.baeldung.optional.Person; | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.Arrays; | ||||
| import java.util.List; | ||||
| @ -12,6 +14,10 @@ import java.util.Optional; | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| public class OptionalTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(OptionalTest.class); | ||||
| 
 | ||||
|      | ||||
|     // creating Optional | ||||
|     @Test | ||||
|     public void whenCreatesEmptyOptional_thenCorrect() { | ||||
| @ -66,7 +72,7 @@ public class OptionalTest { | ||||
|     @Test | ||||
|     public void givenOptional_whenIfPresentWorks_thenCorrect() { | ||||
|         Optional<String> opt = Optional.of("baeldung"); | ||||
|         opt.ifPresent(name -> System.out.println(name.length())); | ||||
|         opt.ifPresent(name -> LOG.debug("{}", name.length())); | ||||
|     } | ||||
| 
 | ||||
|     // returning Value With get() | ||||
| @ -200,11 +206,11 @@ public class OptionalTest { | ||||
|     @Test | ||||
|     public void whenOrElseGetAndOrElseOverlap_thenCorrect() { | ||||
|         String text = null; | ||||
|         System.out.println("Using orElseGet:"); | ||||
|         LOG.debug("Using orElseGet:"); | ||||
|         String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); | ||||
|         assertEquals("Default Value", defaultText); | ||||
| 
 | ||||
|         System.out.println("Using orElse:"); | ||||
|         LOG.debug("Using orElse:"); | ||||
|         defaultText = Optional.ofNullable(text).orElse(getMyDefault()); | ||||
|         assertEquals("Default Value", defaultText); | ||||
|     } | ||||
| @ -212,11 +218,11 @@ public class OptionalTest { | ||||
|     @Test | ||||
|     public void whenOrElseGetAndOrElseDiffer_thenCorrect() { | ||||
|         String text = "Text present"; | ||||
|         System.out.println("Using orElseGet:"); | ||||
|         LOG.debug("Using orElseGet:"); | ||||
|         String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault); | ||||
|         assertEquals("Text present", defaultText); | ||||
| 
 | ||||
|         System.out.println("Using orElse:"); | ||||
|         LOG.debug("Using orElse:"); | ||||
|         defaultText = Optional.ofNullable(text).orElse(getMyDefault()); | ||||
|         assertEquals("Text present", defaultText); | ||||
|     } | ||||
| @ -229,7 +235,7 @@ public class OptionalTest { | ||||
|     } | ||||
| 
 | ||||
|     public String getMyDefault() { | ||||
|         System.out.println("Getting default value..."); | ||||
|         LOG.debug("Getting default value..."); | ||||
|         return "Default Value"; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										158
									
								
								core-java/src/test/java/com/baeldung/jdbc/JdbcTest.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										158
									
								
								core-java/src/test/java/com/baeldung/jdbc/JdbcTest.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,158 @@ | ||||
| package com.baeldung.jdbc; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| import java.sql.CallableStatement; | ||||
| import java.sql.Connection; | ||||
| import java.sql.DatabaseMetaData; | ||||
| import java.sql.DriverManager; | ||||
| import java.sql.PreparedStatement; | ||||
| import java.sql.ResultSet; | ||||
| import java.sql.ResultSetMetaData; | ||||
| import java.sql.SQLException; | ||||
| import java.sql.Statement; | ||||
| import java.sql.Types; | ||||
| import java.util.ArrayList; | ||||
| import java.util.List; | ||||
| import java.util.stream.IntStream; | ||||
| 
 | ||||
| import org.apache.log4j.Logger; | ||||
| import org.junit.After; | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class JdbcTest { | ||||
| 
 | ||||
|     private static final Logger LOG = Logger.getLogger(JdbcTest.class); | ||||
| 
 | ||||
|     private Connection con; | ||||
| 
 | ||||
|     @Before | ||||
|     public void setup() throws ClassNotFoundException, SQLException { | ||||
|         Class.forName("com.mysql.cj.jdbc.Driver"); | ||||
| 
 | ||||
|         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDb?noAccessToProcedureBodies=true", "user1", "pass"); | ||||
| 
 | ||||
|         Statement stmt = con.createStatement(); | ||||
| 
 | ||||
|         String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; | ||||
|         stmt.execute(tableSql); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenInsertUpdateRecord_thenCorrect() throws SQLException { | ||||
|         Statement stmt = con.createStatement(); | ||||
| 
 | ||||
|         String insertSql = "INSERT INTO employees(name, position, salary) values ('john', 'developer', 2000)"; | ||||
|         stmt.executeUpdate(insertSql); | ||||
| 
 | ||||
|         String selectSql = "SELECT * FROM employees"; | ||||
|         ResultSet resultSet = stmt.executeQuery(selectSql); | ||||
| 
 | ||||
|         List<Employee> employees = new ArrayList<>(); | ||||
| 
 | ||||
|         while (resultSet.next()) { | ||||
|             Employee emp = new Employee(); | ||||
|             emp.setId(resultSet.getInt("emp_id")); | ||||
|             emp.setName(resultSet.getString("name")); | ||||
|             emp.setSalary(resultSet.getDouble("salary")); | ||||
|             emp.setPosition(resultSet.getString("position")); | ||||
|             employees.add(emp); | ||||
|         } | ||||
| 
 | ||||
|         assertEquals("employees list size incorrect", 1, employees.size()); | ||||
|         assertEquals("name incorrect", "john", employees.iterator().next().getName()); | ||||
|         assertEquals("position incorrect", "developer", employees.iterator().next().getPosition()); | ||||
|         assertEquals("salary incorrect", 2000, employees.iterator().next().getSalary(), 0.1); | ||||
| 
 | ||||
|         Statement updatableStmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); | ||||
|         ResultSet updatableResultSet = updatableStmt.executeQuery(selectSql); | ||||
| 
 | ||||
|         updatableResultSet.moveToInsertRow(); | ||||
|         updatableResultSet.updateString("name", "mark"); | ||||
|         updatableResultSet.updateString("position", "analyst"); | ||||
|         updatableResultSet.updateDouble("salary", 2000); | ||||
|         updatableResultSet.insertRow(); | ||||
| 
 | ||||
|         String updatePositionSql = "UPDATE employees SET position=? WHERE emp_id=?"; | ||||
|         PreparedStatement pstmt = con.prepareStatement(updatePositionSql); | ||||
|         pstmt.setString(1, "lead developer"); | ||||
|         pstmt.setInt(2, 1); | ||||
| 
 | ||||
|         String updateSalarySql = "UPDATE employees SET salary=? WHERE emp_id=?"; | ||||
|         PreparedStatement pstmt2 = con.prepareStatement(updateSalarySql); | ||||
|         pstmt.setDouble(1, 3000); | ||||
|         pstmt.setInt(2, 1); | ||||
| 
 | ||||
|         boolean autoCommit = con.getAutoCommit(); | ||||
| 
 | ||||
|         try { | ||||
|             con.setAutoCommit(false); | ||||
|             pstmt.executeUpdate(); | ||||
|             pstmt2.executeUpdate(); | ||||
|             con.commit(); | ||||
|         } catch (SQLException exc) { | ||||
|             con.rollback(); | ||||
|         } finally { | ||||
|             con.setAutoCommit(autoCommit); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCallProcedure_thenCorrect() { | ||||
| 
 | ||||
|         try { | ||||
|             String preparedSql = "{call insertEmployee(?,?,?,?)}"; | ||||
|             CallableStatement cstmt = con.prepareCall(preparedSql); | ||||
|             cstmt.setString(2, "ana"); | ||||
|             cstmt.setString(3, "tester"); | ||||
|             cstmt.setDouble(4, 2000); | ||||
|             cstmt.registerOutParameter(1, Types.INTEGER); | ||||
|             cstmt.execute(); | ||||
|             int new_id = cstmt.getInt(1); | ||||
|             assertTrue(new_id > 0); | ||||
|         } catch (SQLException exc) { | ||||
|             LOG.error("Procedure incorrect or does not exist!"); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenReadMetadata_thenCorrect() throws SQLException { | ||||
| 
 | ||||
|         DatabaseMetaData dbmd = con.getMetaData(); | ||||
|         ResultSet tablesResultSet = dbmd.getTables(null, null, "%", null); | ||||
|         while (tablesResultSet.next()) { | ||||
|             LOG.info(tablesResultSet.getString("TABLE_NAME")); | ||||
|         } | ||||
| 
 | ||||
|         String selectSql = "SELECT * FROM employees"; | ||||
|         Statement stmt = con.createStatement(); | ||||
|         ResultSet resultSet = stmt.executeQuery(selectSql); | ||||
|         ResultSetMetaData rsmd = resultSet.getMetaData(); | ||||
|         int nrColumns = rsmd.getColumnCount(); | ||||
|         assertEquals(nrColumns, 4); | ||||
| 
 | ||||
|         IntStream.range(1, nrColumns).forEach(i -> { | ||||
|             try { | ||||
|                 LOG.info(rsmd.getColumnName(i)); | ||||
|             } catch (SQLException e) { | ||||
|                 e.printStackTrace(); | ||||
|             } | ||||
|         }); | ||||
|     } | ||||
| 
 | ||||
|     @After | ||||
|     public void closeConnection() throws SQLException { | ||||
| 
 | ||||
|         Statement updatableStmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); | ||||
|         ResultSet updatableResultSet = updatableStmt.executeQuery("SELECT * FROM employees"); | ||||
| 
 | ||||
|         while (updatableResultSet.next()) { | ||||
|             updatableResultSet.deleteRow(); | ||||
|         } | ||||
| 
 | ||||
|         con.close(); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,68 @@ | ||||
| package com.baeldung.mappedbytebuffer; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.nio.CharBuffer; | ||||
| import java.nio.MappedByteBuffer; | ||||
| import java.nio.channels.FileChannel; | ||||
| import java.nio.charset.Charset; | ||||
| import java.nio.file.Files; | ||||
| import java.nio.file.Path; | ||||
| import java.nio.file.Paths; | ||||
| import java.nio.file.StandardOpenOption; | ||||
| import java.util.EnumSet; | ||||
| import java.util.List; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertNotNull; | ||||
| 
 | ||||
| public class MappedByteBufferTest { | ||||
| 
 | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception { | ||||
|         //given | ||||
|         CharBuffer charBuffer = null; | ||||
|         Path pathToRead = getFileURIFromResources("fileToRead.txt"); | ||||
| 
 | ||||
|         //when | ||||
|         try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) { | ||||
|             MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); | ||||
| 
 | ||||
|             if (mappedByteBuffer != null) { | ||||
|                 charBuffer = Charset.forName("UTF-8").decode(mappedByteBuffer); | ||||
|             } | ||||
|         } | ||||
| 
 | ||||
|         //then | ||||
|         assertNotNull(charBuffer); | ||||
|         assertEquals(charBuffer.toString(), "This is a content of the file"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception { | ||||
|         //given | ||||
|         CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file"); | ||||
|         Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt"); | ||||
| 
 | ||||
|         //when | ||||
|         try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, | ||||
|                 EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) { | ||||
|             MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length()); | ||||
| 
 | ||||
|             if (mappedByteBuffer != null) { | ||||
|                 mappedByteBuffer.put(Charset.forName("utf-8").encode(charBuffer)); | ||||
|             } | ||||
|         } | ||||
| 
 | ||||
|         //then | ||||
|         List<String> fileContent = Files.readAllLines(pathToWrite); | ||||
|         assertEquals(fileContent.get(0), "This will be written to the file"); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     public Path getFileURIFromResources(String fileName) throws Exception { | ||||
|         ClassLoader classLoader = getClass().getClassLoader(); | ||||
|         return Paths.get(classLoader.getResource(fileName).getPath()); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										32
									
								
								core-java/src/test/java/com/baeldung/string/SplitTest.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										32
									
								
								core-java/src/test/java/com/baeldung/string/SplitTest.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,32 @@ | ||||
| package com.baeldung.string; | ||||
| 
 | ||||
| import org.apache.commons.lang.StringUtils; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.Arrays; | ||||
| 
 | ||||
| import static org.junit.Assert.assertArrayEquals; | ||||
| 
 | ||||
| public class SplitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenString_whenSplit_thenRetrunsArray_through_JavaLangString() { | ||||
|         assertArrayEquals("split by comma", Arrays.asList("peter", "james", "thomas").toArray(), "peter,james,thomas".split(",")); | ||||
|         assertArrayEquals("split by whitespace", Arrays.asList("car", "jeep", "scooter").toArray(), "car jeep scooter".split(" ")); | ||||
|         assertArrayEquals("split by hyphen", Arrays.asList("1", "120", "232323").toArray(), "1-120-232323".split("-")); | ||||
|         assertArrayEquals("split by dot", Arrays.asList("192", "168", "1", "178").toArray(), "192.168.1.178".split("\\.")); | ||||
|         assertArrayEquals("split by a regex", Arrays.asList("b", "a", "e", "l", "d", "u", "n", "g").toArray(), | ||||
|                           "b a, e, l.d u, n g".split("\\s+|,\\s*|\\.\\s*")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenString_whenSplit_thenRetrunsArray_through_StringUtils() { | ||||
|         StringUtils.split("car jeep scooter"); | ||||
| 
 | ||||
|         assertArrayEquals("split by whitespace", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car jeep scooter")); | ||||
|         assertArrayEquals("split by space, extra spaces ignored", Arrays.asList("car", "jeep", "scooter").toArray(), | ||||
|                           StringUtils.split("car    jeep   scooter")); | ||||
|         assertArrayEquals("split by colon", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car:jeep:scooter", ":")); | ||||
|         assertArrayEquals("split by dot", Arrays.asList("car", "jeep", "scooter").toArray(), StringUtils.split("car.jeep.scooter", ".")); | ||||
|     } | ||||
| } | ||||
| @ -3,6 +3,8 @@ package com.baeldung.synchronousqueue; | ||||
| import org.junit.FixMethodOrder; | ||||
| import org.junit.Test; | ||||
| import org.junit.runners.MethodSorters; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.concurrent.*; | ||||
| import java.util.concurrent.atomic.AtomicInteger; | ||||
| @ -12,6 +14,9 @@ import static junit.framework.TestCase.assertEquals; | ||||
| @FixMethodOrder(MethodSorters.NAME_ASCENDING) | ||||
| public class SynchronousQueueTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(SynchronousQueueTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenTwoThreads_whenWantToExchangeUsingLockGuardedVariable_thenItSucceed() throws InterruptedException { | ||||
|         //given | ||||
| @ -21,7 +26,7 @@ public class SynchronousQueueTest { | ||||
| 
 | ||||
|         Runnable producer = () -> { | ||||
|             Integer producedElement = ThreadLocalRandom.current().nextInt(); | ||||
|             System.out.println("Saving an element: " + producedElement + " to the exchange point"); | ||||
|             LOG.debug("Saving an element: " + producedElement + " to the exchange point"); | ||||
|             sharedState.set(producedElement); | ||||
|             countDownLatch.countDown(); | ||||
|         }; | ||||
| @ -30,7 +35,7 @@ public class SynchronousQueueTest { | ||||
|             try { | ||||
|                 countDownLatch.await(); | ||||
|                 Integer consumedElement = sharedState.get(); | ||||
|                 System.out.println("consumed an element: " + consumedElement + " from the exchange point"); | ||||
|                 LOG.debug("consumed an element: " + consumedElement + " from the exchange point"); | ||||
|             } catch (InterruptedException ex) { | ||||
|                 ex.printStackTrace(); | ||||
|             } | ||||
| @ -55,7 +60,7 @@ public class SynchronousQueueTest { | ||||
|         Runnable producer = () -> { | ||||
|             Integer producedElement = ThreadLocalRandom.current().nextInt(); | ||||
|             try { | ||||
|                 System.out.println("Saving an element: " + producedElement + " to the exchange point"); | ||||
|                 LOG.debug("Saving an element: " + producedElement + " to the exchange point"); | ||||
|                 queue.put(producedElement); | ||||
|             } catch (InterruptedException ex) { | ||||
|                 ex.printStackTrace(); | ||||
| @ -65,7 +70,7 @@ public class SynchronousQueueTest { | ||||
|         Runnable consumer = () -> { | ||||
|             try { | ||||
|                 Integer consumedElement = queue.take(); | ||||
|                 System.out.println("consumed an element: " + consumedElement + " from the exchange point"); | ||||
|                 LOG.debug("consumed an element: " + consumedElement + " from the exchange point"); | ||||
|             } catch (InterruptedException ex) { | ||||
|                 ex.printStackTrace(); | ||||
|             } | ||||
|  | ||||
| @ -7,7 +7,7 @@ import java.util.concurrent.ExecutionException; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| public class ThreadLocalTest { | ||||
| public class ThreadLocalIntegrationTest { | ||||
|     @Test | ||||
|     public void givenThreadThatStoresContextInAMap_whenStartThread_thenShouldSetContextForBothUsers() throws ExecutionException, InterruptedException { | ||||
|         //when | ||||
| @ -1,24 +1,19 @@ | ||||
| package com.baeldung.threadpool; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.concurrent.*; | ||||
| import java.util.concurrent.atomic.AtomicInteger; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| import java.util.concurrent.CountDownLatch; | ||||
| import java.util.concurrent.ExecutionException; | ||||
| import java.util.concurrent.Executor; | ||||
| import java.util.concurrent.ExecutorService; | ||||
| import java.util.concurrent.Executors; | ||||
| import java.util.concurrent.ForkJoinPool; | ||||
| import java.util.concurrent.Future; | ||||
| import java.util.concurrent.ScheduledExecutorService; | ||||
| import java.util.concurrent.ScheduledFuture; | ||||
| import java.util.concurrent.ThreadPoolExecutor; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| import java.util.concurrent.atomic.AtomicInteger; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class CoreThreadPoolIntegrationTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     @Test(timeout = 1000) | ||||
|     public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { | ||||
| 
 | ||||
| @ -26,7 +21,7 @@ public class CoreThreadPoolIntegrationTest { | ||||
| 
 | ||||
|         Executor executor = Executors.newSingleThreadExecutor(); | ||||
|         executor.execute(() -> { | ||||
|             System.out.println("Hello World"); | ||||
|             LOG.debug("Hello World"); | ||||
|             lock.countDown(); | ||||
|         }); | ||||
| 
 | ||||
| @ -115,7 +110,7 @@ public class CoreThreadPoolIntegrationTest { | ||||
| 
 | ||||
|         ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); | ||||
|         executor.schedule(() -> { | ||||
|             System.out.println("Hello World"); | ||||
|             LOG.debug("Hello World"); | ||||
|             lock.countDown(); | ||||
|         }, 500, TimeUnit.MILLISECONDS); | ||||
| 
 | ||||
| @ -130,7 +125,7 @@ public class CoreThreadPoolIntegrationTest { | ||||
| 
 | ||||
|         ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); | ||||
|         ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> { | ||||
|             System.out.println("Hello World"); | ||||
|             LOG.debug("Hello World"); | ||||
|             lock.countDown(); | ||||
|         }, 500, 100, TimeUnit.MILLISECONDS); | ||||
| 
 | ||||
|  | ||||
| @ -9,7 +9,7 @@ import java.util.concurrent.*; | ||||
| import static junit.framework.TestCase.assertEquals; | ||||
| 
 | ||||
| @FixMethodOrder(MethodSorters.NAME_ASCENDING) | ||||
| public class TransferQueueTest { | ||||
| public class TransferQueueIntegrationTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenMultipleConsumersAndProducers_thenProcessAllMessages() throws InterruptedException { | ||||
| @ -1,15 +1,10 @@ | ||||
| package org.baeldung.core.exceptions; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.File; | ||||
| import java.io.FileNotFoundException; | ||||
| import java.io.FileReader; | ||||
| import java.io.IOException; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import java.io.*; | ||||
| 
 | ||||
| public class FileNotFoundExceptionUnitTest { | ||||
| 
 | ||||
| @ -22,7 +17,7 @@ public class FileNotFoundExceptionUnitTest { | ||||
|         try { | ||||
|             readFailingFile(); | ||||
|         } catch (FileNotFoundException ex) { | ||||
|             throw new BusinessException("BusinessException: necessary file was not present.", ex); | ||||
|             throw new BusinessException("BusinessException: necessary file was not present."); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -35,7 +30,7 @@ public class FileNotFoundExceptionUnitTest { | ||||
|                 new File(fileName).createNewFile(); | ||||
|                 readFailingFile(); | ||||
|             } catch (IOException ioe) { | ||||
|                 throw new RuntimeException("BusinessException: even creation is not possible.", ioe); | ||||
|                 throw new RuntimeException("BusinessException: even creation is not possible."); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| @ -45,7 +40,7 @@ public class FileNotFoundExceptionUnitTest { | ||||
|         try { | ||||
|             readFailingFile(); | ||||
|         } catch (FileNotFoundException ex) { | ||||
|             LOG.error("Optional file " + fileName + " was not found.", ex); | ||||
|             LOG.error("Optional file " + fileName + " was not found."); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -56,8 +51,8 @@ public class FileNotFoundExceptionUnitTest { | ||||
|     } | ||||
| 
 | ||||
|     private class BusinessException extends RuntimeException { | ||||
|         BusinessException(String string, FileNotFoundException ex) { | ||||
|             super(string, ex); | ||||
|         BusinessException(String string) { | ||||
|             super(string); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -3,26 +3,31 @@ package org.baeldung.java; | ||||
| import org.apache.commons.lang3.RandomStringUtils; | ||||
| import org.apache.commons.math3.random.RandomDataGenerator; | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.nio.charset.Charset; | ||||
| import java.util.Random; | ||||
| 
 | ||||
| public class JavaRandomUnitTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     // tests - random long | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() { | ||||
|         final long generatedLong = new Random().nextLong(); | ||||
| 
 | ||||
|         System.out.println(generatedLong); | ||||
|         LOG.debug("{}", generatedLong); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() { | ||||
|         final long generatedLong = new RandomDataGenerator().getRandomGenerator().nextLong(); | ||||
| 
 | ||||
|         System.out.println(generatedLong); | ||||
|         LOG.debug("{}", generatedLong); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -31,7 +36,7 @@ public class JavaRandomUnitTest { | ||||
|         final long rightLimit = 10L; | ||||
|         final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit)); | ||||
| 
 | ||||
|         System.out.println(generatedLong); | ||||
|         LOG.debug("{}", generatedLong); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -40,7 +45,7 @@ public class JavaRandomUnitTest { | ||||
|         final long rightLimit = 100L; | ||||
|         final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit); | ||||
| 
 | ||||
|         System.out.println(generatedLong); | ||||
|         LOG.debug("{}", generatedLong); | ||||
|     } | ||||
| 
 | ||||
|     // tests - random int | ||||
| @ -49,7 +54,7 @@ public class JavaRandomUnitTest { | ||||
|     public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() { | ||||
|         final int generatedInteger = new Random().nextInt(); | ||||
| 
 | ||||
|         System.out.println(generatedInteger); | ||||
|         LOG.debug("{}", generatedInteger); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -58,14 +63,14 @@ public class JavaRandomUnitTest { | ||||
|         final int rightLimit = 10; | ||||
|         final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); | ||||
| 
 | ||||
|         System.out.println(generatedInteger); | ||||
|         LOG.debug("{}", generatedInteger); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() { | ||||
|         final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator().nextInt(); | ||||
| 
 | ||||
|         System.out.println(generatedInteger); | ||||
|         LOG.debug("{}", generatedInteger); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -74,7 +79,7 @@ public class JavaRandomUnitTest { | ||||
|         final int rightLimit = 10; | ||||
|         final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit); | ||||
| 
 | ||||
|         System.out.println(generatedInteger); | ||||
|         LOG.debug("{}", generatedInteger); | ||||
|     } | ||||
| 
 | ||||
|     // tests - random float | ||||
| @ -83,14 +88,14 @@ public class JavaRandomUnitTest { | ||||
|     public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() { | ||||
|         final float generatedFloat = new Random().nextFloat(); | ||||
| 
 | ||||
|         System.out.println(generatedFloat); | ||||
|         LOG.debug("{}", generatedFloat); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() { | ||||
|         final float generatedFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); | ||||
| 
 | ||||
|         System.out.println(generatedFloat); | ||||
|         LOG.debug("{}", generatedFloat); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -99,7 +104,7 @@ public class JavaRandomUnitTest { | ||||
|         final float rightLimit = 10F; | ||||
|         final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit); | ||||
| 
 | ||||
|         System.out.println(generatedFloat); | ||||
|         LOG.debug("{}", generatedFloat); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -109,7 +114,7 @@ public class JavaRandomUnitTest { | ||||
|         final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); | ||||
|         final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit); | ||||
| 
 | ||||
|         System.out.println(generatedFloat); | ||||
|         LOG.debug("{}", generatedFloat); | ||||
|     } | ||||
| 
 | ||||
|     // tests - random double | ||||
| @ -118,14 +123,14 @@ public class JavaRandomUnitTest { | ||||
|     public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() { | ||||
|         final double generatedDouble = Math.random(); | ||||
| 
 | ||||
|         System.out.println(generatedDouble); | ||||
|         LOG.debug("{}", generatedDouble); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { | ||||
|         final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); | ||||
| 
 | ||||
|         System.out.println(generatedDouble); | ||||
|         LOG.debug("{}", generatedDouble); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -134,7 +139,7 @@ public class JavaRandomUnitTest { | ||||
|         final double rightLimit = 10D; | ||||
|         final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit); | ||||
| 
 | ||||
|         System.out.println(generatedDouble); | ||||
|         LOG.debug("{}", generatedDouble); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -143,7 +148,7 @@ public class JavaRandomUnitTest { | ||||
|         final double rightLimit = 100D; | ||||
|         final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit); | ||||
| 
 | ||||
|         System.out.println(generatedDouble); | ||||
|         LOG.debug("{}", generatedDouble); | ||||
|     } | ||||
| 
 | ||||
|     // tests - random String | ||||
| @ -154,7 +159,7 @@ public class JavaRandomUnitTest { | ||||
|         new Random().nextBytes(array); | ||||
|         final String generatedString = new String(array, Charset.forName("UTF-8")); | ||||
| 
 | ||||
|         System.out.println(generatedString); | ||||
|         LOG.debug(generatedString); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -169,28 +174,28 @@ public class JavaRandomUnitTest { | ||||
|         } | ||||
|         final String generatedString = buffer.toString(); | ||||
| 
 | ||||
|         System.out.println(generatedString); | ||||
|         LOG.debug(generatedString); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingApache_whenGeneratingRandomString_thenCorrect() { | ||||
|         final String generatedString = RandomStringUtils.random(10); | ||||
| 
 | ||||
|         System.out.println(generatedString); | ||||
|         LOG.debug(generatedString); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { | ||||
|         final String generatedString = RandomStringUtils.randomAlphabetic(10); | ||||
| 
 | ||||
|         System.out.println(generatedString); | ||||
|         LOG.debug(generatedString); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { | ||||
|         final String generatedString = RandomStringUtils.randomAlphanumeric(10); | ||||
| 
 | ||||
|         System.out.println(generatedString); | ||||
|         LOG.debug(generatedString); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -200,7 +205,7 @@ public class JavaRandomUnitTest { | ||||
|         final boolean useNumbers = false; | ||||
|         final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); | ||||
| 
 | ||||
|         System.out.println(generatedString); | ||||
|         LOG.debug(generatedString); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
|  | ||||
| @ -1,5 +1,9 @@ | ||||
| package org.baeldung.java; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.Date; | ||||
| import java.util.Timer; | ||||
| import java.util.TimerTask; | ||||
| @ -7,10 +11,11 @@ import java.util.concurrent.Executors; | ||||
| import java.util.concurrent.ScheduledExecutorService; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class JavaTimerLongRunningUnitTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     // tests | ||||
| 
 | ||||
|     @Test | ||||
| @ -18,7 +23,7 @@ public class JavaTimerLongRunningUnitTest { | ||||
|         final TimerTask timerTask = new TimerTask() { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 System.out.println("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName()); | ||||
|                 LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread().getName()); | ||||
|             } | ||||
|         }; | ||||
|         final Timer timer = new Timer("Timer"); | ||||
| @ -35,7 +40,7 @@ public class JavaTimerLongRunningUnitTest { | ||||
|         final TimerTask repeatedTask = new TimerTask() { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 System.out.println("Task performed on " + new Date()); | ||||
|                 LOG.debug("Task performed on " + new Date()); | ||||
|             } | ||||
|         }; | ||||
|         final Timer timer = new Timer("Timer"); | ||||
| @ -53,7 +58,7 @@ public class JavaTimerLongRunningUnitTest { | ||||
|         final TimerTask repeatedTask = new TimerTask() { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 System.out.println("Task performed on " + new Date()); | ||||
|                 LOG.debug("Task performed on " + new Date()); | ||||
|             } | ||||
|         }; | ||||
|         final Timer timer = new Timer("Timer"); | ||||
| @ -71,7 +76,7 @@ public class JavaTimerLongRunningUnitTest { | ||||
|         final TimerTask task = new TimerTask() { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 System.out.println("Task performed on " + new Date()); | ||||
|                 LOG.debug("Task performed on " + new Date()); | ||||
|                 cancel(); | ||||
|             } | ||||
|         }; | ||||
| @ -89,7 +94,7 @@ public class JavaTimerLongRunningUnitTest { | ||||
|         final TimerTask task = new TimerTask() { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 System.out.println("Task performed on " + new Date()); | ||||
|                 LOG.debug("Task performed on " + new Date()); | ||||
|             } | ||||
|         }; | ||||
|         final Timer timer = new Timer("Timer"); | ||||
| @ -104,7 +109,7 @@ public class JavaTimerLongRunningUnitTest { | ||||
|         final TimerTask task = new TimerTask() { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 System.out.println("Task performed on " + new Date()); | ||||
|                 LOG.debug("Task performed on " + new Date()); | ||||
|             } | ||||
|         }; | ||||
|         final Timer timer = new Timer("Timer"); | ||||
| @ -120,7 +125,7 @@ public class JavaTimerLongRunningUnitTest { | ||||
|         final TimerTask repeatedTask = new TimerTask() { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 System.out.println("Task performed on " + new Date()); | ||||
|                 LOG.debug("Task performed on " + new Date()); | ||||
|             } | ||||
|         }; | ||||
|         final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); | ||||
|  | ||||
| @ -1,24 +1,28 @@ | ||||
| package org.baeldung.java.collections; | ||||
| 
 | ||||
| import com.google.common.collect.ImmutableList; | ||||
| import org.apache.commons.collections4.ListUtils; | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.Arrays; | ||||
| import java.util.Collections; | ||||
| import java.util.List; | ||||
| 
 | ||||
| import org.apache.commons.collections4.ListUtils; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.google.common.collect.ImmutableList; | ||||
| 
 | ||||
| public class CoreJavaCollectionsUnitTest { | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(CoreJavaCollectionsUnitTest.class); | ||||
| 
 | ||||
| 
 | ||||
|     // tests - | ||||
| 
 | ||||
|     @Test | ||||
|     public final void givenUsingTheJdk_whenArrayListIsSynchronized_thenCorrect() { | ||||
|         final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three")); | ||||
|         final List<String> synchronizedList = Collections.synchronizedList(list); | ||||
|         System.out.println("Synchronized List is: " + synchronizedList); | ||||
|         LOG.debug("Synchronized List is: " + synchronizedList); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = UnsupportedOperationException.class) | ||||
|  | ||||
| @ -1,18 +1,10 @@ | ||||
| package org.baeldung.java.io; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.DataInputStream; | ||||
| import java.io.File; | ||||
| import java.io.FileInputStream; | ||||
| import java.io.FileReader; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStreamReader; | ||||
| import java.io.RandomAccessFile; | ||||
| import java.io.SequenceInputStream; | ||||
| import java.io.StreamTokenizer; | ||||
| import java.io.*; | ||||
| import java.nio.ByteBuffer; | ||||
| import java.nio.channels.FileChannel; | ||||
| import java.nio.charset.Charset; | ||||
| @ -21,10 +13,14 @@ import java.nio.file.Path; | ||||
| import java.nio.file.Paths; | ||||
| import java.util.Scanner; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class JavaReadFromFileUnitTest { | ||||
| 
 | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class); | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenReadWithBufferedReader_thenCorrect() throws IOException { | ||||
|         final String expected_value = "Hello world"; | ||||
| @ -115,7 +111,7 @@ public class JavaReadFromFileUnitTest { | ||||
|         final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); | ||||
|         final String currentLine = reader.readLine(); | ||||
|         reader.close(); | ||||
|         System.out.println(currentLine); | ||||
|         LOG.debug(currentLine); | ||||
|         assertEquals(expected_value, currentLine); | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -1,11 +1,12 @@ | ||||
| package org.baeldung.java.lists; | ||||
| 
 | ||||
| import org.testng.Assert; | ||||
| import org.testng.annotations.Test; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.Arrays; | ||||
| import java.util.List; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| public class ListTestNgUnitTest { | ||||
| 
 | ||||
|     private final List<String> list1 = Arrays.asList("1", "2", "3", "4"); | ||||
| @ -14,8 +15,8 @@ public class ListTestNgUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenTestingForEquality_ShouldBeEqual() throws Exception { | ||||
|         Assert.assertEquals(list1, list2); | ||||
|         Assert.assertNotSame(list1, list2); | ||||
|         Assert.assertNotEquals(list1, list3); | ||||
|         assertEquals(list1, list2); | ||||
|         assertNotSame(list1, list2); | ||||
|         assertNotEquals(list1, list3); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -1,25 +1,30 @@ | ||||
| package org.baeldung.java.sandbox; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import java.util.Date; | ||||
| import java.util.Timer; | ||||
| import java.util.TimerTask; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class SandboxJavaManualTest { | ||||
| 
 | ||||
| 
 | ||||
|     private static final Logger LOG = LoggerFactory.getLogger(SandboxJavaManualTest.class); | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException { | ||||
|         final TimerTask timerTask = new TimerTask() { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 System.out.println("Time when was task performed" + new Date()); | ||||
|                 System.out.println("Thread's name: " + Thread.currentThread().getName()); | ||||
|                 LOG.debug("Time when was task performed" + new Date()); | ||||
|                 LOG.debug("Thread's name: " + Thread.currentThread().getName()); | ||||
|             } | ||||
|         }; | ||||
|         final Timer timer = new Timer("Thread's name"); | ||||
|         System.out.println("Current time:" + new Date()); | ||||
|         System.out.println("Thread's name: " + Thread.currentThread().getName()); | ||||
|         LOG.debug("Current time:" + new Date()); | ||||
|         LOG.debug("Thread's name: " + Thread.currentThread().getName()); | ||||
|         final long delay = 2L * 1000L; | ||||
|         timer.schedule(timerTask, delay); | ||||
|         Thread.sleep(delay); | ||||
| @ -33,16 +38,16 @@ public class SandboxJavaManualTest { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 count++; | ||||
|                 System.out.println("Time when task was performed: " + new Date()); | ||||
|                 System.out.println("Thread's name: " + Thread.currentThread().getName()); | ||||
|                 LOG.debug("Time when task was performed: " + new Date()); | ||||
|                 LOG.debug("Thread's name: " + Thread.currentThread().getName()); | ||||
|                 if (count >= 5) { | ||||
|                     cancel(); | ||||
|                 } | ||||
|             } | ||||
|         }; | ||||
|         final Timer timer = new Timer("Timer thread"); | ||||
|         System.out.println("Current time: " + new Date()); | ||||
|         System.out.println("Thread's name: " + Thread.currentThread().getName()); | ||||
|         LOG.debug("Current time: " + new Date()); | ||||
|         LOG.debug("Thread's name: " + Thread.currentThread().getName()); | ||||
|         final long delay = 2L * 1000L; | ||||
|         final long period = 1L * 1000L; | ||||
|         timer.scheduleAtFixedRate(repeatedTask, delay, period); | ||||
| @ -62,8 +67,8 @@ public class SandboxJavaManualTest { | ||||
|             @Override | ||||
|             public void run() { | ||||
|                 timesRunned++; | ||||
|                 System.out.println("Task performed on: " + new Date()); | ||||
|                 System.out.println("Thread's name: " + Thread.currentThread().getName()); | ||||
|                 LOG.debug("Task performed on: " + new Date()); | ||||
|                 LOG.debug("Thread's name: " + Thread.currentThread().getName()); | ||||
|                 if (timesRunned >= timesToRun) { | ||||
|                     cancel(); | ||||
|                 } | ||||
| @ -72,10 +77,10 @@ public class SandboxJavaManualTest { | ||||
|         final MyTask repeatedTask = new MyTask(); | ||||
|         repeatedTask.setTimesToRun(5); | ||||
|         final long delay = 2L * 1000L; | ||||
|         final long period = 1L * 1000L; | ||||
|         final long period = 1000L; | ||||
|         final Timer timer = new Timer("Timer"); | ||||
|         System.out.println("Current time: " + new Date()); | ||||
|         System.out.println("Thread's name: " + Thread.currentThread().getName()); | ||||
|         LOG.debug("Current time: " + new Date()); | ||||
|         LOG.debug("Thread's name: " + Thread.currentThread().getName()); | ||||
|         timer.scheduleAtFixedRate(repeatedTask, delay, period); | ||||
|         Thread.sleep(delay + period * repeatedTask.timesToRun); | ||||
|     } | ||||
|  | ||||
							
								
								
									
										1
									
								
								core-java/src/test/resources/fileToRead.txt
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										1
									
								
								core-java/src/test/resources/fileToRead.txt
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1 @@ | ||||
| This is a content of the file | ||||
| @ -77,14 +77,14 @@ | ||||
|           <target>${java.target.version}</target> | ||||
|         </configuration> | ||||
|       </plugin> | ||||
| 
 | ||||
|       <plugin> | ||||
|         <groupId>org.apache.maven.plugins</groupId> | ||||
|         <artifactId>maven-surefire-plugin</artifactId> | ||||
|         <version>${surefire.plugin.version}</version> | ||||
|         <configuration> | ||||
|           <includes> | ||||
|             <include>**/CalculatorTest.java</include> | ||||
|           </includes> | ||||
|           <excludes> | ||||
|             <exclude>**/*IntegrationTest.java</exclude> | ||||
|           </excludes> | ||||
|         </configuration> | ||||
|       </plugin> | ||||
|     </plugins> | ||||
|  | ||||
| @ -11,5 +11,5 @@ import cucumber.api.junit.Cucumber; | ||||
|     , plugin = { "pretty", "json:target/reports/json/calculator.json" } | ||||
|     , glue = {"com.baeldung.cucumber.calculator"} | ||||
| ) | ||||
| public class CalculatorTest { | ||||
| public class CalculatorIntegrationTest { | ||||
| } | ||||
| @ -1,16 +1,17 @@ | ||||
| package com.baeldung.disruptor; | ||||
| 
 | ||||
| import java.util.concurrent.ThreadFactory; | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| import com.lmax.disruptor.BusySpinWaitStrategy; | ||||
| import com.lmax.disruptor.RingBuffer; | ||||
| import com.lmax.disruptor.WaitStrategy; | ||||
| import com.lmax.disruptor.dsl.Disruptor; | ||||
| import com.lmax.disruptor.dsl.ProducerType; | ||||
| import com.lmax.disruptor.util.DaemonThreadFactory; | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class DisruptorTest { | ||||
| import java.util.concurrent.ThreadFactory; | ||||
| 
 | ||||
| public class DisruptorIntegrationTest { | ||||
|     private Disruptor<ValueEvent> disruptor; | ||||
|     private WaitStrategy waitStrategy; | ||||
| 
 | ||||
| @ -21,7 +22,7 @@ public class DisruptorTest { | ||||
| 
 | ||||
|     private void createDisruptor(final ProducerType producerType, final EventConsumer eventConsumer) { | ||||
|         final ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE; | ||||
|         disruptor = new Disruptor<ValueEvent>(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy); | ||||
|         disruptor = new Disruptor<>(ValueEvent.EVENT_FACTORY, 16, threadFactory, producerType, waitStrategy); | ||||
|         disruptor.handleEventsWith(eventConsumer.getEventHandler()); | ||||
|     } | ||||
| 
 | ||||
| @ -0,0 +1,70 @@ | ||||
| package org.baeldung.guava; | ||||
| import com.google.common.collect.ClassToInstanceMap; | ||||
| import com.google.common.collect.ImmutableClassToInstanceMap; | ||||
| import com.google.common.collect.MutableClassToInstanceMap; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| public class ClassToInstanceMapTests { | ||||
|     @Test | ||||
|     public void createEmptyImmutableMap() { | ||||
|         ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.of(); | ||||
|         assertTrue(map.isEmpty()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void createEmptyMutableMap() { | ||||
|         ClassToInstanceMap<Action> map = MutableClassToInstanceMap.create(); | ||||
|         assertTrue(map.isEmpty()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void createSingleEntryMap() { | ||||
|         ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.of(Save.class, new Save()); | ||||
|         assertEquals(1, map.size()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void createMapWithBuilder() { | ||||
|         ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.<Action>builder() | ||||
|                 .put(Save.class, new Save()) | ||||
|                 .put(Open.class, new Open()) | ||||
|                 .build(); | ||||
|         assertEquals(2, map.size()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldReturnElement() { | ||||
|         ClassToInstanceMap<Action> map = ImmutableClassToInstanceMap.of(Save.class, new Save()); | ||||
|         Action action = map.get(Save.class); | ||||
|         assertTrue(action instanceof Save); | ||||
| 
 | ||||
|         // Use getInstance to avoid casting | ||||
|         Save save = map.getInstance(Save.class); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void shouldPutElement() { | ||||
|         ClassToInstanceMap<Action> map = MutableClassToInstanceMap.create(); | ||||
|         map.put(Save.class, new Save()); | ||||
|         // Put again to get previous value returned | ||||
|         Action action = map.put(Save.class, new Save()); | ||||
|         assertTrue(action instanceof Save); | ||||
| 
 | ||||
|         // Use putInstance to avoid casting | ||||
|         Save save = map.putInstance(Save.class, new Save()); | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| abstract class Action { | ||||
| } | ||||
| 
 | ||||
| class Save extends Action { | ||||
| } | ||||
| 
 | ||||
| class Open extends Action { | ||||
| } | ||||
| 
 | ||||
| class Delete extends Action { | ||||
| } | ||||
| @ -0,0 +1,112 @@ | ||||
| package org.baeldung.guava; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.math.BigInteger; | ||||
| import java.math.RoundingMode; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.google.common.math.BigIntegerMath; | ||||
| 
 | ||||
| public class GuavaBigIntegerMathTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPerformBinomialOnTwoIntValues_shouldReturnResult() { | ||||
|         BigInteger result = BigIntegerMath.binomial(6, 3); | ||||
|         assertEquals(new BigInteger("20"), result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenProformCeilPowOfTwoBigIntegerValues_shouldReturnResult() { | ||||
|         BigInteger result = BigIntegerMath.ceilingPowerOfTwo(new BigInteger("20")); | ||||
|         assertEquals(new BigInteger("32"), result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenDivideTwoBigIntegerValues_shouldDivideThemAndReturnTheResultForCeilingRounding() { | ||||
|         BigInteger result = BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.CEILING); | ||||
|         assertEquals(new BigInteger("4"), result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenDivideTwoBigIntegerValues_shouldDivideThemAndReturnTheResultForFloorRounding() { | ||||
|         BigInteger result = BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.FLOOR); | ||||
|         assertEquals(new BigInteger("3"), result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenDivideTwoBigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         BigIntegerMath.divide(new BigInteger("10"), new BigInteger("3"), RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFactorailInteger_shouldFactorialThemAndReturnTheResultIfInIntRange() { | ||||
|         BigInteger result = BigIntegerMath.factorial(5); | ||||
|         assertEquals(new BigInteger("120"), result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFloorPowerOfInteger_shouldReturnValue() { | ||||
|         BigInteger result = BigIntegerMath.floorPowerOfTwo(new BigInteger("30")); | ||||
|         assertEquals(new BigInteger("16"), result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPowOfInteger_shouldReturnTrueIfPowerOfTwo() { | ||||
|         boolean result = BigIntegerMath.isPowerOfTwo(new BigInteger("16")); | ||||
|         assertTrue(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog10BigIntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = BigIntegerMath.log10(new BigInteger("30"), RoundingMode.CEILING); | ||||
|         assertEquals(2, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog10BigIntegerValues_shouldog10ThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = BigIntegerMath.log10(new BigInteger("30"), RoundingMode.FLOOR); | ||||
|         assertEquals(1, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenLog10BigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         BigIntegerMath.log10(new BigInteger("30"), RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog2BigIntegerValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = BigIntegerMath.log2(new BigInteger("30"), RoundingMode.CEILING); | ||||
|         assertEquals(5, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog2BigIntegerValues_shouldog2ThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = BigIntegerMath.log2(new BigInteger("30"), RoundingMode.FLOOR); | ||||
|         assertEquals(4, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenLog2BigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         BigIntegerMath.log2(new BigInteger("30"), RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSqrtBigIntegerValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() { | ||||
|         BigInteger result = BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.CEILING); | ||||
|         assertEquals(new BigInteger("6"), result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSqrtBigIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() { | ||||
|         BigInteger result = BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.FLOOR); | ||||
|         assertEquals(new BigInteger("5"), result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenSqrtBigIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         BigIntegerMath.sqrt(new BigInteger("30"), RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,98 @@ | ||||
| package org.baeldung.guava; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| import java.math.RoundingMode; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.google.common.math.DoubleMath; | ||||
| import com.google.common.math.IntMath; | ||||
| 
 | ||||
| public class GuavaDoubleMathTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFactorailDouble_shouldFactorialThemAndReturnTheResultIfInDoubleRange() { | ||||
|         double result = DoubleMath.factorial(5); | ||||
|         assertEquals(120, result, 0); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFactorailDouble_shouldFactorialThemAndReturnDoubkeInfIfNotInDoubletRange() { | ||||
|         double result = DoubleMath.factorial(Integer.MAX_VALUE); | ||||
|         assertEquals(Double.POSITIVE_INFINITY, result, 0); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFuzzyCompareDouble_shouldReturnZeroIfInRange() { | ||||
|         int result = DoubleMath.fuzzyCompare(4, 4.05, 0.6); | ||||
|         assertEquals(0, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFuzzyCompareDouble_shouldReturnNonZeroIfNotInRange() { | ||||
|         int result = DoubleMath.fuzzyCompare(4, 5, 0.1); | ||||
|         assertEquals(-1, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFuzzyEqualDouble_shouldReturnZeroIfInRange() { | ||||
|         boolean result = DoubleMath.fuzzyEquals(4, 4.05, 0.6); | ||||
|         assertTrue(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFuzzyEqualDouble_shouldReturnNonZeroIfNotInRange() { | ||||
|         boolean result = DoubleMath.fuzzyEquals(4, 5, 0.1); | ||||
|         assertFalse(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenMathematicalIntDouble_shouldReturnTrueIfInRange() { | ||||
|         boolean result = DoubleMath.isMathematicalInteger(5); | ||||
|         assertTrue(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenMathematicalIntDouble_shouldReturnFalseIfNotInRange() { | ||||
|         boolean result = DoubleMath.isMathematicalInteger(5.2); | ||||
|         assertFalse(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPowerOfTwoDouble_shouldReturnTrueIfIsPowerOfTwo() { | ||||
|         boolean result = DoubleMath.isMathematicalInteger(4); | ||||
|         assertTrue(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPowerOfTwoDouble_shouldReturnFalseIsNotPowerOfTwoe() { | ||||
|         boolean result = DoubleMath.isMathematicalInteger(5.2); | ||||
|         assertFalse(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog2Double_shouldReturnResult() { | ||||
|         double result = DoubleMath.log2(4); | ||||
|         assertEquals(2, result, 0); | ||||
|     } | ||||
|      | ||||
|      | ||||
|     @Test | ||||
|     public void whenLog2DoubleValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = DoubleMath.log2(30, RoundingMode.CEILING); | ||||
|         assertEquals(5, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog2DoubleValues_shouldog2ThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = DoubleMath.log2(30, RoundingMode.FLOOR); | ||||
|         assertEquals(4, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenLog2DoubleValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         DoubleMath.log2(30, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
							
								
								
									
										274
									
								
								guava/src/test/java/org/baeldung/guava/GuavaIntMathTest.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										274
									
								
								guava/src/test/java/org/baeldung/guava/GuavaIntMathTest.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,274 @@ | ||||
| package org.baeldung.guava; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| import java.math.RoundingMode; | ||||
| 
 | ||||
| import com.google.common.math.IntMath; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class GuavaIntMathTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPerformBinomialOnTwoIntegerValues_shouldReturnResultIfUnderInt() { | ||||
|         int result = IntMath.binomial(6, 3); | ||||
|         assertEquals(20, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPerformBinomialOnTwoIntegerValues_shouldReturnIntMaxIfUnderInt() { | ||||
|         int result = IntMath.binomial(Integer.MAX_VALUE, 3); | ||||
|         assertEquals(Integer.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenProformCeilPowOfTwoIntegerValues_shouldReturnResult() { | ||||
|         int result = IntMath.ceilingPowerOfTwo(20); | ||||
|         assertEquals(32, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCheckedAddTwoIntegerValues_shouldAddThemAndReturnTheSumIfNotOverflow() { | ||||
|         int result = IntMath.checkedAdd(1, 2); | ||||
|         assertEquals(3, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void gwhenCheckedAddTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() { | ||||
|         IntMath.checkedAdd(Integer.MAX_VALUE, 100); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCheckedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnTheResultIfNotOverflow() { | ||||
|         int result = IntMath.checkedMultiply(1, 2); | ||||
|         assertEquals(2, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void gwhenCheckedMultiplyTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() { | ||||
|         IntMath.checkedMultiply(Integer.MAX_VALUE, 100); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCheckedPowTwoIntegerValues_shouldPowThemAndReturnTheResultIfNotOverflow() { | ||||
|         int result = IntMath.checkedPow(2, 3); | ||||
|         assertEquals(8, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void gwhenCheckedPowTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() { | ||||
|         IntMath.checkedPow(Integer.MAX_VALUE, 100); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCheckedSubstractTwoIntegerValues_shouldSubstractThemAndReturnTheResultIfNotOverflow() { | ||||
|         int result = IntMath.checkedSubtract(4, 1); | ||||
|         assertEquals(3, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void gwhenCheckedSubstractTwoIntegerValues_shouldThrowArithmeticExceptionIfOverflow() { | ||||
|         IntMath.checkedSubtract(Integer.MAX_VALUE, -100); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenDivideTwoIntegerValues_shouldDivideThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = IntMath.divide(10, 3, RoundingMode.CEILING); | ||||
|         assertEquals(4, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenDivideTwoIntegerValues_shouldDivideThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = IntMath.divide(10, 3, RoundingMode.FLOOR); | ||||
|         assertEquals(3, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenDivideTwoIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         IntMath.divide(10, 3, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFactorailInteger_shouldFactorialThemAndReturnTheResultIfInIntRange() { | ||||
|         int result = IntMath.factorial(5); | ||||
|         assertEquals(120, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFactorailInteger_shouldFactorialThemAndReturnIntMaxIfNotInIntRange() { | ||||
|         int result = IntMath.factorial(Integer.MAX_VALUE); | ||||
|         assertEquals(Integer.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFloorPowerOfInteger_shouldReturnValue() { | ||||
|         int result = IntMath.floorPowerOfTwo(30); | ||||
|         assertEquals(16, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGcdOfTwoIntegers_shouldReturnValue() { | ||||
|         int result = IntMath.gcd(30, 40); | ||||
|         assertEquals(10, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPowOfInteger_shouldReturnTrueIfPowerOfTwo() { | ||||
|         boolean result = IntMath.isPowerOfTwo(16); | ||||
|         assertTrue(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPowOfInteger_shouldReturnFalseeIfNotPowerOfTwo() { | ||||
|         boolean result = IntMath.isPowerOfTwo(20); | ||||
|         assertFalse(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPrineOfInteger_shouldReturnFalseeIfNotPrime() { | ||||
|         boolean result = IntMath.isPrime(20); | ||||
|         assertFalse(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog10IntegerValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = IntMath.log10(30, RoundingMode.CEILING); | ||||
|         assertEquals(2, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog10IntegerValues_shouldog10ThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = IntMath.log10(30, RoundingMode.FLOOR); | ||||
|         assertEquals(1, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenLog10IntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         IntMath.log10(30, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog2IntegerValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = IntMath.log2(30, RoundingMode.CEILING); | ||||
|         assertEquals(5, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog2IntegerValues_shouldog2ThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = IntMath.log2(30, RoundingMode.FLOOR); | ||||
|         assertEquals(4, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenLog2IntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         IntMath.log2(30, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenMeanTwoIntegerValues_shouldMeanThemAndReturnTheResult() { | ||||
|         int result = IntMath.mean(30, 20); | ||||
|         assertEquals(25, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenModTwoIntegerValues_shouldModThemAndReturnTheResult() { | ||||
|         int result = IntMath.mod(30, 4); | ||||
|         assertEquals(2, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPowTwoIntegerValues_shouldPowThemAndReturnTheResult() { | ||||
|         int result = IntMath.pow(6, 4); | ||||
|         assertEquals(1296, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnTheResult() { | ||||
|         int result = IntMath.saturatedAdd(6, 4); | ||||
|         assertEquals(10, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnIntMaxIfOverflow() { | ||||
|         int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 1000); | ||||
|         assertEquals(Integer.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedAddTwoIntegerValues_shouldAddThemAndReturnIntMinIfUnderflow() { | ||||
|         int result = IntMath.saturatedAdd(Integer.MIN_VALUE, -1000); | ||||
|         assertEquals(Integer.MIN_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnTheResult() { | ||||
|         int result = IntMath.saturatedMultiply(6, 4); | ||||
|         assertEquals(24, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() { | ||||
|         int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 1000); | ||||
|         assertEquals(Integer.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedMultiplyTwoIntegerValues_shouldMultiplyThemAndReturnIntMinIfUnderflow() { | ||||
|         int result = IntMath.saturatedMultiply(Integer.MIN_VALUE, 1000); | ||||
|         assertEquals(Integer.MIN_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnTheResult() { | ||||
|         int result = IntMath.saturatedPow(6, 2); | ||||
|         assertEquals(36, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnIntMaxIfOverflow() { | ||||
|         int result = IntMath.saturatedPow(Integer.MAX_VALUE, 2); | ||||
|         assertEquals(Integer.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedPowTwoIntegerValues_shouldPowThemAndReturnIntMinIfUnderflow() { | ||||
|         int result = IntMath.saturatedPow(Integer.MIN_VALUE, 3); | ||||
|         assertEquals(Integer.MIN_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractThemAndReturnTheResult() { | ||||
|         int result = IntMath.saturatedSubtract(6, 2); | ||||
|         assertEquals(4, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractwThemAndReturnIntMaxIfOverflow() { | ||||
|         int result = IntMath.saturatedSubtract(Integer.MAX_VALUE, -2); | ||||
|         assertEquals(Integer.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedSubstractTwoIntegerValues_shouldSubstractThemAndReturnIntMinIfUnderflow() { | ||||
|         int result = IntMath.saturatedSubtract(Integer.MIN_VALUE, 3); | ||||
|         assertEquals(Integer.MIN_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = IntMath.sqrt(30, RoundingMode.CEILING); | ||||
|         assertEquals(6, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSqrtIntegerValues_shouldSqrtThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = IntMath.sqrt(30, RoundingMode.FLOOR); | ||||
|         assertEquals(5, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenSqrtIntegerValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         IntMath.sqrt(30, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
							
								
								
									
										268
									
								
								guava/src/test/java/org/baeldung/guava/GuavaLongMathTest.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										268
									
								
								guava/src/test/java/org/baeldung/guava/GuavaLongMathTest.java
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,268 @@ | ||||
| package org.baeldung.guava; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| import java.math.RoundingMode; | ||||
| 
 | ||||
| import com.google.common.math.LongMath; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class GuavaLongMathTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPerformBinomialOnTwoLongValues_shouldReturnResultIfUnderLong() { | ||||
|         long result = LongMath.binomial(6, 3); | ||||
|         assertEquals(20L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenProformCeilPowOfTwoLongValues_shouldReturnResult() { | ||||
|         long result = LongMath.ceilingPowerOfTwo(20L); | ||||
|         assertEquals(32L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCheckedAddTwoLongValues_shouldAddThemAndReturnTheSumIfNotOverflow() { | ||||
|         long result = LongMath.checkedAdd(1L, 2L); | ||||
|         assertEquals(3L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenCheckedAddTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() { | ||||
|         LongMath.checkedAdd(Long.MAX_VALUE, 100L); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCheckedMultiplyTwoLongValues_shouldMultiplyThemAndReturnTheResultIfNotOverflow() { | ||||
|         long result = LongMath.checkedMultiply(3L, 2L); | ||||
|         assertEquals(6L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenCheckedMultiplyTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() { | ||||
|         LongMath.checkedMultiply(Long.MAX_VALUE, 100L); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCheckedPowTwoLongValues_shouldPowThemAndReturnTheResultIfNotOverflow() { | ||||
|         long result = LongMath.checkedPow(2L, 3); | ||||
|         assertEquals(8L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void gwhenCheckedPowTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() { | ||||
|         LongMath.checkedPow(Long.MAX_VALUE, 100); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCheckedSubstractTwoLongValues_shouldSubstractThemAndReturnTheResultIfNotOverflow() { | ||||
|         long result = LongMath.checkedSubtract(4L, 1L); | ||||
|         assertEquals(3L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void gwhenCheckedSubstractTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() { | ||||
|         LongMath.checkedSubtract(Long.MAX_VALUE, -100); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenDivideTwoLongValues_shouldDivideThemAndReturnTheResultForCeilingRounding() { | ||||
|         long result = LongMath.divide(10L, 3L, RoundingMode.CEILING); | ||||
|         assertEquals(4L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenDivideTwoLongValues_shouldDivideThemAndReturnTheResultForFloorRounding() { | ||||
|         long result = LongMath.divide(10L, 3L, RoundingMode.FLOOR); | ||||
|         assertEquals(3L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenDivideTwoLongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         LongMath.divide(10L, 3L, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFactorailLong_shouldFactorialThemAndReturnTheResultIfInIntRange() { | ||||
|         long result = LongMath.factorial(5); | ||||
|         assertEquals(120L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFactorailLong_shouldFactorialThemAndReturnIntMaxIfNotInIntRange() { | ||||
|         long result = LongMath.factorial(Integer.MAX_VALUE); | ||||
|         assertEquals(Long.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFloorPowerOfLong_shouldReturnValue() { | ||||
|         long result = LongMath.floorPowerOfTwo(30L); | ||||
|         assertEquals(16L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGcdOfTwoLongs_shouldReturnValue() { | ||||
|         long result = LongMath.gcd(30L, 40L); | ||||
|         assertEquals(10L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPowOfLong_shouldReturnTrueIfPowerOfTwo() { | ||||
|         boolean result = LongMath.isPowerOfTwo(16L); | ||||
|         assertTrue(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPowOfLong_shouldReturnFalseeIfNotPowerOfTwo() { | ||||
|         boolean result = LongMath.isPowerOfTwo(20L); | ||||
|         assertFalse(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenIsPrineOfLong_shouldReturnFalseeIfNotPrime() { | ||||
|         boolean result = LongMath.isPrime(20L); | ||||
|         assertFalse(result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog10LongValues_shouldLog10ThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = LongMath.log10(30L, RoundingMode.CEILING); | ||||
|         assertEquals(2, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog10LongValues_shouldog10ThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = LongMath.log10(30L, RoundingMode.FLOOR); | ||||
|         assertEquals(1, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenLog10LongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         LongMath.log10(30L, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog2LongValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { | ||||
|         int result = LongMath.log2(30L, RoundingMode.CEILING); | ||||
|         assertEquals(5, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenLog2LongValues_shouldog2ThemAndReturnTheResultForFloorRounding() { | ||||
|         int result = LongMath.log2(30L, RoundingMode.FLOOR); | ||||
|         assertEquals(4, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenLog2LongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         LongMath.log2(30L, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenMeanTwoLongValues_shouldMeanThemAndReturnTheResult() { | ||||
|         long result = LongMath.mean(30L, 20L); | ||||
|         assertEquals(25L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenModLongAndIntegerValues_shouldModThemAndReturnTheResult() { | ||||
|         int result = LongMath.mod(30L, 4); | ||||
|         assertEquals(2, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenModTwoLongValues_shouldModThemAndReturnTheResult() { | ||||
|         long result = LongMath.mod(30L, 4L); | ||||
|         assertEquals(2L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPowTwoLongValues_shouldPowThemAndReturnTheResult() { | ||||
|         long result = LongMath.pow(6L, 4); | ||||
|         assertEquals(1296L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnTheResult() { | ||||
|         long result = LongMath.saturatedAdd(6L, 4L); | ||||
|         assertEquals(10L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnIntMaxIfOverflow() { | ||||
|         long result = LongMath.saturatedAdd(Long.MAX_VALUE, 1000L); | ||||
|         assertEquals(Long.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedAddTwoLongValues_shouldAddThemAndReturnIntMinIfUnderflow() { | ||||
|         long result = LongMath.saturatedAdd(Long.MIN_VALUE, -1000); | ||||
|         assertEquals(Long.MIN_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnTheResult() { | ||||
|         long result = LongMath.saturatedMultiply(6L, 4L); | ||||
|         assertEquals(24L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() { | ||||
|         long result = LongMath.saturatedMultiply(Long.MAX_VALUE, 1000L); | ||||
|         assertEquals(Long.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnTheResult() { | ||||
|         long result = LongMath.saturatedPow(6L, 2); | ||||
|         assertEquals(36L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnIntMaxIfOverflow() { | ||||
|         long result = LongMath.saturatedPow(Long.MAX_VALUE, 2); | ||||
|         assertEquals(Long.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedPowTwoLongValues_shouldPowThemAndReturnIntMinIfUnderflow() { | ||||
|         long result = LongMath.saturatedPow(Long.MIN_VALUE, 3); | ||||
|         assertEquals(Long.MIN_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedSubstractTwoLongValues_shouldSubstractThemAndReturnTheResult() { | ||||
|         long result = LongMath.saturatedSubtract(6L, 2L); | ||||
|         assertEquals(4L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedSubstractTwoLongValues_shouldSubstractwThemAndReturnIntMaxIfOverflow() { | ||||
|         long result = LongMath.saturatedSubtract(Long.MAX_VALUE, -2L); | ||||
|         assertEquals(Long.MAX_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSaturatedSubstractTwoLongValues_shouldSubstractThemAndReturnIntMinIfUnderflow() { | ||||
|         long result = LongMath.saturatedSubtract(Long.MIN_VALUE, 3L); | ||||
|         assertEquals(Long.MIN_VALUE, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForCeilingRounding() { | ||||
|         long result = LongMath.sqrt(30L, RoundingMode.CEILING); | ||||
|         assertEquals(6L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForFloorRounding() { | ||||
|         long result = LongMath.sqrt(30L, RoundingMode.FLOOR); | ||||
|         assertEquals(5L, result); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = ArithmeticException.class) | ||||
|     public void whenSqrtLongValues_shouldThrowArithmeticExceptionIfRoundingNotDefinedButNecessary() { | ||||
|         LongMath.sqrt(30L, RoundingMode.UNNECESSARY); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -9,7 +9,7 @@ import java.util.stream.IntStream; | ||||
| import java.util.stream.LongStream; | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| public class GauavaStreamsTests { | ||||
| public class GuavaStreamsTests { | ||||
| 
 | ||||
|     List<Integer> numbers; | ||||
| 
 | ||||
| @ -55,6 +55,19 @@ | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-surefire-plugin</artifactId> | ||||
|                 <configuration> | ||||
|                     <forkCount>3</forkCount> | ||||
|                     <reuseForks>true</reuseForks> | ||||
|                     <excludes> | ||||
|                         <exclude>**/*IntegrationTest.java</exclude> | ||||
|                         <exclude>**/*LiveTest.java</exclude> | ||||
|                     </excludes> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
| 
 | ||||
|         </plugins> | ||||
| 
 | ||||
|     </build> | ||||
|  | ||||
| @ -1,21 +1,14 @@ | ||||
| package com.baeldung.hibernate; | ||||
| import static org.junit.Assert.assertNotEquals; | ||||
| 
 | ||||
| import java.sql.Connection; | ||||
| import java.sql.DriverManager; | ||||
| import java.sql.SQLException; | ||||
| import java.sql.Statement; | ||||
| 
 | ||||
| import com.baeldung.hibernate.pojo.Supplier; | ||||
| import org.hibernate.Session; | ||||
| import org.hibernate.SessionFactory; | ||||
| import org.hibernate.Transaction; | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import com.baeldung.hibernate.pojo.Supplier; | ||||
| import static org.junit.Assert.assertNotEquals; | ||||
| 
 | ||||
| 
 | ||||
| public class MultiTenantHibernateTest  { | ||||
| public class MultiTenantHibernateIntegrationTest { | ||||
|     @Test | ||||
|     public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs () { | ||||
|         SessionFactory sessionFactory; | ||||
| @ -23,7 +23,7 @@ public class DistanceSerializer extends StdSerializer<Distance> { | ||||
|     public void serialize(Distance distance, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException { | ||||
|         generator.writeStartObject(); | ||||
|         generator.writeFieldName("name"); | ||||
|         generator.writeNumber(distance.name()); | ||||
|         generator.writeString(distance.name()); | ||||
|         generator.writeFieldName("unit"); | ||||
|         generator.writeString(distance.getUnit()); | ||||
|         generator.writeFieldName("meters"); | ||||
|  | ||||
| @ -2,3 +2,4 @@ | ||||
| - [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition) | ||||
| - [JSON Processing in Java EE 7](http://www.baeldung.com/jee7-json) | ||||
| - [Converters, Listeners and Validators in Java EE 7](http://www.baeldung.com/java-ee7-converter-listener-validator) | ||||
| - [Introduction to JAX-WS](http://www.baeldung.com/jax-ws) | ||||
|  | ||||
							
								
								
									
										26
									
								
								libraries/myPersistence.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										26
									
								
								libraries/myPersistence.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,26 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?><root> | ||||
|      | ||||
|      | ||||
|      | ||||
| 
 | ||||
|      | ||||
|      | ||||
| 
 | ||||
|      | ||||
|      | ||||
| 
 | ||||
|      | ||||
|      | ||||
| 
 | ||||
|      | ||||
|      | ||||
| 
 | ||||
|      | ||||
|      | ||||
| 
 | ||||
|      | ||||
|      | ||||
| 
 | ||||
|      | ||||
|      | ||||
| </root> | ||||
| @ -59,6 +59,26 @@ | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|             <!-- JDO Plugin --> | ||||
| 			<plugin> | ||||
|                 <groupId>org.datanucleus</groupId> | ||||
|     			<artifactId>datanucleus-maven-plugin</artifactId> | ||||
|     			<version>5.0.2</version> | ||||
|                 <configuration> | ||||
|                     <api>JDO</api> | ||||
|                     <props>${basedir}/datanucleus.properties</props> | ||||
|                     <log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration> | ||||
|                     <verbose>true</verbose> | ||||
|                 </configuration> | ||||
| 				<executions> | ||||
|                 	<execution> | ||||
|                         <phase>process-classes</phase> | ||||
|                         <goals> | ||||
|                             <goal>enhance</goal> | ||||
|                         </goals> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
|         </plugins> | ||||
|     </build> | ||||
| 
 | ||||
| @ -200,6 +220,42 @@ | ||||
|             <artifactId>jackson-databind</artifactId> | ||||
|             <version>${jackson.version}</version> | ||||
|         </dependency> | ||||
| 		<!-- JDO --> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>javax.jdo</artifactId> | ||||
| 		    <version>3.2.0-m6</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-core</artifactId> | ||||
| 		    <version>5.1.0-m1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-api-jdo</artifactId> | ||||
| 		    <version>5.1.0-m1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-rdbms</artifactId> | ||||
| 		    <version>5.1.0-m1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-maven-plugin</artifactId> | ||||
| 		    <version>5.0.2</version> | ||||
| 		</dependency>		 | ||||
| 		<dependency> | ||||
| 		    <groupId>com.h2database</groupId> | ||||
| 		    <artifactId>h2</artifactId> | ||||
| 		    <version>1.4.194</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 		    <groupId>org.datanucleus</groupId> | ||||
| 		    <artifactId>datanucleus-xml</artifactId> | ||||
| 		    <version>5.0.0-release</version> | ||||
| 		</dependency>		 | ||||
|     </dependencies> | ||||
| 
 | ||||
|     <properties> | ||||
|  | ||||
| @ -1,49 +0,0 @@ | ||||
| package com.baeldung.http; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.DataOutputStream; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStreamReader; | ||||
| import java.net.HttpURLConnection; | ||||
| import java.net.URL; | ||||
| import java.util.Map; | ||||
| 
 | ||||
| import org.apache.log4j.Logger; | ||||
| 
 | ||||
| public class HttpRequestBuilder { | ||||
| 
 | ||||
|     private static final Logger LOG = Logger.getLogger(HttpRequestBuilder.class); | ||||
| 
 | ||||
|     public HttpResponseWrapper sendRequest(String urlString, String method, Map<String, String> parameters, Map<String, String> properties) throws IOException{ | ||||
|         URL url = new URL(urlString); | ||||
|         HttpURLConnection con = (HttpURLConnection) url.openConnection(); | ||||
|         con.setRequestMethod(method); | ||||
|         if (properties != null) { | ||||
|             properties.forEach((key, value) -> con.setRequestProperty(key, value)); | ||||
|         } | ||||
|         if (parameters != null) { | ||||
|             con.setDoOutput(true); | ||||
|             DataOutputStream out = new DataOutputStream(con.getOutputStream()); | ||||
|             out.writeBytes(ParameterStringBuilder.getParamsString(parameters)); | ||||
|             out.flush(); | ||||
|             out.close(); | ||||
|         } | ||||
|              | ||||
|         int status = con.getResponseCode(); | ||||
| 
 | ||||
|         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); | ||||
|         String inputLine; | ||||
|         StringBuffer content = new StringBuffer(); | ||||
|         while ((inputLine = in.readLine()) != null) { | ||||
|             content.append(inputLine); | ||||
|         } | ||||
|         in.close(); | ||||
| 
 | ||||
|         HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); | ||||
|         responseWrapper.setStatus(status); | ||||
|         responseWrapper.setContent(content.toString()); | ||||
|          | ||||
| 		return responseWrapper; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -1,31 +0,0 @@ | ||||
| package com.baeldung.http; | ||||
| 
 | ||||
| public class HttpResponseWrapper { | ||||
|     private int status; | ||||
|     private String content; | ||||
|      | ||||
|     public HttpResponseWrapper(){ } | ||||
| 
 | ||||
|     public HttpResponseWrapper(int status, String content) { | ||||
|         super(); | ||||
|         this.status = status; | ||||
|         this.content = content; | ||||
|     } | ||||
| 
 | ||||
|     public int getStatus() { | ||||
|         return status; | ||||
|     } | ||||
| 
 | ||||
|     public void setStatus(int status) { | ||||
|         this.status = status; | ||||
|     } | ||||
| 
 | ||||
|     public String getContent() { | ||||
|         return content; | ||||
|     } | ||||
| 
 | ||||
|     public void setContent(String content) { | ||||
|         this.content = content; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -1,27 +0,0 @@ | ||||
| package com.baeldung.http; | ||||
| 
 | ||||
| import java.io.UnsupportedEncodingException; | ||||
| import java.net.URLEncoder; | ||||
| import java.util.Map; | ||||
| 
 | ||||
| public class ParameterStringBuilder { | ||||
|     public static String getParamsString(Map<String, String> params) { | ||||
|         StringBuilder result = new StringBuilder(); | ||||
| 
 | ||||
|         params.forEach((key, value) -> { | ||||
|             try { | ||||
|                 result.append(URLEncoder.encode(key, "UTF-8")); | ||||
|                 result.append("="); | ||||
|                 result.append(URLEncoder.encode(value, "UTF-8")); | ||||
|                 result.append("&"); | ||||
|             } catch (UnsupportedEncodingException exc) { | ||||
|             } | ||||
|         }); | ||||
| 
 | ||||
|         String resultString = result.toString(); | ||||
|         if (resultString.length() > 0) { | ||||
|             resultString = resultString.substring(0, resultString.length() - 1); | ||||
|         } | ||||
|         return resultString; | ||||
|     } | ||||
| } | ||||
| @ -1,124 +0,0 @@ | ||||
| package com.baeldung.httpclient; | ||||
| 
 | ||||
| import java.io.BufferedReader; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStreamReader; | ||||
| import java.util.ArrayList; | ||||
| import java.util.List; | ||||
| import java.util.Map; | ||||
| 
 | ||||
| import org.apache.http.HttpResponse; | ||||
| import org.apache.http.NameValuePair; | ||||
| import org.apache.http.client.ClientProtocolException; | ||||
| import org.apache.http.client.HttpClient; | ||||
| import org.apache.http.client.entity.UrlEncodedFormEntity; | ||||
| import org.apache.http.client.methods.HttpGet; | ||||
| import org.apache.http.client.methods.HttpPost; | ||||
| import org.apache.http.entity.StringEntity; | ||||
| import org.apache.http.impl.client.HttpClientBuilder; | ||||
| import org.apache.http.message.BasicNameValuePair; | ||||
| 
 | ||||
| import com.baeldung.http.HttpResponseWrapper; | ||||
| import com.baeldung.http.ParameterStringBuilder; | ||||
| 
 | ||||
| public class HttpClientRequestBuilder { | ||||
| 
 | ||||
|     public HttpResponseWrapper sendGetRequest(String url, Map<String, String> parameters) { | ||||
|         HttpClient client = HttpClientBuilder.create() | ||||
|             .build(); | ||||
|         if (parameters != null) { | ||||
|             url += "?" + ParameterStringBuilder.getParamsString(parameters); | ||||
|         } | ||||
|         HttpGet request = new HttpGet(url); | ||||
|         try { | ||||
|             HttpResponse response = client.execute(request); | ||||
| 
 | ||||
|             HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); | ||||
|             responseWrapper.setStatus(response.getStatusLine() | ||||
|                 .getStatusCode()); | ||||
|             BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() | ||||
|                 .getContent())); | ||||
| 
 | ||||
|             String line = "", content = ""; | ||||
|             while ((line = in.readLine()) != null) { | ||||
|                 content += line; | ||||
|             } | ||||
|             responseWrapper.setContent(content); | ||||
|             return responseWrapper; | ||||
|         } catch (ClientProtocolException e) { | ||||
|             e.printStackTrace(); | ||||
|             return null; | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             return null; | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public HttpResponseWrapper sendPostRequestWithParameters(String url, Map<String, String> parameters) { | ||||
|         HttpClient client = HttpClientBuilder.create() | ||||
|             .build(); | ||||
|         HttpPost request = new HttpPost(url); | ||||
| 
 | ||||
|         try { | ||||
|             if (parameters != null) { | ||||
|                 List<NameValuePair> nameValuePairs = new ArrayList<>(); | ||||
|                 parameters.forEach((key, value) -> nameValuePairs.add(new BasicNameValuePair(key, value))); | ||||
|                 request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); | ||||
|             } | ||||
| 
 | ||||
|             HttpResponse response = client.execute(request); | ||||
| 
 | ||||
|             HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); | ||||
|             responseWrapper.setStatus(response.getStatusLine() | ||||
|                 .getStatusCode()); | ||||
|             BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() | ||||
|                 .getContent())); | ||||
| 
 | ||||
|             String line = "", content = ""; | ||||
|             while ((line = in.readLine()) != null) { | ||||
|                 content += line; | ||||
|             } | ||||
|             responseWrapper.setContent(content); | ||||
|             return responseWrapper; | ||||
|         } catch (ClientProtocolException e) { | ||||
|             e.printStackTrace(); | ||||
|             return null; | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             return null; | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public HttpResponseWrapper sendPostRequestWithJson(String url, String json) { | ||||
|         HttpClient client = HttpClientBuilder.create() | ||||
|             .build(); | ||||
|         HttpPost request = new HttpPost(url); | ||||
| 
 | ||||
|         try { | ||||
|             request.addHeader("Content-Type", "application/json"); | ||||
|             request.setEntity(new StringEntity(json)); | ||||
| 
 | ||||
|             HttpResponse response = client.execute(request); | ||||
| 
 | ||||
|             HttpResponseWrapper responseWrapper = new HttpResponseWrapper(); | ||||
|             responseWrapper.setStatus(response.getStatusLine() | ||||
|                 .getStatusCode()); | ||||
|             BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity() | ||||
|                 .getContent())); | ||||
| 
 | ||||
|             String line = "", content = ""; | ||||
|             while ((line = in.readLine()) != null) { | ||||
|                 content += line; | ||||
|             } | ||||
|             responseWrapper.setContent(content); | ||||
|             return responseWrapper; | ||||
|         } catch (ClientProtocolException e) { | ||||
|             e.printStackTrace(); | ||||
|             return null; | ||||
|         } catch (IOException e) { | ||||
|             e.printStackTrace(); | ||||
|             return null; | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| } | ||||
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