From e5c20ff0ba8ff516422f5102ff2c46544bf068e8 Mon Sep 17 00:00:00 2001 From: eugenp Date: Thu, 26 Jun 2014 01:37:52 +0300 Subject: [PATCH 01/32] cleanup work --- .../{dtos => serialization}/MyDtoNullKeySerializer.java | 4 +--- .../jackson/test/JacksonSerializationIgnoreUnitTest.java | 4 +++- 2 files changed, 4 insertions(+), 4 deletions(-) rename jackson/src/test/java/org/baeldung/jackson/{dtos => serialization}/MyDtoNullKeySerializer.java (89%) diff --git a/jackson/src/test/java/org/baeldung/jackson/dtos/MyDtoNullKeySerializer.java b/jackson/src/test/java/org/baeldung/jackson/serialization/MyDtoNullKeySerializer.java similarity index 89% rename from jackson/src/test/java/org/baeldung/jackson/dtos/MyDtoNullKeySerializer.java rename to jackson/src/test/java/org/baeldung/jackson/serialization/MyDtoNullKeySerializer.java index ab8ac6249d..8219abaddf 100644 --- a/jackson/src/test/java/org/baeldung/jackson/dtos/MyDtoNullKeySerializer.java +++ b/jackson/src/test/java/org/baeldung/jackson/serialization/MyDtoNullKeySerializer.java @@ -1,4 +1,4 @@ -package org.baeldung.jackson.dtos; +package org.baeldung.jackson.serialization; import java.io.IOException; @@ -11,9 +11,7 @@ public class MyDtoNullKeySerializer extends JsonSerializer { @Override public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeFieldName(""); - } } diff --git a/jackson/src/test/java/org/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson/src/test/java/org/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index c973584f9b..d0e0426ff0 100644 --- a/jackson/src/test/java/org/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -10,12 +10,12 @@ import java.util.Map; import org.baeldung.jackson.dtos.MyDto; import org.baeldung.jackson.dtos.MyDtoIncludeNonDefault; -import org.baeldung.jackson.dtos.MyDtoNullKeySerializer; import org.baeldung.jackson.dtos.MyDtoWithFilter; import org.baeldung.jackson.dtos.MyMixInForString; import org.baeldung.jackson.dtos.ignore.MyDtoIgnoreField; import org.baeldung.jackson.dtos.ignore.MyDtoIgnoreFieldByName; import org.baeldung.jackson.dtos.ignore.MyDtoIgnoreNull; +import org.baeldung.jackson.serialization.MyDtoNullKeySerializer; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -187,6 +187,8 @@ public class JacksonSerializationIgnoreUnitTest { System.out.println(dtoAsString); } + // map + @Test public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); From a4c585e489e35530a2a5306eb44788ea436a47b8 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 28 Jun 2014 16:06:47 +0300 Subject: [PATCH 02/32] IO work --- .../java/io/JavaFileIntegrationTest.java | 45 +++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java index 0ce720c80a..cc0014dc7c 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java @@ -1,5 +1,7 @@ package org.baeldung.java.io; +import static org.junit.Assert.assertTrue; + import java.io.File; import java.io.IOException; import java.nio.file.FileSystemException; @@ -17,7 +19,9 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException { final File newFile = new File("src/test/resources/newFile_jdk6.txt"); - newFile.createNewFile(); + final boolean success = newFile.createNewFile(); + + assertTrue(success); } @Test @@ -27,7 +31,7 @@ public class JavaFileIntegrationTest { } @Test - public final void givenUsingApache_whenCreatingFile_thenCorrect() throws IOException { + public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException { FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt")); } @@ -76,6 +80,41 @@ public class JavaFileIntegrationTest { FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/main/resources/"), true); } - // rename a file + // delete a file + + @Test + public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException { + new File("src/test/resources/fileToDelete_jdk6.txt").createNewFile(); + + final File fileToDelete = new File("src/test/resources/fileToDelete_jdk6.txt"); + final boolean success = fileToDelete.delete(); + + assertTrue(success); + } + + @Test + public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException { + // Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt")); + + final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt"); + Files.delete(fileToDeletePath); + } + + @Test + public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException { + FileUtils.touch(new File("src/test/resources/fileToDelete_commonsIo.txt")); + + final File fileToDelete = FileUtils.getFile("src/test/resources/fileToDelete_commonsIo.txt"); + final boolean success = FileUtils.deleteQuietly(fileToDelete); + + assertTrue(success); + } + + @Test + public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException { + // FileUtils.touch(new File("src/test/resources/fileToDelete.txt")); + + FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt")); + } } From 463f14a965d9c3176931afaeab980db2371f5791 Mon Sep 17 00:00:00 2001 From: Dheeraj-Baluja Date: Tue, 1 Jul 2014 01:06:33 +0530 Subject: [PATCH 03/32] adde a new project for Using Spring Forms --- .../WebContent/META-INF/MANIFEST.MF | 3 ++ .../WebContent/WEB-INF/dispatcher-servlet.xml | 27 +++++++++++++ .../WEB-INF/views/employeeAdded.jsp | 24 ++++++++++++ .../WebContent/WEB-INF/views/employeeHome.jsp | 38 +++++++++++++++++++ .../WebContent/WEB-INF/views/error.jsp | 20 ++++++++++ .../WebContent/WEB-INF/web.xml | 16 ++++++++ SpringMVCFormExample/WebContent/index.jsp | 18 +++++++++ .../demo/controllers/EmployeeController.java | 34 +++++++++++++++++ .../src/com/demo/form/Employee.java | 33 ++++++++++++++++ 9 files changed, 213 insertions(+) create mode 100644 SpringMVCFormExample/WebContent/META-INF/MANIFEST.MF create mode 100644 SpringMVCFormExample/WebContent/WEB-INF/dispatcher-servlet.xml create mode 100644 SpringMVCFormExample/WebContent/WEB-INF/views/employeeAdded.jsp create mode 100644 SpringMVCFormExample/WebContent/WEB-INF/views/employeeHome.jsp create mode 100644 SpringMVCFormExample/WebContent/WEB-INF/views/error.jsp create mode 100644 SpringMVCFormExample/WebContent/WEB-INF/web.xml create mode 100644 SpringMVCFormExample/WebContent/index.jsp create mode 100644 SpringMVCFormExample/src/com/demo/controllers/EmployeeController.java create mode 100644 SpringMVCFormExample/src/com/demo/form/Employee.java diff --git a/SpringMVCFormExample/WebContent/META-INF/MANIFEST.MF b/SpringMVCFormExample/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/SpringMVCFormExample/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/SpringMVCFormExample/WebContent/WEB-INF/dispatcher-servlet.xml b/SpringMVCFormExample/WebContent/WEB-INF/dispatcher-servlet.xml new file mode 100644 index 0000000000..1fc94effba --- /dev/null +++ b/SpringMVCFormExample/WebContent/WEB-INF/dispatcher-servlet.xml @@ -0,0 +1,27 @@ + + + + + + + + + + /WEB-INF/views/ + + + .jsp + + + + \ No newline at end of file diff --git a/SpringMVCFormExample/WebContent/WEB-INF/views/employeeAdded.jsp b/SpringMVCFormExample/WebContent/WEB-INF/views/employeeAdded.jsp new file mode 100644 index 0000000000..1457bc5fc8 --- /dev/null +++ b/SpringMVCFormExample/WebContent/WEB-INF/views/employeeAdded.jsp @@ -0,0 +1,24 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/SpringMVCFormExample/WebContent/WEB-INF/views/employeeHome.jsp b/SpringMVCFormExample/WebContent/WEB-INF/views/employeeHome.jsp new file mode 100644 index 0000000000..f86fc19146 --- /dev/null +++ b/SpringMVCFormExample/WebContent/WEB-INF/views/employeeHome.jsp @@ -0,0 +1,38 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + + + +SpringMVCExample + + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/SpringMVCFormExample/WebContent/WEB-INF/views/error.jsp b/SpringMVCFormExample/WebContent/WEB-INF/views/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/SpringMVCFormExample/WebContent/WEB-INF/views/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file diff --git a/SpringMVCFormExample/WebContent/WEB-INF/web.xml b/SpringMVCFormExample/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000000..47dd114f2a --- /dev/null +++ b/SpringMVCFormExample/WebContent/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + SpringMVCFormExample + + dispatcher + org.springframework.web.servlet.DispatcherServlet + 1 + + + dispatcher + / + + + index.jsp + + \ No newline at end of file diff --git a/SpringMVCFormExample/WebContent/index.jsp b/SpringMVCFormExample/WebContent/index.jsp new file mode 100644 index 0000000000..1ecfcec9d7 --- /dev/null +++ b/SpringMVCFormExample/WebContent/index.jsp @@ -0,0 +1,18 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC Examples + + + +

Spring MVC Examples

+ + + + \ No newline at end of file diff --git a/SpringMVCFormExample/src/com/demo/controllers/EmployeeController.java b/SpringMVCFormExample/src/com/demo/controllers/EmployeeController.java new file mode 100644 index 0000000000..d4bc8e44ad --- /dev/null +++ b/SpringMVCFormExample/src/com/demo/controllers/EmployeeController.java @@ -0,0 +1,34 @@ +package com.demo.controllers; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import com.demo.form.Employee; + +@Controller +public class EmployeeController { + + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("employee")Employee employee, BindingResult result, + ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + return "employeeAdded"; + } +} diff --git a/SpringMVCFormExample/src/com/demo/form/Employee.java b/SpringMVCFormExample/src/com/demo/form/Employee.java new file mode 100644 index 0000000000..cf7fb574cf --- /dev/null +++ b/SpringMVCFormExample/src/com/demo/form/Employee.java @@ -0,0 +1,33 @@ +package com.demo.form; + +public class Employee { + + private String name; + private long id; + private String contactNumber; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(String contactNumber) { + this.contactNumber = contactNumber; + } + +} From aad3a856d9be329abc779459f40f62f3483461b2 Mon Sep 17 00:00:00 2001 From: egmp777 Date: Tue, 1 Jul 2014 08:44:37 -0500 Subject: [PATCH 04/32] HttpClientConnectionManager Tests First Pull --- .../HttpClientConnectionManagementTest.java | 358 +++++++++++++++++- .../IdleConnectionMonitorThread.java | 39 ++ .../httpclient/MultiHttpClientConnThread.java | 61 +++ ...sterVersion_MultiHttpClientConnThread.java | 49 +++ 4 files changed, 500 insertions(+), 7 deletions(-) create mode 100644 httpclient/src/test/java/org/baeldung/httpclient/IdleConnectionMonitorThread.java create mode 100644 httpclient/src/test/java/org/baeldung/httpclient/MultiHttpClientConnThread.java create mode 100644 httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java index 5096725ece..37f7b07145 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java @@ -1,29 +1,373 @@ package org.baeldung.httpclient; +import static org.junit.Assert.assertTrue; + import java.io.IOException; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import org.apache.http.HeaderElement; +import org.apache.http.HeaderElementIterator; +import org.apache.http.HttpClientConnection; import org.apache.http.HttpException; import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.config.SocketConfig; +import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.ConnectionRequest; import org.apache.http.conn.routing.HttpRoute; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicHeaderElementIterator; +import org.apache.http.protocol.HTTP; +import org.apache.http.protocol.HttpContext; +import org.apache.http.protocol.HttpCoreContext; +import org.apache.http.protocol.HttpRequestExecutor; +import org.apache.http.util.EntityUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; -@SuppressWarnings("unused") + public class HttpClientConnectionManagementTest { + private BasicHttpClientConnectionManager basicConnManager; + private HttpClientContext context; + private HttpRoute route; + private static final String SERVER1 = "http://echo.200please.com"; + private static final String SERVER7 = "http://localhost"; + private HttpGet get1; + private HttpGet get2; + private static CloseableHttpResponse response; + private HttpClientConnection conn1; + private HttpClientConnection conn; + private HttpClientConnection conn2; + private PoolingHttpClientConnectionManager poolingConnManager; + private CloseableHttpClient client; + + @Before + public final void before() { + get1 = new HttpGet(SERVER1); + get2 = new HttpGet(SERVER7); + route = new HttpRoute(new HttpHost("localhost", 80)); + } + + @After + public final void after() throws IllegalStateException, IOException { + if (conn != null) + conn.close(); + if (conn1 != null) + conn1.close(); + if (conn2 != null) + conn2.close(); + if (poolingConnManager != null) + poolingConnManager.shutdown(); + if (basicConnManager != null) + basicConnManager.shutdown(); + if (client != null) + client.close(); + if (response != null) + response.close(); + + } // tests @Test + @Ignore + // 2.1 IN ARTCLE public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException { - final HttpClientContext context = HttpClientContext.create(); - final BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(); - final HttpRoute route = new HttpRoute(new HttpHost("localhost", 80)); - final ConnectionRequest connRequest = connManager.requestConnection(route, null); - - connManager.shutdown(); + basicConnManager = new BasicHttpClientConnectionManager(); + final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null); + assertTrue(connRequest.get(1000, TimeUnit.SECONDS) != null); } + @Test + @Ignore + // 2.2 IN ARTICLE + public final void whenOpeningLowLevelConnectionWithSocketTimeout_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { + basicConnManager = new BasicHttpClientConnectionManager(); + context = HttpClientContext.create(); + final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null); + conn = connRequest.get(1000, TimeUnit.SECONDS); + if (!conn.isOpen()) + basicConnManager.connect(conn, route, 1000, context); + conn.setSocketTimeout(30000); + + assertTrue(conn.getSocketTimeout() == 30000); + assertTrue(conn.isOpen()); + } + + @Test + @Ignore + // Example 3.1. TESTER VERSION + public final void WhenTwoConnectionsForTwoRequests_ThenLeaseTwoConnectionsNoExceptions() throws InterruptedException { + get1 = new HttpGet("http://localhost"); + get2 = new HttpGet("http://google.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client1, get1, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client2, get2, poolingConnManager); + thread1.start(); + thread1.join(); + thread2.start(); + assertTrue(poolingConnManager.getTotalStats().getLeased() == 1); + thread2.join(1000); + assertTrue(poolingConnManager.getTotalStats().getLeased() == 2); + } + + @Test + @Ignore + // Example 3.1.ARTICLE VERSION + public final void WhenTwoConnectionsForTwoRequests_ThensNoExceptions() throws InterruptedException { + get1 = new HttpGet("http://localhost"); + get2 = new HttpGet("http://google.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client1, get1); + final MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client2, get2); + thread1.start(); + thread1.join(); + thread2.start(); + thread2.join(); + } + + @Test + @Ignore + // 3.3 + public final void whenIncreasingConnectionPool_thenNoEceptions() { + + poolingConnManager = new PoolingHttpClientConnectionManager(); + poolingConnManager.setMaxTotal(5); + poolingConnManager.setDefaultMaxPerRoute(4); + final HttpHost localhost = new HttpHost("locahost", 80); + poolingConnManager.setMaxPerRoute(new HttpRoute(localhost), 5); + } + + @Test + @Ignore + // 3.4 Tester Version + public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimitNoExceptions() throws InterruptedException, IOException { + final HttpGet get = new HttpGet("http://google.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + thread1.start(); + thread1.join(1000); + assertTrue(poolingConnManager.getTotalStats().getLeased() == 1); + thread2.start(); + thread2.join(1000); + assertTrue(poolingConnManager.getTotalStats().getLeased() == 2); + thread3.start(); + thread3.join(1000); + } + + @Test + @Ignore + // 3.4 Article version + public final void whenExecutingSameRequestsInDifferentThreads_thenExxecuteReuqesttNoExceptions() throws InterruptedException { + final HttpGet get = new HttpGet("http://localhost"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get); + final MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client, get); + final MultiHttpClientConnThread thread3 = new MultiHttpClientConnThread(client, get); + thread1.start(); + thread2.start(); + thread3.start(); + thread1.join(); + thread2.join(); + thread3.join(); + } + + @Test + @Ignore + // 4.1 + public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException { + final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { + @Override + public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) { + final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE)); + while (it.hasNext()) { + final HeaderElement he = it.nextElement(); + final String param = he.getName(); + final String value = he.getValue(); + if (value != null && param.equalsIgnoreCase("timeout")) { + return Long.parseLong(value) * 1000; + } + } + final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); + if ("localhost".equalsIgnoreCase(target.getHostName())) { + return 10 * 1000; + } else { + return 5 * 1000; + } + } + + }; + client = HttpClients.custom().setKeepAliveStrategy(myStrategy).setConnectionManager(poolingConnManager).build(); + client.execute(get1); + client.execute(get2); + } + + @Test + @Ignore + // 5.1 + public final void GivenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { + basicConnManager = new BasicHttpClientConnectionManager(); + context = HttpClientContext.create(); + final HttpGet get = new HttpGet("http://localhost"); + HttpResponse thisResponse = null; + final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null); + client = HttpClients.custom().setConnectionManager(basicConnManager).build(); + boolean respAvail = false; + conn = connRequest.get(10, TimeUnit.SECONDS); + if (!conn.isOpen()) { + basicConnManager.connect(conn, route, 1000, context); + basicConnManager.routeComplete(conn, route, context); + final HttpRequestExecutor exeRequest = new HttpRequestExecutor(); + context.setTargetHost((new HttpHost("localhost", 80))); + thisResponse = exeRequest.execute(get, conn, context); + respAvail = conn.isResponseAvailable(1000); + } + basicConnManager.releaseConnection(conn, null, 1, TimeUnit.SECONDS); + if (respAvail) { + client.execute(get); + } + } + + @Test + @Ignore + // 5.2 TESTER VERSION + public final void WhenConnectionsNeededGreaterThanMaxTotal_thenReuseConnectionsNoExceptions() throws InterruptedException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + poolingConnManager.setDefaultMaxPerRoute(5); + poolingConnManager.setMaxTotal(5); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10]; + int countConnMade = 0; + for (int i = 0; i < threads.length; i++) { + threads[i] = new MultiHttpClientConnThread(client, get1, poolingConnManager); + } + for (final MultiHttpClientConnThread thread : threads) { + thread.start(); + } + for (final MultiHttpClientConnThread thread : threads) { + thread.join(10000); + countConnMade++; + if (countConnMade == 0) + assertTrue(thread.getLeasedConn() == 5); + } + } + + @Test + // 5.2 ARTICLE VERSION + @Ignore + public final void WhenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuseNoExceptions() throws InterruptedException { + final HttpGet get = new HttpGet("http://echo.200please.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + poolingConnManager.setDefaultMaxPerRoute(5); + poolingConnManager.setMaxTotal(5); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final MultiHttpClientConnThread[] threads = new MultiHttpClientConnThread[10]; + for (int i = 0; i < threads.length; i++) { + threads[i] = new MultiHttpClientConnThread(client, get, poolingConnManager); + } + for (final MultiHttpClientConnThread thread : threads) { + thread.start(); + } + for (final MultiHttpClientConnThread thread : threads) { + thread.join(10000); + } + } + + @Test + @Ignore + // 6.2.1 + public final void whenConfiguringTimeOut_thenNoExceptions() { + route = new HttpRoute(new HttpHost("localhost", 80)); + poolingConnManager = new PoolingHttpClientConnectionManager(); + poolingConnManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom().setSoTimeout(5000).build()); + assertTrue(poolingConnManager.getSocketConfig(route.getTargetHost()).getSoTimeout() == 5000); + } + + @Test + @Ignore + // 7.1 + public final void whenHttpClientChecksStaleConns_thenNoExceptions() { + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build()).setConnectionManager(poolingConnManager).build(); + } + + @Test + @Ignore + // 7.2 TESTER VERSION + public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConnsNoExceptions() throws InterruptedException, IOException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); + final HttpGet get = new HttpGet("http://google.com"); + // test this with new HttpGet("http://iotechperu.com")----First test will fail b/c there is redirect connection at that site + final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + staleMonitor.start(); + thread1.start(); + thread1.join(); + thread2.start(); + thread2.join(); + thread3.start(); + assertTrue(poolingConnManager.getTotalStats().getAvailable() == 1); + thread3.join(32000); + assertTrue(poolingConnManager.getTotalStats().getAvailable() == 0); + } + + @Test + @Ignore + // 7.2 ARTICLE VERSION + public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException, IOException { + final HttpGet get = new HttpGet("http://google.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); + staleMonitor.start(); + staleMonitor.join(1000); + } + + @Test(expected = IllegalStateException.class) + @Ignore + // 8.1 + public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { + route = new HttpRoute(new HttpHost("google.com", 80)); + final HttpGet get = new HttpGet("http://google.com"); + poolingConnManager = new PoolingHttpClientConnectionManager(); + final ConnectionRequest connRequest = poolingConnManager.requestConnection(route, null); + context = HttpClientContext.create(); + conn = connRequest.get(10, TimeUnit.SECONDS); + poolingConnManager.connect(conn, route, 10000, context); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + response = client.execute(get); + EntityUtils.consume(response.getEntity()); + client.close(); + conn.close(); + response.close(); + poolingConnManager.close(); + poolingConnManager.shutdown(); + client.execute(get); + conn.sendRequestHeader(get); + assertTrue(!conn.isOpen()); + assertTrue(conn.isOpen()); + assertTrue(response.getEntity() == null); + } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/IdleConnectionMonitorThread.java b/httpclient/src/test/java/org/baeldung/httpclient/IdleConnectionMonitorThread.java new file mode 100644 index 0000000000..4c4c7f36a1 --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/IdleConnectionMonitorThread.java @@ -0,0 +1,39 @@ +package org.baeldung.httpclient; + +import java.util.concurrent.TimeUnit; + +import org.apache.http.conn.HttpClientConnectionManager; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; + +public class IdleConnectionMonitorThread extends Thread { + private final HttpClientConnectionManager connMgr; + private volatile boolean shutdown; + + public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { + super(); + this.connMgr = connMgr; + } + + @Override + public void run() { + try { + while (!shutdown) { + synchronized (this) { + wait(1000); + connMgr.closeExpiredConnections(); + connMgr.closeIdleConnections(30, TimeUnit.SECONDS); + } + } + } catch (final InterruptedException ex) { + shutdown(); + + } + } + + public void shutdown() { + shutdown = true; + synchronized (this) { + notifyAll(); + } + } +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/MultiHttpClientConnThread.java new file mode 100644 index 0000000000..e2f8fabbdf --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/MultiHttpClientConnThread.java @@ -0,0 +1,61 @@ +package org.baeldung.httpclient; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; + +public class MultiHttpClientConnThread extends Thread { + private final CloseableHttpClient client; + private final HttpGet get; + private PoolingHttpClientConnectionManager connManager = null; + private static HttpResponse response; + private Logger logger; + public int leasedConn; + + public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + this.client = client; + this.get = get; + this.connManager = connManager; + logger = Logger.getLogger(MultiHttpClientConnThread.class.getName()); + leasedConn = 0; + } + + public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { + this.client = client; + this.get = get; + logger = Logger.getLogger(MultiHttpClientConnThread.class.getName()); + } + + public int getLeasedConn() { + return leasedConn; + } + + @Override + public void run() { + + try { + if (this != null) + logger.log(Level.SEVERE, "Thread Running: " + getName()); + response = client.execute(get); + if (connManager != null) { + logger.log(Level.SEVERE, "Leased Connections " + connManager.getTotalStats().getLeased()); + leasedConn = connManager.getTotalStats().getLeased(); + logger.log(Level.SEVERE, "Available Connections " + connManager.getTotalStats().getAvailable()); + } + EntityUtils.consume(response.getEntity()); + + } catch (final ClientProtocolException ex) { + + } catch (final IOException ex) { + + } + + } +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java new file mode 100644 index 0000000000..f71ac7462e --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java @@ -0,0 +1,49 @@ +package org.baeldung.httpclient; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; + +public class TesterVersion_MultiHttpClientConnThread extends Thread { + private final CloseableHttpClient client; + private final HttpGet get; + private PoolingHttpClientConnectionManager connManager = null; + private Logger logger; + public int leasedConn; + public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + this.client = client; + this.get = get; + this.connManager = connManager; + logger = Logger.getLogger(TesterVersion_MultiHttpClientConnThread.class.getName()); + leasedConn = 0; + } + + public int getLeasedConn() { + return leasedConn; + } + + @Override + public void run() { + try { + if (this != null) + logger.log(Level.SEVERE, "Thread Running: " + getName()); + client.execute(get); + if (connManager != null) { + logger.log(Level.SEVERE, "Leased Connections " + connManager.getTotalStats().getLeased()); + leasedConn = connManager.getTotalStats().getLeased(); + logger.log(Level.SEVERE, "Available Connections " + connManager.getTotalStats().getAvailable()); + } + + } catch (final ClientProtocolException ex) { + + } catch (final IOException ex) { + + } + } + +} From c3d7000ff136314634421159969985526f180b47 Mon Sep 17 00:00:00 2001 From: Dheeraj-Baluja Date: Sat, 5 Jul 2014 01:18:51 +0530 Subject: [PATCH 05/32] Formatting done and renamed the project correctly --- .../WebContent/META-INF/MANIFEST.MF | 0 .../WebContent/WEB-INF/dispatcher-servlet.xml | 0 .../WebContent/WEB-INF/views/employeeAdded.jsp | 0 .../WebContent/WEB-INF/views/employeeHome.jsp | 0 .../WebContent/WEB-INF/views/error.jsp | 0 .../WebContent/WEB-INF/web.xml | 0 {SpringMVCFormExample => spring-mvc-forms}/WebContent/index.jsp | 0 .../src/com/demo/controllers/EmployeeController.java | 0 .../src/com/demo/form/Employee.java | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename {SpringMVCFormExample => spring-mvc-forms}/WebContent/META-INF/MANIFEST.MF (100%) rename {SpringMVCFormExample => spring-mvc-forms}/WebContent/WEB-INF/dispatcher-servlet.xml (100%) rename {SpringMVCFormExample => spring-mvc-forms}/WebContent/WEB-INF/views/employeeAdded.jsp (100%) rename {SpringMVCFormExample => spring-mvc-forms}/WebContent/WEB-INF/views/employeeHome.jsp (100%) rename {SpringMVCFormExample => spring-mvc-forms}/WebContent/WEB-INF/views/error.jsp (100%) rename {SpringMVCFormExample => spring-mvc-forms}/WebContent/WEB-INF/web.xml (100%) rename {SpringMVCFormExample => spring-mvc-forms}/WebContent/index.jsp (100%) rename {SpringMVCFormExample => spring-mvc-forms}/src/com/demo/controllers/EmployeeController.java (100%) rename {SpringMVCFormExample => spring-mvc-forms}/src/com/demo/form/Employee.java (100%) diff --git a/SpringMVCFormExample/WebContent/META-INF/MANIFEST.MF b/spring-mvc-forms/WebContent/META-INF/MANIFEST.MF similarity index 100% rename from SpringMVCFormExample/WebContent/META-INF/MANIFEST.MF rename to spring-mvc-forms/WebContent/META-INF/MANIFEST.MF diff --git a/SpringMVCFormExample/WebContent/WEB-INF/dispatcher-servlet.xml b/spring-mvc-forms/WebContent/WEB-INF/dispatcher-servlet.xml similarity index 100% rename from SpringMVCFormExample/WebContent/WEB-INF/dispatcher-servlet.xml rename to spring-mvc-forms/WebContent/WEB-INF/dispatcher-servlet.xml diff --git a/SpringMVCFormExample/WebContent/WEB-INF/views/employeeAdded.jsp b/spring-mvc-forms/WebContent/WEB-INF/views/employeeAdded.jsp similarity index 100% rename from SpringMVCFormExample/WebContent/WEB-INF/views/employeeAdded.jsp rename to spring-mvc-forms/WebContent/WEB-INF/views/employeeAdded.jsp diff --git a/SpringMVCFormExample/WebContent/WEB-INF/views/employeeHome.jsp b/spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp similarity index 100% rename from SpringMVCFormExample/WebContent/WEB-INF/views/employeeHome.jsp rename to spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp diff --git a/SpringMVCFormExample/WebContent/WEB-INF/views/error.jsp b/spring-mvc-forms/WebContent/WEB-INF/views/error.jsp similarity index 100% rename from SpringMVCFormExample/WebContent/WEB-INF/views/error.jsp rename to spring-mvc-forms/WebContent/WEB-INF/views/error.jsp diff --git a/SpringMVCFormExample/WebContent/WEB-INF/web.xml b/spring-mvc-forms/WebContent/WEB-INF/web.xml similarity index 100% rename from SpringMVCFormExample/WebContent/WEB-INF/web.xml rename to spring-mvc-forms/WebContent/WEB-INF/web.xml diff --git a/SpringMVCFormExample/WebContent/index.jsp b/spring-mvc-forms/WebContent/index.jsp similarity index 100% rename from SpringMVCFormExample/WebContent/index.jsp rename to spring-mvc-forms/WebContent/index.jsp diff --git a/SpringMVCFormExample/src/com/demo/controllers/EmployeeController.java b/spring-mvc-forms/src/com/demo/controllers/EmployeeController.java similarity index 100% rename from SpringMVCFormExample/src/com/demo/controllers/EmployeeController.java rename to spring-mvc-forms/src/com/demo/controllers/EmployeeController.java diff --git a/SpringMVCFormExample/src/com/demo/form/Employee.java b/spring-mvc-forms/src/com/demo/form/Employee.java similarity index 100% rename from SpringMVCFormExample/src/com/demo/form/Employee.java rename to spring-mvc-forms/src/com/demo/form/Employee.java From 8434f826e6a631409bdc9fbd705c4240fd7c5207 Mon Sep 17 00:00:00 2001 From: Dheeraj-Baluja Date: Sat, 5 Jul 2014 01:27:10 +0530 Subject: [PATCH 06/32] Formatted the code --- .../WebContent/WEB-INF/views/employeeHome.jsp | 2 +- spring-mvc-forms/WebContent/WEB-INF/web.xml | 31 +++++++------- .../demo/controllers/EmployeeController.java | 29 +++++++------ .../src/com/demo/form/Employee.java | 42 +++++++++---------- 4 files changed, 53 insertions(+), 51 deletions(-) diff --git a/spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp b/spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp index f86fc19146..497eade8c7 100644 --- a/spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp +++ b/spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp @@ -12,7 +12,7 @@

Welcome, Enter The Employee Details

- diff --git a/spring-mvc-forms/WebContent/WEB-INF/web.xml b/spring-mvc-forms/WebContent/WEB-INF/web.xml index 47dd114f2a..4c122670e5 100644 --- a/spring-mvc-forms/WebContent/WEB-INF/web.xml +++ b/spring-mvc-forms/WebContent/WEB-INF/web.xml @@ -1,16 +1,19 @@ - - SpringMVCFormExample - - dispatcher - org.springframework.web.servlet.DispatcherServlet - 1 - - - dispatcher - / - - - index.jsp - + + SpringMVCFormExample + + dispatcher + org.springframework.web.servlet.DispatcherServlet + + 1 + + + dispatcher + / + + + index.jsp + \ No newline at end of file diff --git a/spring-mvc-forms/src/com/demo/controllers/EmployeeController.java b/spring-mvc-forms/src/com/demo/controllers/EmployeeController.java index d4bc8e44ad..1dd76ae23f 100644 --- a/spring-mvc-forms/src/com/demo/controllers/EmployeeController.java +++ b/spring-mvc-forms/src/com/demo/controllers/EmployeeController.java @@ -15,20 +15,19 @@ import com.demo.form.Employee; @Controller public class EmployeeController { - @RequestMapping(value = "/employee", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); - } + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) - public String submit(@Valid @ModelAttribute("employee")Employee employee, BindingResult result, - ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - return "employeeAdded"; - } + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("employee") Employee employee, BindingResult result, ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + return "employeeAdded"; + } } diff --git a/spring-mvc-forms/src/com/demo/form/Employee.java b/spring-mvc-forms/src/com/demo/form/Employee.java index cf7fb574cf..569347b628 100644 --- a/spring-mvc-forms/src/com/demo/form/Employee.java +++ b/spring-mvc-forms/src/com/demo/form/Employee.java @@ -2,32 +2,32 @@ package com.demo.form; public class Employee { - private String name; - private long id; - private String contactNumber; + private String name; + private long id; + private String contactNumber; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getContactNumber() { - return contactNumber; - } + public String getContactNumber() { + return contactNumber; + } - public void setContactNumber(String contactNumber) { - this.contactNumber = contactNumber; - } + public void setContactNumber(String contactNumber) { + this.contactNumber = contactNumber; + } } From 0a76200ab4df8717b5fc7ab05ec601cf5de4fa07 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 6 Jul 2014 11:37:59 +0300 Subject: [PATCH 07/32] work on java io tests --- .../java/io/JavaFileIntegrationTest.java | 5 ++ .../java/io/JavaReaderToXUnitTest.java | 46 +++++++++++++++++++ .../HttpClientConnectionManagementTest.java | 44 ++++++++---------- ...sterVersion_MultiHttpClientConnThread.java | 1 + 4 files changed, 72 insertions(+), 24 deletions(-) create mode 100644 core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java index cc0014dc7c..c139e34afb 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java @@ -35,6 +35,11 @@ public class JavaFileIntegrationTest { FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt")); } + @Test + public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException { + com.google.common.io.Files.touch(new File("src/test/resources/newFile_guava.txt")); + } + // move a file @Test diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java new file mode 100644 index 0000000000..4e8b97f381 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java @@ -0,0 +1,46 @@ +package org.baeldung.java.io; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; + +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.io.CharSource; +import com.google.common.io.CharStreams; + +@SuppressWarnings("unused") +public class JavaReaderToXUnitTest { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + private static final int DEFAULT_SIZE = 1500000; + + // tests - Reader to String + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoString_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("text"); + + final char[] mediationArray = new char["text".length()]; + initialReader.read(mediationArray); + initialReader.close(); + final String targetString = new String(mediationArray); + } + + @Test + public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() throws IOException { + final Reader initialReader = CharSource.wrap("Google Guava v.17.0").openStream(); + final String targetString = CharStreams.toString(initialReader); + initialReader.close(); + } + + @Test + public void givenUsingCommonsIo_whenConvertingReaderIntoString_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("Apache Commons IO 2.4"); + final String targetString = IOUtils.toString(initialReader); + initialReader.close(); + } + +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java index 37f7b07145..2a923585b6 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java @@ -33,10 +33,8 @@ import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; - public class HttpClientConnectionManagementTest { private BasicHttpClientConnectionManager basicConnManager; private HttpClientContext context; @@ -75,13 +73,12 @@ public class HttpClientConnectionManagementTest { client.close(); if (response != null) response.close(); - } // tests @Test - @Ignore + // @Ignore // 2.1 IN ARTCLE public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException { basicConnManager = new BasicHttpClientConnectionManager(); @@ -90,7 +87,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 2.2 IN ARTICLE public final void whenOpeningLowLevelConnectionWithSocketTimeout_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { basicConnManager = new BasicHttpClientConnectionManager(); @@ -106,11 +103,11 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // Example 3.1. TESTER VERSION public final void WhenTwoConnectionsForTwoRequests_ThenLeaseTwoConnectionsNoExceptions() throws InterruptedException { - get1 = new HttpGet("http://localhost"); - get2 = new HttpGet("http://google.com"); + get1 = new HttpGet("http://www.petrikainulainen.net/"); + get2 = new HttpGet("http://www.baeldung.com/"); poolingConnManager = new PoolingHttpClientConnectionManager(); final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -119,13 +116,12 @@ public class HttpClientConnectionManagementTest { thread1.start(); thread1.join(); thread2.start(); - assertTrue(poolingConnManager.getTotalStats().getLeased() == 1); thread2.join(1000); assertTrue(poolingConnManager.getTotalStats().getLeased() == 2); } @Test - @Ignore + // @Ignore // Example 3.1.ARTICLE VERSION public final void WhenTwoConnectionsForTwoRequests_ThensNoExceptions() throws InterruptedException { get1 = new HttpGet("http://localhost"); @@ -142,10 +138,9 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 3.3 public final void whenIncreasingConnectionPool_thenNoEceptions() { - poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setMaxTotal(5); poolingConnManager.setDefaultMaxPerRoute(4); @@ -154,7 +149,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 3.4 Tester Version public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimitNoExceptions() throws InterruptedException, IOException { final HttpGet get = new HttpGet("http://google.com"); @@ -174,7 +169,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 3.4 Article version public final void whenExecutingSameRequestsInDifferentThreads_thenExxecuteReuqesttNoExceptions() throws InterruptedException { final HttpGet get = new HttpGet("http://localhost"); @@ -192,7 +187,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 4.1 public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException { final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { @@ -222,7 +217,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 5.1 public final void GivenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { basicConnManager = new BasicHttpClientConnectionManager(); @@ -248,7 +243,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 5.2 TESTER VERSION public final void WhenConnectionsNeededGreaterThanMaxTotal_thenReuseConnectionsNoExceptions() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); @@ -271,9 +266,9 @@ public class HttpClientConnectionManagementTest { } } - @Test // 5.2 ARTICLE VERSION - @Ignore + @Test + // @Ignore public final void WhenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuseNoExceptions() throws InterruptedException { final HttpGet get = new HttpGet("http://echo.200please.com"); poolingConnManager = new PoolingHttpClientConnectionManager(); @@ -293,7 +288,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 6.2.1 public final void whenConfiguringTimeOut_thenNoExceptions() { route = new HttpRoute(new HttpHost("localhost", 80)); @@ -303,7 +298,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 7.1 public final void whenHttpClientChecksStaleConns_thenNoExceptions() { poolingConnManager = new PoolingHttpClientConnectionManager(); @@ -311,7 +306,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 7.2 TESTER VERSION public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConnsNoExceptions() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); @@ -334,7 +329,7 @@ public class HttpClientConnectionManagementTest { } @Test - @Ignore + // @Ignore // 7.2 ARTICLE VERSION public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException, IOException { final HttpGet get = new HttpGet("http://google.com"); @@ -346,7 +341,7 @@ public class HttpClientConnectionManagementTest { } @Test(expected = IllegalStateException.class) - @Ignore + // @Ignore // 8.1 public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { route = new HttpRoute(new HttpHost("google.com", 80)); @@ -370,4 +365,5 @@ public class HttpClientConnectionManagementTest { assertTrue(conn.isOpen()); assertTrue(response.getEntity() == null); } + } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java index f71ac7462e..131761b072 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java @@ -15,6 +15,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { private PoolingHttpClientConnectionManager connManager = null; private Logger logger; public int leasedConn; + public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; From 59917554029f536490903e119cc8f296e7ea3a9d Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 6 Jul 2014 16:35:52 +0300 Subject: [PATCH 08/32] connection management work --- .../HttpClientConnectionManagementTest.java | 71 ++++++++++++------- 1 file changed, 46 insertions(+), 25 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java index 2a923585b6..293564086f 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java @@ -36,18 +36,22 @@ import org.junit.Before; import org.junit.Test; public class HttpClientConnectionManagementTest { + private static final String SERVER1 = "http://www.petrikainulainen.net/"; + private static final String SERVER7 = "http://www.baeldung.com/"; + private BasicHttpClientConnectionManager basicConnManager; + private PoolingHttpClientConnectionManager poolingConnManager; + private HttpClientContext context; private HttpRoute route; - private static final String SERVER1 = "http://echo.200please.com"; - private static final String SERVER7 = "http://localhost"; - private HttpGet get1; - private HttpGet get2; - private static CloseableHttpResponse response; private HttpClientConnection conn1; private HttpClientConnection conn; private HttpClientConnection conn2; - private PoolingHttpClientConnectionManager poolingConnManager; + + private CloseableHttpResponse response; + private HttpGet get1; + private HttpGet get2; + private CloseableHttpClient client; @Before @@ -75,7 +79,7 @@ public class HttpClientConnectionManagementTest { response.close(); } - // tests + // 2 @Test // @Ignore @@ -102,12 +106,11 @@ public class HttpClientConnectionManagementTest { assertTrue(conn.isOpen()); } + // 3 + @Test // @Ignore - // Example 3.1. TESTER VERSION - public final void WhenTwoConnectionsForTwoRequests_ThenLeaseTwoConnectionsNoExceptions() throws InterruptedException { - get1 = new HttpGet("http://www.petrikainulainen.net/"); - get2 = new HttpGet("http://www.baeldung.com/"); + public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -122,10 +125,24 @@ public class HttpClientConnectionManagementTest { @Test // @Ignore - // Example 3.1.ARTICLE VERSION - public final void WhenTwoConnectionsForTwoRequests_ThensNoExceptions() throws InterruptedException { - get1 = new HttpGet("http://localhost"); - get2 = new HttpGet("http://google.com"); + // Example 3.2. TESTER VERSION + /*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { + poolingConnManager = new PoolingHttpClientConnectionManager(); + final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client1, get1, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client2, get2, poolingConnManager); + thread1.start(); + thread1.join(); + thread2.start(); + thread2.join(1000); + assertTrue(poolingConnManager.getTotalStats().getLeased() == 2); + } + + @Test + // @Ignore + // Example 3.2. ARTICLE VERSION + public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -139,7 +156,7 @@ public class HttpClientConnectionManagementTest { @Test // @Ignore - // 3.3 + // 3.4 public final void whenIncreasingConnectionPool_thenNoEceptions() { poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setMaxTotal(5); @@ -150,8 +167,8 @@ public class HttpClientConnectionManagementTest { @Test // @Ignore - // 3.4 Tester Version - public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimitNoExceptions() throws InterruptedException, IOException { + // 3.5 Tester Version + /*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { final HttpGet get = new HttpGet("http://google.com"); poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -170,8 +187,8 @@ public class HttpClientConnectionManagementTest { @Test // @Ignore - // 3.4 Article version - public final void whenExecutingSameRequestsInDifferentThreads_thenExxecuteReuqesttNoExceptions() throws InterruptedException { + // 3.5 Article version + public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException { final HttpGet get = new HttpGet("http://localhost"); poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -186,6 +203,8 @@ public class HttpClientConnectionManagementTest { thread3.join(); } + // 4 + @Test // @Ignore // 4.1 @@ -216,10 +235,12 @@ public class HttpClientConnectionManagementTest { client.execute(get2); } + // 5 + @Test // @Ignore // 5.1 - public final void GivenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { + public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { basicConnManager = new BasicHttpClientConnectionManager(); context = HttpClientContext.create(); final HttpGet get = new HttpGet("http://localhost"); @@ -245,7 +266,7 @@ public class HttpClientConnectionManagementTest { @Test // @Ignore // 5.2 TESTER VERSION - public final void WhenConnectionsNeededGreaterThanMaxTotal_thenReuseConnectionsNoExceptions() throws InterruptedException { + /*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setDefaultMaxPerRoute(5); poolingConnManager.setMaxTotal(5); @@ -266,10 +287,10 @@ public class HttpClientConnectionManagementTest { } } - // 5.2 ARTICLE VERSION @Test + // 5.2 ARTICLE VERSION // @Ignore - public final void WhenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuseNoExceptions() throws InterruptedException { + public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException { final HttpGet get = new HttpGet("http://echo.200please.com"); poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setDefaultMaxPerRoute(5); @@ -308,7 +329,7 @@ public class HttpClientConnectionManagementTest { @Test // @Ignore // 7.2 TESTER VERSION - public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConnsNoExceptions() throws InterruptedException, IOException { + /*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); From 2b704f933addf8fdcea554403e18ad5b53c59878 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 6 Jul 2014 16:41:37 +0300 Subject: [PATCH 09/32] further connection management work --- .../HttpClientConnectionManagementTest.java | 20 +++++++------------ .../IdleConnectionMonitorThread.java | 2 +- .../{ => conn}/MultiHttpClientConnThread.java | 2 +- ...sterVersion_MultiHttpClientConnThread.java | 2 +- 4 files changed, 10 insertions(+), 16 deletions(-) rename httpclient/src/test/java/org/baeldung/httpclient/{ => conn}/HttpClientConnectionManagementTest.java (95%) rename httpclient/src/test/java/org/baeldung/httpclient/{ => conn}/IdleConnectionMonitorThread.java (96%) rename httpclient/src/test/java/org/baeldung/httpclient/{ => conn}/MultiHttpClientConnThread.java (98%) rename httpclient/src/test/java/org/baeldung/httpclient/{ => conn}/TesterVersion_MultiHttpClientConnThread.java (97%) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java similarity index 95% rename from httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java rename to httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java index 293564086f..934c4bd761 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientConnectionManagementTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java @@ -1,4 +1,4 @@ -package org.baeldung.httpclient; +package org.baeldung.httpclient.conn; import static org.junit.Assert.assertTrue; @@ -109,18 +109,12 @@ public class HttpClientConnectionManagementTest { // 3 @Test - // @Ignore - public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws InterruptedException { + public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws InterruptedException, ClientProtocolException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); - final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); - final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); - final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client1, get1, poolingConnManager); - final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client2, get2, poolingConnManager); - thread1.start(); - thread1.join(); - thread2.start(); - thread2.join(1000); - assertTrue(poolingConnManager.getTotalStats().getLeased() == 2); + client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + client.execute(get1); + + assertTrue(poolingConnManager.getTotalStats().getLeased() == 1); } @Test @@ -149,8 +143,8 @@ public class HttpClientConnectionManagementTest { final MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client1, get1); final MultiHttpClientConnThread thread2 = new MultiHttpClientConnThread(client2, get2); thread1.start(); - thread1.join(); thread2.start(); + thread1.join(); thread2.join(); } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/IdleConnectionMonitorThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java similarity index 96% rename from httpclient/src/test/java/org/baeldung/httpclient/IdleConnectionMonitorThread.java rename to httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java index 4c4c7f36a1..cd0acef09b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/IdleConnectionMonitorThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java @@ -1,4 +1,4 @@ -package org.baeldung.httpclient; +package org.baeldung.httpclient.conn; import java.util.concurrent.TimeUnit; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java similarity index 98% rename from httpclient/src/test/java/org/baeldung/httpclient/MultiHttpClientConnThread.java rename to httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java index e2f8fabbdf..b21684fdbb 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java @@ -1,4 +1,4 @@ -package org.baeldung.httpclient; +package org.baeldung.httpclient.conn; import java.io.IOException; import java.util.logging.Level; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java similarity index 97% rename from httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java rename to httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java index 131761b072..9562ffbae1 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/TesterVersion_MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -1,4 +1,4 @@ -package org.baeldung.httpclient; +package org.baeldung.httpclient.conn; import java.io.IOException; import java.util.logging.Level; From fc6e8af9ea053452560c37e0d9d61e698648f90d Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 6 Jul 2014 16:51:41 +0300 Subject: [PATCH 10/32] cleanup work --- .../conn/MultiHttpClientConnThread.java | 38 ++++++++++--------- ...sterVersion_MultiHttpClientConnThread.java | 28 +++++++------- 2 files changed, 34 insertions(+), 32 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java index b21684fdbb..e29aa11a2b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java @@ -1,8 +1,6 @@ package org.baeldung.httpclient.conn; import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; @@ -10,52 +8,56 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MultiHttpClientConnThread extends Thread { + private final Logger logger = LoggerFactory.getLogger(getClass()); + private final CloseableHttpClient client; private final HttpGet get; - private PoolingHttpClientConnectionManager connManager = null; + + private PoolingHttpClientConnectionManager connManager; private static HttpResponse response; - private Logger logger; public int leasedConn; public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = connManager; - logger = Logger.getLogger(MultiHttpClientConnThread.class.getName()); - leasedConn = 0; + this.leasedConn = 0; } public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { this.client = client; this.get = get; - logger = Logger.getLogger(MultiHttpClientConnThread.class.getName()); } - public int getLeasedConn() { + // API + + public final int getLeasedConn() { return leasedConn; } - @Override - public void run() { + // + @Override + public final void run() { try { - if (this != null) - logger.log(Level.SEVERE, "Thread Running: " + getName()); + logger.info("Thread Running: " + getName()); + response = client.execute(get); if (connManager != null) { - logger.log(Level.SEVERE, "Leased Connections " + connManager.getTotalStats().getLeased()); + logger.info("Leased Connections " + connManager.getTotalStats().getLeased()); leasedConn = connManager.getTotalStats().getLeased(); - logger.log(Level.SEVERE, "Available Connections " + connManager.getTotalStats().getAvailable()); + logger.info("Available Connections " + connManager.getTotalStats().getAvailable()); } EntityUtils.consume(response.getEntity()); - } catch (final ClientProtocolException ex) { - + logger.error("", ex); } catch (final IOException ex) { - + logger.error("", ex); } - } + } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java index 9562ffbae1..99619d3023 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -1,49 +1,49 @@ package org.baeldung.httpclient.conn; import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class TesterVersion_MultiHttpClientConnThread extends Thread { + private final Logger logger = LoggerFactory.getLogger(getClass()); + private final CloseableHttpClient client; private final HttpGet get; - private PoolingHttpClientConnectionManager connManager = null; - private Logger logger; + private PoolingHttpClientConnectionManager connManager; public int leasedConn; public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = connManager; - logger = Logger.getLogger(TesterVersion_MultiHttpClientConnThread.class.getName()); leasedConn = 0; } - public int getLeasedConn() { + // + + public final int getLeasedConn() { return leasedConn; } @Override - public void run() { + public final void run() { try { - if (this != null) - logger.log(Level.SEVERE, "Thread Running: " + getName()); + logger.info("Thread Running: " + getName()); client.execute(get); if (connManager != null) { - logger.log(Level.SEVERE, "Leased Connections " + connManager.getTotalStats().getLeased()); + logger.info("Leased Connections " + connManager.getTotalStats().getLeased()); leasedConn = connManager.getTotalStats().getLeased(); - logger.log(Level.SEVERE, "Available Connections " + connManager.getTotalStats().getAvailable()); + logger.info("Available Connections " + connManager.getTotalStats().getAvailable()); } - } catch (final ClientProtocolException ex) { - + logger.error("", ex); } catch (final IOException ex) { - + logger.error("", ex); } } From 40dc518df0abd8e4baa609ee61738505cc42629c Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 6 Jul 2014 19:13:05 +0300 Subject: [PATCH 11/32] connection management work --- .../HttpClientConnectionManagementTest.java | 116 ++++++++++-------- .../conn/MultiHttpClientConnThread.java | 22 ++-- ...sterVersion_MultiHttpClientConnThread.java | 24 ++-- 3 files changed, 89 insertions(+), 73 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java index 934c4bd761..619e2539cf 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java @@ -33,6 +33,7 @@ import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; public class HttpClientConnectionManagementTest { @@ -58,31 +59,37 @@ public class HttpClientConnectionManagementTest { public final void before() { get1 = new HttpGet(SERVER1); get2 = new HttpGet(SERVER7); - route = new HttpRoute(new HttpHost("localhost", 80)); + route = new HttpRoute(new HttpHost("www.baeldung.com", 80)); } @After public final void after() throws IllegalStateException, IOException { - if (conn != null) + if (conn != null) { conn.close(); - if (conn1 != null) + } + if (conn1 != null) { conn1.close(); - if (conn2 != null) + } + if (conn2 != null) { conn2.close(); - if (poolingConnManager != null) + } + if (poolingConnManager != null) { poolingConnManager.shutdown(); - if (basicConnManager != null) + } + if (basicConnManager != null) { basicConnManager.shutdown(); - if (client != null) + } + if (client != null) { client.close(); - if (response != null) + } + if (response != null) { response.close(); + } } // 2 @Test - // @Ignore // 2.1 IN ARTCLE public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException { basicConnManager = new BasicHttpClientConnectionManager(); @@ -98,8 +105,9 @@ public class HttpClientConnectionManagementTest { context = HttpClientContext.create(); final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null); conn = connRequest.get(1000, TimeUnit.SECONDS); - if (!conn.isOpen()) + if (!conn.isOpen()) { basicConnManager.connect(conn, route, 1000, context); + } conn.setSocketTimeout(30000); assertTrue(conn.getSocketTimeout() == 30000); @@ -109,6 +117,7 @@ public class HttpClientConnectionManagementTest { // 3 @Test + // Example 3.1. public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws InterruptedException, ClientProtocolException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -127,8 +136,8 @@ public class HttpClientConnectionManagementTest { final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client1, get1, poolingConnManager); final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client2, get2, poolingConnManager); thread1.start(); - thread1.join(); thread2.start(); + thread1.join(); thread2.join(1000); assertTrue(poolingConnManager.getTotalStats().getLeased() == 2); } @@ -148,42 +157,40 @@ public class HttpClientConnectionManagementTest { thread2.join(); } + // 4 + @Test - // @Ignore - // 3.4 + // Example 4.1 public final void whenIncreasingConnectionPool_thenNoEceptions() { poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setMaxTotal(5); poolingConnManager.setDefaultMaxPerRoute(4); + final HttpHost localhost = new HttpHost("locahost", 80); poolingConnManager.setMaxPerRoute(new HttpRoute(localhost), 5); } @Test // @Ignore - // 3.5 Tester Version + // 4.2 Tester Version /*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { - final HttpGet get = new HttpGet("http://google.com"); poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); - final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); - final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); - final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, get, poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread2 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); + final TesterVersion_MultiHttpClientConnThread thread3 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); thread1.start(); - thread1.join(1000); - assertTrue(poolingConnManager.getTotalStats().getLeased() == 1); thread2.start(); - thread2.join(1000); - assertTrue(poolingConnManager.getTotalStats().getLeased() == 2); thread3.start(); - thread3.join(1000); + thread1.join(10000); + thread2.join(10000); + thread3.join(10000); } @Test - // @Ignore - // 3.5 Article version + // 4.2 Article version public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException { - final HttpGet get = new HttpGet("http://localhost"); + final HttpGet get = new HttpGet("http://www.google.com"); poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final MultiHttpClientConnThread thread1 = new MultiHttpClientConnThread(client, get); @@ -197,11 +204,11 @@ public class HttpClientConnectionManagementTest { thread3.join(); } - // 4 + // 5 @Test // @Ignore - // 4.1 + // 5.1 public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException { final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() { @Override @@ -229,37 +236,36 @@ public class HttpClientConnectionManagementTest { client.execute(get2); } - // 5 + // 6 @Test // @Ignore - // 5.1 + // 6.1 public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { basicConnManager = new BasicHttpClientConnectionManager(); context = HttpClientContext.create(); - final HttpGet get = new HttpGet("http://localhost"); - HttpResponse thisResponse = null; + final ConnectionRequest connRequest = basicConnManager.requestConnection(route, null); - client = HttpClients.custom().setConnectionManager(basicConnManager).build(); - boolean respAvail = false; conn = connRequest.get(10, TimeUnit.SECONDS); - if (!conn.isOpen()) { - basicConnManager.connect(conn, route, 1000, context); - basicConnManager.routeComplete(conn, route, context); - final HttpRequestExecutor exeRequest = new HttpRequestExecutor(); - context.setTargetHost((new HttpHost("localhost", 80))); - thisResponse = exeRequest.execute(get, conn, context); - respAvail = conn.isResponseAvailable(1000); - } + + basicConnManager.connect(conn, route, 1000, context); + basicConnManager.routeComplete(conn, route, context); + final HttpRequestExecutor exeRequest = new HttpRequestExecutor(); + context.setTargetHost((new HttpHost("www.baeldung.com", 80))); + + final HttpGet get = new HttpGet("http://www.baeldung.com"); + exeRequest.execute(get, conn, context); + conn.isResponseAvailable(1000); basicConnManager.releaseConnection(conn, null, 1, TimeUnit.SECONDS); - if (respAvail) { - client.execute(get); - } + + // + client = HttpClients.custom().setConnectionManager(basicConnManager).build(); + client.execute(get); } @Test // @Ignore - // 5.2 TESTER VERSION + // 6.2 TESTER VERSION /*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setDefaultMaxPerRoute(5); @@ -282,7 +288,7 @@ public class HttpClientConnectionManagementTest { } @Test - // 5.2 ARTICLE VERSION + // 7.2 ARTICLE VERSION // @Ignore public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException { final HttpGet get = new HttpGet("http://echo.200please.com"); @@ -304,7 +310,7 @@ public class HttpClientConnectionManagementTest { @Test // @Ignore - // 6.2.1 + // 7.2.1 public final void whenConfiguringTimeOut_thenNoExceptions() { route = new HttpRoute(new HttpHost("localhost", 80)); poolingConnManager = new PoolingHttpClientConnectionManager(); @@ -312,17 +318,19 @@ public class HttpClientConnectionManagementTest { assertTrue(poolingConnManager.getSocketConfig(route.getTargetHost()).getSoTimeout() == 5000); } + // 8 + @Test // @Ignore - // 7.1 + // 8.1 public final void whenHttpClientChecksStaleConns_thenNoExceptions() { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setStaleConnectionCheckEnabled(true).build()).setConnectionManager(poolingConnManager).build(); } @Test - // @Ignore - // 7.2 TESTER VERSION + @Ignore("Very Long Running") + // 8.2 TESTER VERSION /*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -345,7 +353,7 @@ public class HttpClientConnectionManagementTest { @Test // @Ignore - // 7.2 ARTICLE VERSION + // 8.2 ARTICLE VERSION public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException, IOException { final HttpGet get = new HttpGet("http://google.com"); poolingConnManager = new PoolingHttpClientConnectionManager(); @@ -355,9 +363,11 @@ public class HttpClientConnectionManagementTest { staleMonitor.join(1000); } + // 9 + @Test(expected = IllegalStateException.class) // @Ignore - // 8.1 + // 9.1 public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { route = new HttpRoute(new HttpHost("google.com", 80)); final HttpGet get = new HttpGet("http://google.com"); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java index e29aa11a2b..071b964710 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java @@ -18,14 +18,13 @@ public class MultiHttpClientConnThread extends Thread { private final HttpGet get; private PoolingHttpClientConnectionManager connManager; - private static HttpResponse response; public int leasedConn; public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = connManager; - this.leasedConn = 0; + leasedConn = 0; } public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { @@ -44,14 +43,23 @@ public class MultiHttpClientConnThread extends Thread { @Override public final void run() { try { - logger.info("Thread Running: " + getName()); + logger.debug("Thread Running: " + getName()); + + logger.debug("Thread Running: " + getName()); - response = client.execute(get); if (connManager != null) { - logger.info("Leased Connections " + connManager.getTotalStats().getLeased()); - leasedConn = connManager.getTotalStats().getLeased(); - logger.info("Available Connections " + connManager.getTotalStats().getAvailable()); + logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased()); + logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable()); } + + final HttpResponse response = client.execute(get); + + if (connManager != null) { + leasedConn = connManager.getTotalStats().getLeased(); + logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); + logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); + } + EntityUtils.consume(response.getEntity()); } catch (final ClientProtocolException ex) { logger.error("", ex); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java index 99619d3023..62cd466596 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -9,37 +9,35 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.base.Preconditions; + public class TesterVersion_MultiHttpClientConnThread extends Thread { private final Logger logger = LoggerFactory.getLogger(getClass()); private final CloseableHttpClient client; private final HttpGet get; private PoolingHttpClientConnectionManager connManager; - public int leasedConn; public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; - this.connManager = connManager; - leasedConn = 0; + this.connManager = Preconditions.checkNotNull(connManager); } // - public final int getLeasedConn() { - return leasedConn; - } - @Override public final void run() { try { - logger.info("Thread Running: " + getName()); + logger.debug("Thread Running: " + getName()); + + logger.info("Before - Leased Connections = " + connManager.getTotalStats().getLeased()); + logger.info("Before - Available Connections = " + connManager.getTotalStats().getAvailable()); + client.execute(get); - if (connManager != null) { - logger.info("Leased Connections " + connManager.getTotalStats().getLeased()); - leasedConn = connManager.getTotalStats().getLeased(); - logger.info("Available Connections " + connManager.getTotalStats().getAvailable()); - } + + logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); + logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); } catch (final ClientProtocolException ex) { logger.error("", ex); } catch (final IOException ex) { From c3f0555b20fd0142d48a1970e79f9a1710cb1065 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 6 Jul 2014 20:19:06 +0300 Subject: [PATCH 12/32] work on connection management --- .../HttpClientConnectionManagementTest.java | 25 ++++++++----------- .../conn/IdleConnectionMonitorThread.java | 8 +++--- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java index 619e2539cf..c5c960f527 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementTest.java @@ -288,7 +288,7 @@ public class HttpClientConnectionManagementTest { } @Test - // 7.2 ARTICLE VERSION + // 6.2 ARTICLE VERSION // @Ignore public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException { final HttpGet get = new HttpGet("http://echo.200please.com"); @@ -308,9 +308,10 @@ public class HttpClientConnectionManagementTest { } } + // 7 + @Test - // @Ignore - // 7.2.1 + // 7.1 public final void whenConfiguringTimeOut_thenNoExceptions() { route = new HttpRoute(new HttpHost("localhost", 80)); poolingConnManager = new PoolingHttpClientConnectionManager(); @@ -368,26 +369,20 @@ public class HttpClientConnectionManagementTest { @Test(expected = IllegalStateException.class) // @Ignore // 9.1 - public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions() throws InterruptedException, ExecutionException, IOException, HttpException { - route = new HttpRoute(new HttpHost("google.com", 80)); - final HttpGet get = new HttpGet("http://google.com"); + public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws InterruptedException, ExecutionException, IOException, HttpException { poolingConnManager = new PoolingHttpClientConnectionManager(); - final ConnectionRequest connRequest = poolingConnManager.requestConnection(route, null); - context = HttpClientContext.create(); - conn = connRequest.get(10, TimeUnit.SECONDS); - poolingConnManager.connect(conn, route, 10000, context); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); + final HttpGet get = new HttpGet("http://google.com"); response = client.execute(get); + EntityUtils.consume(response.getEntity()); - client.close(); - conn.close(); response.close(); + client.close(); poolingConnManager.close(); poolingConnManager.shutdown(); + client.execute(get); - conn.sendRequestHeader(get); - assertTrue(!conn.isOpen()); - assertTrue(conn.isOpen()); + assertTrue(response.getEntity() == null); } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java index cd0acef09b..2a1c419e41 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java @@ -14,8 +14,10 @@ public class IdleConnectionMonitorThread extends Thread { this.connMgr = connMgr; } + // API + @Override - public void run() { + public final void run() { try { while (!shutdown) { synchronized (this) { @@ -26,14 +28,14 @@ public class IdleConnectionMonitorThread extends Thread { } } catch (final InterruptedException ex) { shutdown(); - } } - public void shutdown() { + public final void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } + } From 8438a27f6f688f2abaf3c481f0ea4b854f0aecfb Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 9 Jul 2014 13:08:16 +0300 Subject: [PATCH 13/32] minor testing work --- .../java/io/JavaReaderToXUnitTest.java | 20 +++++----- .../java/io/JavaXToReaderUnitTest.java | 40 +++++++++++++++++++ 2 files changed, 50 insertions(+), 10 deletions(-) create mode 100644 core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java index 4e8b97f381..b5f846e885 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java @@ -19,15 +19,15 @@ public class JavaReaderToXUnitTest { // tests - Reader to String - @Test - public void givenUsingPlainJava_whenConvertingReaderIntoString_thenCorrect() throws IOException { - final Reader initialReader = new StringReader("text"); - - final char[] mediationArray = new char["text".length()]; - initialReader.read(mediationArray); - initialReader.close(); - final String targetString = new String(mediationArray); - } + // @Test + // public void givenUsingPlainJava_whenConvertingReaderIntoString_thenCorrect() throws IOException { + // final Reader initialReader = new StringReader("text"); + // // int bufferSize = initialReader.toString().length(); + // // char[] buffer = new char[bufferSize]; + // initialReader.read(buffer); + // initialReader.close(); + // final String targetString = new String(buffer); + // } @Test public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() throws IOException { @@ -37,7 +37,7 @@ public class JavaReaderToXUnitTest { } @Test - public void givenUsingCommonsIo_whenConvertingReaderIntoString_thenCorrect() throws IOException { + public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect() throws IOException { final Reader initialReader = new StringReader("Apache Commons IO 2.4"); final String targetString = IOUtils.toString(initialReader); initialReader.close(); diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java new file mode 100644 index 0000000000..f181fbd153 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java @@ -0,0 +1,40 @@ +package org.baeldung.java.io; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; + +import org.apache.commons.io.input.CharSequenceReader; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.io.CharSource; + +public class JavaXToReaderUnitTest { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + // tests - String to Reader + + @Test + public void givenUsingPlainJava_whenConvertingStringIntoReader_thenCorrect() throws IOException { + final String initialString = "With Plain Java"; + final Reader targetReader = new StringReader(initialString); + targetReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingStringIntoReader_thenCorrect() throws IOException { + final String initialString = "With Google Guava"; + final Reader targetReader = CharSource.wrap(initialString).openStream(); + targetReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingStringIntoReader_thenCorrect() throws IOException { + final String initialString = "With Apache Commons IO"; + final Reader targetReader = new CharSequenceReader(initialString); + targetReader.close(); + } + +} From 8b17941edb1149d3ec28a5ddc17a631367600934 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 9 Jul 2014 17:29:52 +0300 Subject: [PATCH 14/32] java testing work --- .../java/io/JavaXToReaderUnitTest.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java index f181fbd153..0d9f6d1f06 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java @@ -1,9 +1,13 @@ package org.baeldung.java.io; +import java.io.File; +import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; +import java.nio.charset.Charset; +import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.CharSequenceReader; import org.junit.Test; import org.slf4j.Logger; @@ -37,4 +41,57 @@ public class JavaXToReaderUnitTest { targetReader.close(); } + // tests - byte array to Reader + + @Test + public void givenUsingPlainJava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException { + final byte[] initialArray = "Hello world!".getBytes(); + final Reader targetReader = new StringReader(new String(initialArray)); + targetReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException { + final byte[] initialArray = "With Guava".getBytes(); + final String bufferString = new String(initialArray); + final Reader targetReader = CharSource.wrap(bufferString).openStream(); + + targetReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException { + final byte[] initialArray = "With Commons IO".getBytes(); + final Reader targetReader = new CharSequenceReader(new String(initialArray)); + targetReader.close(); + } + + // tests - File to Reader + + @Test + public void givenUsingPlainJava_whenConvertingFileIntoReader_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/initialFile.txt"); + initialFile.createNewFile(); + final Reader targetReader = new FileReader(initialFile); + targetReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingFileIntoReader_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/initialFile.txt"); + com.google.common.io.Files.touch(initialFile); + final Reader targetReader = com.google.common.io.Files.newReader(initialFile, Charset.defaultCharset()); + targetReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingFileIntoReader_thenCorrect() throws IOException { + final File initialFile = new File("src/test/resources/initialFile.txt"); + FileUtils.touch(initialFile); + FileUtils.write(initialFile, "With Commons IO"); + final byte[] buffer = FileUtils.readFileToByteArray(initialFile); + final Reader targetReader = new CharSequenceReader(new String(buffer)); + targetReader.close(); + } + } From bc29b044dceb4ed7984a899710e828da46439d89 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 9 Jul 2014 23:41:36 +0300 Subject: [PATCH 15/32] java testing work --- .../java/io/JavaXToByteArrayUnitTest.java | 11 ++++ .../java/io/JavaXToWriterUnitTest.java | 53 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/io/JavaXToByteArrayUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToByteArrayUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToByteArrayUnitTest.java new file mode 100644 index 0000000000..e45e3e73f4 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToByteArrayUnitTest.java @@ -0,0 +1,11 @@ +package org.baeldung.java.io; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JavaXToByteArrayUnitTest { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + // tests - X to Byte Array + +} diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java new file mode 100644 index 0000000000..35ec15df16 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java @@ -0,0 +1,53 @@ +package org.baeldung.java.io; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +import org.apache.commons.io.output.StringBuilderWriter; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.io.CharSink; + +public class JavaXToWriterUnitTest { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + // tests - byte[] to Writer + + @Test + public void givenPlainJava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException { + final byte[] initialArray = "With Java".getBytes(); + + final Writer targetWriter = new StringWriter().append(new String(initialArray)); + + targetWriter.close(); + } + + @Test + public void givenUsingGuava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException { + final byte[] initialArray = "With Guava".getBytes(); + + final String buffer = new String(initialArray); + final StringWriter stringWriter = new StringWriter(); + final CharSink charSink = new CharSink() { + @Override + public final Writer openStream() throws IOException { + return stringWriter; + } + }; + charSink.write(buffer); + + stringWriter.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException { + final byte[] initialArray = "With Commons IO".getBytes(); + final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray))); + + targetWriter.close(); + } + +} From 8228e34dc013ca2f891f45a01f530b3ca39e9100 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 9 Jul 2014 23:42:47 +0300 Subject: [PATCH 16/32] minor doc change --- .../java/io/JavaReaderToXUnitTest.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java index b5f846e885..ce40c12099 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java @@ -1,16 +1,25 @@ package org.baeldung.java.io; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.StringReader; +import java.io.Writer; +import java.nio.charset.Charset; +import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; +import org.apache.commons.io.input.CharSequenceReader; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.io.CharSink; import com.google.common.io.CharSource; import com.google.common.io.CharStreams; +import com.google.common.io.FileWriteMode; @SuppressWarnings("unused") public class JavaReaderToXUnitTest { @@ -43,4 +52,44 @@ public class JavaReaderToXUnitTest { initialReader.close(); } + // tests - Reader WRITE TO File + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoFile_thenCorrect() throws IOException { + final File sourceFile = new File("src/test/resources/sourceFile.txt"); + sourceFile.createNewFile(); + + final Reader initialReader = new FileReader(sourceFile); + final char[] buffer = new char[(int) sourceFile.length()]; + initialReader.read(buffer); + initialReader.close(); + + final File targetFile = new File("src/test/resources/targetFile.txt"); + targetFile.createNewFile(); + + final Writer targetFileWriter = new FileWriter(targetFile); + targetFileWriter.write(buffer); + targetFileWriter.close(); + } + + @Test + public void givenUsingGuava_whenConvertingReaderIntoFile_thenCorrect() throws IOException { + final Reader initialReader = CharSource.wrap("IDDQD").openStream(); + final File targetFile = new File("src/test/resources/targetFile.txt"); + com.google.common.io.Files.touch(targetFile); + final CharSink charSink = com.google.common.io.Files.asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND); + charSink.writeFrom(initialReader); + initialReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoFile_thenCorrect() throws IOException { + final Reader initialReader = new CharSequenceReader("CharSequenceReader extends Reader"); + final File targetFile = new File("src/test/resources/targetFile.txt"); + FileUtils.touch(targetFile); + final byte[] buffer = IOUtils.toByteArray(initialReader); + FileUtils.writeByteArrayToFile(targetFile, buffer); + initialReader.close(); + } + } From 092b3213ea830aa5889fab78b5840a800eb59aa6 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 12 Jul 2014 11:55:08 +0300 Subject: [PATCH 17/32] cleanup work in tests --- .../java/io/JavaReaderToXUnitTest.java | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java index ce40c12099..8923c5c797 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java @@ -26,17 +26,39 @@ public class JavaReaderToXUnitTest { protected final Logger logger = LoggerFactory.getLogger(getClass()); private static final int DEFAULT_SIZE = 1500000; + // tests - sandbox + // tests - Reader to String - // @Test - // public void givenUsingPlainJava_whenConvertingReaderIntoString_thenCorrect() throws IOException { - // final Reader initialReader = new StringReader("text"); - // // int bufferSize = initialReader.toString().length(); - // // char[] buffer = new char[bufferSize]; - // initialReader.read(buffer); - // initialReader.close(); - // final String targetString = new String(buffer); - // } + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoString1_thenCorrect() throws IOException { + final Reader reader = new StringReader("text"); + int intValueOfChar; + String targetString = ""; + while ((intValueOfChar = reader.read()) != -1) { + targetString += (char) intValueOfChar; + } + reader.close(); + + // test + System.out.println("targetString: " + targetString); + } + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoString2_thenCorrect() throws IOException { + final Reader reader = new StringReader("text"); + final char[] arr = new char[8 * 1024]; // 8K at a time + final StringBuffer buf = new StringBuffer(); + int numChars; + while ((numChars = reader.read(arr, 0, arr.length)) > 0) { + buf.append(arr, 0, numChars); + } + + reader.close(); + + // test + System.out.println("targetString: " + buf.toString()); + } @Test public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() throws IOException { From 120da93492ee79afa065a6d2f512a0fd6aad526f Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 12 Jul 2014 12:47:24 +0300 Subject: [PATCH 18/32] persistence cleanup work --- ...tenceServiceData.java => FooFixtures.java} | 32 +++------- ...oPaginationPersistenceIntegrationTest.java | 7 ++- .../FooSortingPersistenceServiceTest.java | 58 ++++++++----------- ...rentServicePersistenceIntegrationTest.java | 6 -- 4 files changed, 34 insertions(+), 69 deletions(-) rename spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/{FooSortingPersistenceServiceData.java => FooFixtures.java} (65%) diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceData.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooFixtures.java similarity index 65% rename from spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceData.java rename to spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooFixtures.java index 5b8696821d..8b16f9b605 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceData.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooFixtures.java @@ -8,26 +8,21 @@ import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; import com.google.common.collect.Lists; -public class FooSortingPersistenceServiceData { - private static ServiceRegistry serviceRegistry; - private static SessionFactory sessionFactory; - private static Configuration configuration; - private static StandardServiceRegistryBuilder builder; +public class FooFixtures { + private SessionFactory sessionFactory; - public FooSortingPersistenceServiceData() { + public FooFixtures(final SessionFactory sessionFactory) { super(); + + this.sessionFactory = sessionFactory; } - public void createBars() { + // API - configWork(); + public void createBars() { Session session = null; Transaction tx = null; session = sessionFactory.openSession(); @@ -66,8 +61,6 @@ public class FooSortingPersistenceServiceData { } public void createFoos() { - - configWork(); Session session = null; Transaction tx = null; session = sessionFactory.openSession(); @@ -105,15 +98,4 @@ public class FooSortingPersistenceServiceData { } } - public void configWork() { - configuration = new Configuration(); - configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty(AvailableSettings.DRIVER, "com.mysql.jdbc.Driver"); - configuration.setProperty(AvailableSettings.URL, "jdbc:mysql://localhost:3306/HIBERTEST2_TEST"); - configuration.setProperty(AvailableSettings.USER, "root"); - configuration.setProperty(AvailableSettings.PASS, ""); - builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); - sessionFactory = configuration.addPackage("com.cc.example.hibernate").addAnnotatedClass(Foo.class).addAnnotatedClass(Bar.class).configure().buildSessionFactory(builder.build()); - } } diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java index ec90c3779c..3d5c14231e 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooPaginationPersistenceIntegrationTest.java @@ -34,10 +34,10 @@ import com.google.common.collect.Lists; public class FooPaginationPersistenceIntegrationTest { @Autowired - private SessionFactory sessionFactory; + private IFooService fooService; @Autowired - private IFooService fooService; + private SessionFactory sessionFactory; private Session session; @@ -140,8 +140,9 @@ public class FooPaginationPersistenceIntegrationTest { int i = 0; while (pageSize > i++) { fooPage.add((Foo) resultScroll.get(0)); - if (!resultScroll.next()) + if (!resultScroll.next()) { break; + } } assertThat(fooPage, hasSize(lessThan(10 + 1))); diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java index 6b1f4318de..3e600816f5 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java @@ -5,8 +5,6 @@ import static org.junit.Assert.assertNull; import java.util.List; import java.util.Set; -import javax.imageio.spi.ServiceRegistry; - import org.baeldung.persistence.model.Bar; import org.baeldung.persistence.model.Foo; import org.baeldung.spring.PersistenceConfig; @@ -15,14 +13,12 @@ import org.hibernate.NullPrecedence; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Order; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -31,40 +27,32 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @SuppressWarnings("unchecked") public class FooSortingPersistenceServiceTest { - private SessionFactory sf; - private Session sess; - private static ServiceRegistry serviceRegistry; - private static Configuration configuration; - private static StandardServiceRegistryBuilder builder; + + @Autowired + private SessionFactory sessionFactory; + + private Session session; @Before public void before() { + session = sessionFactory.openSession(); - final FooSortingPersistenceServiceData fooData = new FooSortingPersistenceServiceData(); + session.beginTransaction(); + + final FooFixtures fooData = new FooFixtures(sessionFactory); fooData.createBars(); - configuration = new Configuration(); - configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect"); - configuration.setProperty(AvailableSettings.DRIVER, "com.mysql.jdbc.Driver"); - configuration.setProperty(AvailableSettings.URL, "jdbc:mysql://localhost:3306/HIBERTEST2_TEST"); - configuration.setProperty(AvailableSettings.USER, "root"); - configuration.setProperty(AvailableSettings.PASS, ""); - configuration.setProperty("hibernate.show_sql", "true"); - builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); - sf = configuration.addPackage("org.baeldung.persistence.model").addAnnotatedClass(Foo.class).addAnnotatedClass(Bar.class).configure().buildSessionFactory(builder.build()); - sess = sf.openSession(); - sess.beginTransaction(); } @After public void after() { - sess.getTransaction().commit(); + session.getTransaction().commit(); + session.close(); } @Test public final void whenHQlSortingByOneAttribute_thenPrintSortedResults() { final String hql = "FROM Foo f ORDER BY f.name"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); @@ -74,7 +62,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQlSortingByStringNullLast_thenLastNull() { final String hql = "FROM Foo f ORDER BY f.name NULLS LAST"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); assertNull(fooList.get(fooList.toArray().length - 1).getName()); @@ -86,7 +74,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenSortingByStringNullsFirst_thenReturnNullsFirst() { final String hql = "FROM Foo f ORDER BY f.name NULLS FIRST"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); assertNull(fooList.get(0).getName()); for (final Foo foo : fooList) { @@ -98,7 +86,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQlSortingByOneAttribute_andOrderDirection_thenPrintSortedResults() { final String hql = "FROM Foo f ORDER BY f.name ASC"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); @@ -108,7 +96,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQlSortingByMultipleAttributes_thenSortedResults() { final String hql = "FROM Foo f ORDER BY f.name, f.id"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); @@ -118,7 +106,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQlSortingByMultipleAttributes_andOrderDirection_thenPrintSortedResults() { final String hql = "FROM Foo f ORDER BY f.name DESC, f.id ASC"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List fooList = query.list(); for (final Foo foo : fooList) { System.out.println("Name: " + foo.getName() + ", Id: " + foo.getId()); @@ -127,7 +115,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() { - final Criteria criteria = sess.createCriteria(Foo.class, "FOO"); + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); criteria.addOrder(Order.asc("id")); final List fooList = criteria.list(); for (final Foo foo : fooList) { @@ -137,7 +125,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenHQLCriteriaSortingByMultipAttr_thenSortedResults() { - final Criteria criteria = sess.createCriteria(Foo.class, "FOO"); + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); criteria.addOrder(Order.asc("name")); criteria.addOrder(Order.asc("id")); final List fooList = criteria.list(); @@ -148,7 +136,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenCriteriaSortingStringNullsLastAsc_thenNullsLast() { - final Criteria criteria = sess.createCriteria(Foo.class, "FOO"); + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); criteria.addOrder(Order.asc("name").nulls(NullPrecedence.LAST)); final List fooList = criteria.list(); assertNull(fooList.get(fooList.toArray().length - 1).getName()); @@ -159,7 +147,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenCriteriaSortingStringNullsFirstDesc_thenNullsFirst() { - final Criteria criteria = sess.createCriteria(Foo.class, "FOO"); + final Criteria criteria = session.createCriteria(Foo.class, "FOO"); criteria.addOrder(Order.desc("name").nulls(NullPrecedence.FIRST)); final List fooList = criteria.list(); assertNull(fooList.get(0).getName()); @@ -171,7 +159,7 @@ public class FooSortingPersistenceServiceTest { @Test public final void whenSortingBars_thenBarsWithSortedFoos() { final String hql = "FROM Bar b ORDER BY b.id"; - final Query query = sess.createQuery(hql); + final Query query = session.createQuery(hql); final List barList = query.list(); for (final Bar bar : barList) { final Set fooSet = bar.getFooSet(); diff --git a/spring-hibernate4/src/test/java/org/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java b/spring-hibernate4/src/test/java/org/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java index aeeb810258..3960aa79ea 100644 --- a/spring-hibernate4/src/test/java/org/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java +++ b/spring-hibernate4/src/test/java/org/baeldung/persistence/service/ParentServicePersistenceIntegrationTest.java @@ -2,10 +2,7 @@ package org.baeldung.persistence.service; import org.baeldung.persistence.model.Child; import org.baeldung.persistence.model.Parent; -import org.baeldung.persistence.service.IChildService; -import org.baeldung.persistence.service.IParentService; import org.baeldung.spring.PersistenceConfig; -import org.hibernate.SessionFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -24,9 +21,6 @@ public class ParentServicePersistenceIntegrationTest { @Autowired private IChildService childService; - @Autowired - private SessionFactory sessionFactory; - // tests @Test From 6c52dfacbd2f0fe03d3528c07a597cb1734c4744 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 12 Jul 2014 21:43:03 +0300 Subject: [PATCH 19/32] io testign work --- .../java/io/JavaReaderToXUnitTest.java | 67 +++++++++++++------ core-java/src/test/resources/sourceFile.txt | 0 core-java/src/test/resources/targetFile.txt | 1 + 3 files changed, 49 insertions(+), 19 deletions(-) create mode 100644 core-java/src/test/resources/sourceFile.txt create mode 100644 core-java/src/test/resources/targetFile.txt diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java index 8923c5c797..3d9cdd8a2e 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java @@ -31,45 +31,39 @@ public class JavaReaderToXUnitTest { // tests - Reader to String @Test - public void givenUsingPlainJava_whenConvertingReaderIntoString1_thenCorrect() throws IOException { - final Reader reader = new StringReader("text"); + public void givenUsingPlainJava_whenConvertingReaderIntoStringV1_thenCorrect() throws IOException { + final StringReader reader = new StringReader("With Java 1"); int intValueOfChar; String targetString = ""; while ((intValueOfChar = reader.read()) != -1) { targetString += (char) intValueOfChar; } reader.close(); - - // test - System.out.println("targetString: " + targetString); } @Test - public void givenUsingPlainJava_whenConvertingReaderIntoString2_thenCorrect() throws IOException { - final Reader reader = new StringReader("text"); - final char[] arr = new char[8 * 1024]; // 8K at a time - final StringBuffer buf = new StringBuffer(); - int numChars; - while ((numChars = reader.read(arr, 0, arr.length)) > 0) { - buf.append(arr, 0, numChars); + public void givenUsingPlainJava_whenConvertingReaderIntoStringV2_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Java 1"); + final char[] arr = new char[8 * 1024]; + final StringBuilder buffer = new StringBuilder(); + int numCharsRead; + while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) { + buffer.append(arr, 0, numCharsRead); } - - reader.close(); - - // test - System.out.println("targetString: " + buf.toString()); + initialReader.close(); + final String targetString = buffer.toString(); } @Test public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() throws IOException { - final Reader initialReader = CharSource.wrap("Google Guava v.17.0").openStream(); + final Reader initialReader = CharSource.wrap("With Google Guava").openStream(); final String targetString = CharStreams.toString(initialReader); initialReader.close(); } @Test public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect() throws IOException { - final Reader initialReader = new StringReader("Apache Commons IO 2.4"); + final Reader initialReader = new StringReader("With Apache Commons"); final String targetString = IOUtils.toString(initialReader); initialReader.close(); } @@ -114,4 +108,39 @@ public class JavaReaderToXUnitTest { initialReader.close(); } + // tests - Reader to byte[] + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Java"); + + final char[] charArray = new char[8 * 1024]; + final StringBuilder builder = new StringBuilder(); + int numCharsRead; + while ((numCharsRead = initialReader.read(charArray, 0, charArray.length)) != -1) { + builder.append(charArray, 0, numCharsRead); + } + final byte[] targetArray = builder.toString().getBytes(); + + initialReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException { + final Reader initialReader = CharSource.wrap("With Google Guava").openStream(); + + final byte[] targetArray = CharStreams.toString(initialReader).getBytes(); + + initialReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException { + final StringReader initialReader = new StringReader("With Commons IO"); + + final byte[] targetArray = IOUtils.toByteArray(initialReader); + + initialReader.close(); + } + } diff --git a/core-java/src/test/resources/sourceFile.txt b/core-java/src/test/resources/sourceFile.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java/src/test/resources/targetFile.txt b/core-java/src/test/resources/targetFile.txt new file mode 100644 index 0000000000..f04ec3d9a9 --- /dev/null +++ b/core-java/src/test/resources/targetFile.txt @@ -0,0 +1 @@ +CharSequenceReader extends Reader \ No newline at end of file From 979cd6e3a46f9a580e670e664c15f95d6379d081 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 13 Jul 2014 21:29:13 +0300 Subject: [PATCH 20/32] IO testing work --- .../java/io/JavaReaderToXUnitTest.java | 40 +++++++++++++++++++ .../java/io/JavaXToReaderUnitTest.java | 37 +++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java index 3d9cdd8a2e..7cb9276283 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaReaderToXUnitTest.java @@ -1,9 +1,11 @@ package org.baeldung.java.io; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.Writer; @@ -143,4 +145,42 @@ public class JavaReaderToXUnitTest { initialReader.close(); } + // tests - Reader to InputStream + + @Test + public void givenUsingPlainJava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Java"); + + final char[] charBuffer = new char[8 * 1024]; + final StringBuilder builder = new StringBuilder(); + int numCharsRead; + while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) { + builder.append(charBuffer, 0, numCharsRead); + } + final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes()); + + initialReader.close(); + targetStream.close(); + } + + @Test + public void givenUsingGuava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException { + final Reader initialReader = new StringReader("With Guava"); + + final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes()); + + initialReader.close(); + targetStream.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException { + final Reader initialReader = new StringReader("With Commons IO"); + + final InputStream targetStream = IOUtils.toInputStream(initialReader.toString()); + + initialReader.close(); + targetStream.close(); + } + } diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java index 0d9f6d1f06..42ecef4086 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToReaderUnitTest.java @@ -1,18 +1,24 @@ package org.baeldung.java.io; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.nio.charset.Charset; import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.CharSequenceReader; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.io.ByteSource; +import com.google.common.io.ByteStreams; import com.google.common.io.CharSource; public class JavaXToReaderUnitTest { @@ -94,4 +100,35 @@ public class JavaXToReaderUnitTest { targetReader.close(); } + // tests - InputStream to Reader + + @Test + public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { + final InputStream initialStream = new ByteArrayInputStream("With Java".getBytes()); + final Reader targetReader = new InputStreamReader(initialStream); + + initialStream.close(); + targetReader.close(); + } + + @Test + public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { + final InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream(); + final byte[] buffer = ByteStreams.toByteArray(initialStream); + final Reader targetReader = CharSource.wrap(new String(buffer)).openStream(); + + initialStream.close(); + targetReader.close(); + } + + @Test + public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException { + final InputStream initialStream = IOUtils.toInputStream("With Commons IO"); + final byte[] buffer = IOUtils.toByteArray(initialStream); + final Reader targetReader = new CharSequenceReader(new String(buffer)); + + initialStream.close(); + targetReader.close(); + } + } From 1ee5b0580097a781d9d87b387d7aaa99a5b1bf9f Mon Sep 17 00:00:00 2001 From: Dheeraj-Baluja Date: Thu, 17 Jul 2014 01:36:40 +0530 Subject: [PATCH 21/32] adding spring form changes --- .../spring/controller/EmployeeController.java | 33 ++++++++++++++++ .../org/baeldung/spring/form/Employee.java | 33 ++++++++++++++++ .../src/main/resources/webMvcConfig.xml | 21 ++++++---- .../webapp/WEB-INF/view/employeeAdded.jsp | 24 ++++++++++++ .../main/webapp/WEB-INF/view/employeeHome.jsp | 38 +++++++++++++++++++ .../src/main/webapp/WEB-INF/view/error.jsp | 20 ++++++++++ .../src/main/webapp/WEB-INF/web.xml | 2 +- spring-mvc-xml/src/main/webapp/index.jsp | 18 +++++++++ 8 files changed, 181 insertions(+), 8 deletions(-) create mode 100644 spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java create mode 100644 spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeAdded.jsp create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp create mode 100644 spring-mvc-xml/src/main/webapp/WEB-INF/view/error.jsp create mode 100644 spring-mvc-xml/src/main/webapp/index.jsp diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java new file mode 100644 index 0000000000..0057f68df9 --- /dev/null +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java @@ -0,0 +1,33 @@ +package org.baeldung.spring.controller; + +import javax.validation.Valid; + +import org.baeldung.spring.form.Employee; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + + +@Controller +public class EmployeeController { + + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("id", employee.getId()); + return "employeeAdded"; + } +} diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java new file mode 100644 index 0000000000..7a9f7a4196 --- /dev/null +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java @@ -0,0 +1,33 @@ +package org.baeldung.spring.form; + +public class Employee { + + private String name; + private long id; + private String contactNumber; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(String contactNumber) { + this.contactNumber = contactNumber; + } + +} diff --git a/spring-mvc-xml/src/main/resources/webMvcConfig.xml b/spring-mvc-xml/src/main/resources/webMvcConfig.xml index 5f6e26643b..278f6c5533 100644 --- a/spring-mvc-xml/src/main/resources/webMvcConfig.xml +++ b/spring-mvc-xml/src/main/resources/webMvcConfig.xml @@ -1,16 +1,23 @@ - - - - - + + + + + + - + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeAdded.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeAdded.jsp new file mode 100644 index 0000000000..1457bc5fc8 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeAdded.jsp @@ -0,0 +1,24 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+
+ + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp new file mode 100644 index 0000000000..2f434fb7bd --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -0,0 +1,38 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + + + +SpringMVCExample + + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/error.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/error.jsp new file mode 100644 index 0000000000..8f3d83af17 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/error.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +SpringMVCExample + + + +

Pleas enter the correct details

+ + + + +
Retry
+ + + + \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml index 671813ac90..1a4128fb50 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/web.xml @@ -39,7 +39,7 @@ 10 - index.html + index.jsp \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/index.jsp b/spring-mvc-xml/src/main/webapp/index.jsp new file mode 100644 index 0000000000..1ecfcec9d7 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/index.jsp @@ -0,0 +1,18 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC Examples + + + +

Spring MVC Examples

+ + + + \ No newline at end of file From 0d5c627ebc94d5ccada9b2e19219e0e75e076bff Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 19 Jul 2014 21:33:42 +0300 Subject: [PATCH 22/32] testing work in core java --- core-java/pom.xml | 287 +++++++++--------- .../baeldung/java/CoreJavaRandomUnitTest.java | 126 ++++++++ 2 files changed, 273 insertions(+), 140 deletions(-) create mode 100644 core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java diff --git a/core-java/pom.xml b/core-java/pom.xml index 1986f3e981..5cfd60f746 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,176 +1,183 @@ - - 4.0.0 - org.baeldung - core-java - 0.1-SNAPSHOT + + 4.0.0 + org.baeldung + core-java + 0.1-SNAPSHOT - core-java + core-java - + - + - - com.google.guava - guava - ${guava.version} - + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-collections4 - 4.0 - + + org.apache.commons + commons-collections4 + 4.0 + - - commons-io - commons-io - 2.4 - + + commons-io + commons-io + 2.4 + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - + + org.apache.commons + commons-math3 + 3.3 + - + - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - + - + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + - - junit - junit-dep - ${junit.version} - test - + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + junit + junit-dep + ${junit.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - + + org.mockito + mockito-core + ${mockito.version} + test + - - core-java - - - src/main/resources - true - - + - + + core-java + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.7 - 1.7 - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.7 + 1.7 + + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + - + - - - 4.0.5.RELEASE - 3.2.4.RELEASE + - - 4.3.5.Final - 5.1.30 + + + 4.0.5.RELEASE + 3.2.4.RELEASE - - 2.3.3 + + 4.3.5.Final + 5.1.30 - - 1.7.6 - 1.1.1 + + 2.3.3 - - 5.1.1.Final + + 1.7.6 + 1.1.1 - - 17.0 - 3.3.2 + + 5.1.1.Final - - 1.3 - 4.11 - 1.9.5 + + 17.0 + 3.3.2 - 4.3.2 - 4.3.3 + + 1.3 + 4.11 + 1.9.5 - 2.3.1 + 4.3.2 + 4.3.3 - - 3.1 - 2.4 - 2.17 - 2.6 - 1.4.8 + 2.3.1 - + + 3.1 + 2.4 + 2.17 + 2.6 + 1.4.8 + + \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java new file mode 100644 index 0000000000..5ba312e08d --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java @@ -0,0 +1,126 @@ +package org.baeldung.java; + +import java.util.Random; + +import org.apache.commons.math3.random.RandomDataGenerator; +import org.junit.Test; + +public class CoreJavaRandomUnitTest { + + // tests - random long + + @Test + public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() { + final long generatedLong = new Random().nextLong(); + + System.out.println(generatedLong); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomLongBounded_thenCorrect() { + final long leftLimit = 1L; + final long rightLimit = 10L; + final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit)); + + System.out.println(generatedLong); + } + + @Test + public void givenUsingApacheCommons_whenGeneratingRandomLongBounded_thenCorrect() { + final long leftLimit = 10L; + final long rightLimit = 100L; + final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit); + + System.out.println(generatedLong); + } + + // tests - random int + + @Test + public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() { + final int generatedInteger = new Random().nextInt(); + + System.out.println(generatedInteger); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomIntegerBounded_thenCorrect() { + final int leftLimit = 1; + final int rightLimit = 10; + final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); + + System.out.println(generatedInteger); + } + + @Test + public void givenUsingApache_whenGeneratingRandomIntegerBounded_thenCorrect() { + final int leftLimit = 1; + final int rightLimit = 10; + final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit); + + System.out.println(generatedInteger); + } + + // tests - random float + + @Test + public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() { + final float generatedFloat = new Random().nextFloat(); + + System.out.println(generatedFloat); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomFloatBouned_thenCorrect() { + final float leftLimit = 1F; + final float rightLimit = 10F; + final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit); + + System.out.println(generatedFloat); + } + + @Test + public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() { + final float leftLimit = 1F; + final float rightLimit = 10F; + final float randomFloat = new RandomDataGenerator().getRandomGenerator().nextFloat(); + final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit); + + System.out.println(generatedFloat); + } + + // tests - random double + + @Test + public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() { + final double generatedDouble = Math.random(); + + System.out.println(generatedDouble); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomDoubleBounded_thenCorrect() { + final double leftLimit = 1D; + final double rightLimit = 10D; + final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit); + + System.out.println(generatedDouble); + } + + @Test + public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { + final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); + + System.out.println(generatedDouble); + } + + @Test + public void givenUsingApache_whenGeneratingRandomDoubleBounded_thenCorrect() { + final double leftLimit = 1D; + final double rightLimit = 100D; + final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit); + + System.out.println(generatedDouble); + } + +} From bda2923a84dba85dced310b418b212d73309afe7 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 20 Jul 2014 00:49:02 +0300 Subject: [PATCH 23/32] removing spring forms project --- .../WebContent/META-INF/MANIFEST.MF | 3 -- .../WebContent/WEB-INF/dispatcher-servlet.xml | 27 ------------- .../WEB-INF/views/employeeAdded.jsp | 24 ------------ .../WebContent/WEB-INF/views/employeeHome.jsp | 38 ------------------- .../WebContent/WEB-INF/views/error.jsp | 20 ---------- spring-mvc-forms/WebContent/WEB-INF/web.xml | 19 ---------- spring-mvc-forms/WebContent/index.jsp | 18 --------- .../demo/controllers/EmployeeController.java | 33 ---------------- .../src/com/demo/form/Employee.java | 33 ---------------- 9 files changed, 215 deletions(-) delete mode 100644 spring-mvc-forms/WebContent/META-INF/MANIFEST.MF delete mode 100644 spring-mvc-forms/WebContent/WEB-INF/dispatcher-servlet.xml delete mode 100644 spring-mvc-forms/WebContent/WEB-INF/views/employeeAdded.jsp delete mode 100644 spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp delete mode 100644 spring-mvc-forms/WebContent/WEB-INF/views/error.jsp delete mode 100644 spring-mvc-forms/WebContent/WEB-INF/web.xml delete mode 100644 spring-mvc-forms/WebContent/index.jsp delete mode 100644 spring-mvc-forms/src/com/demo/controllers/EmployeeController.java delete mode 100644 spring-mvc-forms/src/com/demo/form/Employee.java diff --git a/spring-mvc-forms/WebContent/META-INF/MANIFEST.MF b/spring-mvc-forms/WebContent/META-INF/MANIFEST.MF deleted file mode 100644 index 254272e1c0..0000000000 --- a/spring-mvc-forms/WebContent/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - diff --git a/spring-mvc-forms/WebContent/WEB-INF/dispatcher-servlet.xml b/spring-mvc-forms/WebContent/WEB-INF/dispatcher-servlet.xml deleted file mode 100644 index 1fc94effba..0000000000 --- a/spring-mvc-forms/WebContent/WEB-INF/dispatcher-servlet.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - /WEB-INF/views/ - - - .jsp - - - - \ No newline at end of file diff --git a/spring-mvc-forms/WebContent/WEB-INF/views/employeeAdded.jsp b/spring-mvc-forms/WebContent/WEB-INF/views/employeeAdded.jsp deleted file mode 100644 index 1457bc5fc8..0000000000 --- a/spring-mvc-forms/WebContent/WEB-INF/views/employeeAdded.jsp +++ /dev/null @@ -1,24 +0,0 @@ -<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> - - -Spring MVC Form Handling - - - -

Submitted Employee Information

- - - - - - - - - - - - - -
Name :${name}
ID :${id}
Contact Number :${contactNumber}
- - \ No newline at end of file diff --git a/spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp b/spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp deleted file mode 100644 index 497eade8c7..0000000000 --- a/spring-mvc-forms/WebContent/WEB-INF/views/employeeHome.jsp +++ /dev/null @@ -1,38 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> - - - - - -SpringMVCExample - - - -

Welcome, Enter The Employee Details

- - - - - - - - - - - - - - - - - - -
Name
Id
Contact Number
-
- - - - \ No newline at end of file diff --git a/spring-mvc-forms/WebContent/WEB-INF/views/error.jsp b/spring-mvc-forms/WebContent/WEB-INF/views/error.jsp deleted file mode 100644 index 8f3d83af17..0000000000 --- a/spring-mvc-forms/WebContent/WEB-INF/views/error.jsp +++ /dev/null @@ -1,20 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -SpringMVCExample - - - -

Pleas enter the correct details

- - - - -
Retry
- - - - \ No newline at end of file diff --git a/spring-mvc-forms/WebContent/WEB-INF/web.xml b/spring-mvc-forms/WebContent/WEB-INF/web.xml deleted file mode 100644 index 4c122670e5..0000000000 --- a/spring-mvc-forms/WebContent/WEB-INF/web.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - SpringMVCFormExample - - dispatcher - org.springframework.web.servlet.DispatcherServlet - - 1 - - - dispatcher - / - - - index.jsp - - \ No newline at end of file diff --git a/spring-mvc-forms/WebContent/index.jsp b/spring-mvc-forms/WebContent/index.jsp deleted file mode 100644 index 1ecfcec9d7..0000000000 --- a/spring-mvc-forms/WebContent/index.jsp +++ /dev/null @@ -1,18 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Spring MVC Examples - - - -

Spring MVC Examples

- - - - \ No newline at end of file diff --git a/spring-mvc-forms/src/com/demo/controllers/EmployeeController.java b/spring-mvc-forms/src/com/demo/controllers/EmployeeController.java deleted file mode 100644 index 1dd76ae23f..0000000000 --- a/spring-mvc-forms/src/com/demo/controllers/EmployeeController.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.demo.controllers; - -import javax.validation.Valid; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -import com.demo.form.Employee; - -@Controller -public class EmployeeController { - - @RequestMapping(value = "/employee", method = RequestMethod.GET) - public ModelAndView showForm() { - return new ModelAndView("employeeHome", "employee", new Employee()); - } - - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) - public String submit(@Valid @ModelAttribute("employee") Employee employee, BindingResult result, ModelMap model) { - if (result.hasErrors()) { - return "error"; - } - model.addAttribute("name", employee.getName()); - model.addAttribute("contactNumber", employee.getContactNumber()); - model.addAttribute("id", employee.getId()); - return "employeeAdded"; - } -} diff --git a/spring-mvc-forms/src/com/demo/form/Employee.java b/spring-mvc-forms/src/com/demo/form/Employee.java deleted file mode 100644 index 569347b628..0000000000 --- a/spring-mvc-forms/src/com/demo/form/Employee.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.demo.form; - -public class Employee { - - private String name; - private long id; - private String contactNumber; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getContactNumber() { - return contactNumber; - } - - public void setContactNumber(String contactNumber) { - this.contactNumber = contactNumber; - } - -} From a32f9673741780a246ed4069cd1bfc8db6105f38 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 20 Jul 2014 00:52:26 +0300 Subject: [PATCH 24/32] further cleanup work in mvc --- spring-mvc-xml/pom.xml | 8 +++++++- .../baeldung/spring/controller/EmployeeController.java | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 7238c7ec60..581de439c6 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -39,6 +39,12 @@ runtime + + org.hibernate + hibernate-validator + 5.1.1.Final + + @@ -120,7 +126,7 @@ maven-war-plugin ${maven-war-plugin.version} - + org.apache.maven.plugins maven-surefire-plugin diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java index 0057f68df9..007788a843 100644 --- a/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/controller/EmployeeController.java @@ -11,7 +11,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; - @Controller public class EmployeeController { @@ -30,4 +29,5 @@ public class EmployeeController { model.addAttribute("id", employee.getId()); return "employeeAdded"; } + } From e42eab8dfe0c0ec46d4dbf88ba903c081a6cc4d8 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sun, 20 Jul 2014 01:29:35 +0300 Subject: [PATCH 25/32] minor cleanup work on form project --- .../main/java/org/baeldung/spring/form/Employee.java | 12 +++++++++--- .../src/main/webapp/WEB-INF/view/employeeHome.jsp | 9 ++------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java index 7a9f7a4196..5de3d3c899 100644 --- a/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java +++ b/spring-mvc-xml/src/main/java/org/baeldung/spring/form/Employee.java @@ -6,11 +6,17 @@ public class Employee { private long id; private String contactNumber; + public Employee() { + super(); + } + + // + public String getName() { return name; } - public void setName(String name) { + public void setName(final String name) { this.name = name; } @@ -18,7 +24,7 @@ public class Employee { return id; } - public void setId(long id) { + public void setId(final long id) { this.id = id; } @@ -26,7 +32,7 @@ public class Employee { return contactNumber; } - public void setContactNumber(String contactNumber) { + public void setContactNumber(final String contactNumber) { this.contactNumber = contactNumber; } diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp index 2f434fb7bd..97b81b7693 100644 --- a/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -1,19 +1,14 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> - - SpringMVCExample -

Welcome, Enter The Employee Details

- + From 04f7919eb3b0ea3af72cacb0e0c11557a1a15cd8 Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 21 Jul 2014 22:08:24 +0300 Subject: [PATCH 26/32] java random examples --- .../baeldung/java/CoreJavaRandomUnitTest.java | 56 +++++++++++++++++-- 1 file changed, 50 insertions(+), 6 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java index 5ba312e08d..17a78651ff 100644 --- a/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/CoreJavaRandomUnitTest.java @@ -2,6 +2,7 @@ package org.baeldung.java; import java.util.Random; +import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; import org.junit.Test; @@ -99,17 +100,17 @@ public class CoreJavaRandomUnitTest { } @Test - public void givenUsingPlainJava_whenGeneratingRandomDoubleBounded_thenCorrect() { - final double leftLimit = 1D; - final double rightLimit = 10D; - final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit); + public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { + final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); System.out.println(generatedDouble); } @Test - public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() { - final double generatedDouble = new RandomDataGenerator().getRandomGenerator().nextDouble(); + public void givenUsingPlainJava_whenGeneratingRandomDoubleBounded_thenCorrect() { + final double leftLimit = 1D; + final double rightLimit = 10D; + final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit); System.out.println(generatedDouble); } @@ -123,4 +124,47 @@ public class CoreJavaRandomUnitTest { System.out.println(generatedDouble); } + // tests - random String + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { + final byte[] array = new byte[7]; // length is bounded by 7 + new Random().nextBytes(array); + final String generatedString = new String(array); + + System.out.println(generatedString); + } + + @Test + public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { + final int leftLimit = 97; // letter 'a' + final int rightLimit = 122; // letter 'z' + final int targetStringLength = 10; + final StringBuilder buffer = new StringBuilder(targetStringLength); + for (int i = 0; i < targetStringLength; i++) { + final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); + buffer.append((char) randomLimitedInt); + } + final String generatedString = new String(buffer); + + System.out.println(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomStringUnbounded_thenCorrect() { + final String generatedString = RandomStringUtils.random(10); + + System.out.println(generatedString); + } + + @Test + public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { + final int length = 10; + final boolean useLetters = true; + final boolean useNumbers = false; + final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); + + System.out.println(generatedString); + } + } From 3074920322845cc09ad44b22be51bf27c546b82e Mon Sep 17 00:00:00 2001 From: eugenp Date: Mon, 21 Jul 2014 22:48:18 +0300 Subject: [PATCH 27/32] minor jackson testing work --- .../baeldung/jackson/test/JacksonFieldUnitTest.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java b/jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java index fc8c7ff176..5acc3a92af 100644 --- a/jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java +++ b/jackson/src/test/java/org/baeldung/jackson/test/JacksonFieldUnitTest.java @@ -17,13 +17,12 @@ import org.junit.Test; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonFieldUnitTest { @Test - public final void givenDifferentAccessLevels_whenPrivateOrPackage_thenNotSerializable_whenPublic_thenSerializable() throws JsonProcessingException { + public final void givenDifferentAccessLevels_whenSerializing_thenPublicFieldsAreSerialized() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); final MyDtoAccessLevel dtoObject = new MyDtoAccessLevel(); @@ -48,7 +47,7 @@ public class JacksonFieldUnitTest { } @Test - public final void givenDifferentAccessLevels_whenGetterAdded_thenDeserializable() throws JsonProcessingException, JsonMappingException, IOException { + public final void givenDifferentAccessLevels_whenGetterAdded_thenDeserializable() throws IOException { final String jsonAsString = "{\"stringValue\":\"dtoString\",\"booleanValue\":\"true\"}"; final ObjectMapper mapper = new ObjectMapper(); @@ -60,7 +59,7 @@ public class JacksonFieldUnitTest { } @Test - public final void givenDifferentAccessLevels_whenSetterAdded_thenDeserializable() throws JsonProcessingException, JsonMappingException, IOException { + public final void givenDifferentAccessLevels_whenSetterAdded_thenDeserializable() throws IOException { final String jsonAsString = "{\"stringValue\":\"dtoString\",\"intValue\":1}"; final ObjectMapper mapper = new ObjectMapper(); @@ -72,7 +71,7 @@ public class JacksonFieldUnitTest { } @Test - public final void givenDifferentAccessLevels_whenSetterAdded_thenStillNotSerializable() throws JsonProcessingException, JsonMappingException, IOException { + public final void givenDifferentAccessLevels_whenSetterAdded_thenStillNotSerializable() throws IOException { final ObjectMapper mapper = new ObjectMapper(); final MyDtoSetter dtoObject = new MyDtoSetter(); @@ -84,7 +83,7 @@ public class JacksonFieldUnitTest { } @Test - public final void givenDifferentAccessLevels_whenSetVisibility_thenSerializable() throws JsonProcessingException, JsonMappingException, IOException { + public final void givenDifferentAccessLevels_whenSetVisibility_thenSerializable() throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); From fc35344f89e0de4307459ff6e4aa08b7006a7c54 Mon Sep 17 00:00:00 2001 From: egmp777 Date: Mon, 21 Jul 2014 16:39:43 -0500 Subject: [PATCH 28/32] Spring MVC Security Error Handling Code Samples --- .../.springBeans | 15 ++ spring-security-login-error-handling/pom.xml | 226 ++++++++++++++++++ ...SimpleUrlAuthenticationSuccessHandler.java | 81 +++++++ .../java/org/baeldung/spring/MvcConfig.java | 77 ++++++ .../baeldung/spring/SecSecurityConfig.java | 13 + .../src/main/resources/logback.xml | 20 ++ .../src/main/resources/messages_en.properties | 9 + .../main/resources/messages_es_ES.properties | 9 + .../src/main/resources/webSecurityConfig.xml | 38 +++ .../src/main/webapp/WEB-INF/mvc-servlet.xml | 10 + .../src/main/webapp/WEB-INF/view/admin.jsp | 23 ++ .../src/main/webapp/WEB-INF/view/console.jsp | 23 ++ .../src/main/webapp/WEB-INF/view/home.jsp | 13 + .../src/main/webapp/WEB-INF/view/homepage.jsp | 28 +++ .../webapp/WEB-INF/view/invalidSession.jsp | 12 + .../src/main/webapp/WEB-INF/view/login.jsp | 77 ++++++ .../src/main/webapp/WEB-INF/view/logout.jsp | 24 ++ .../main/webapp/WEB-INF/view/registration.jsp | 12 + .../src/main/webapp/WEB-INF/web.xml | 41 ++++ .../src/test/java/.springBeans | 15 ++ .../src/test/java/pom.xml | 225 +++++++++++++++++ 21 files changed, 991 insertions(+) create mode 100644 spring-security-login-error-handling/.springBeans create mode 100644 spring-security-login-error-handling/pom.xml create mode 100644 spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java create mode 100644 spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java create mode 100644 spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java create mode 100644 spring-security-login-error-handling/src/main/resources/logback.xml create mode 100644 spring-security-login-error-handling/src/main/resources/messages_en.properties create mode 100644 spring-security-login-error-handling/src/main/resources/messages_es_ES.properties create mode 100644 spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/mvc-servlet.xml create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/view/logout.jsp create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/view/registration.jsp create mode 100644 spring-security-login-error-handling/src/main/webapp/WEB-INF/web.xml create mode 100644 spring-security-login-error-handling/src/test/java/.springBeans create mode 100644 spring-security-login-error-handling/src/test/java/pom.xml diff --git a/spring-security-login-error-handling/.springBeans b/spring-security-login-error-handling/.springBeans new file mode 100644 index 0000000000..8096aa036b --- /dev/null +++ b/spring-security-login-error-handling/.springBeans @@ -0,0 +1,15 @@ + + + 1 + + + + + + + + + + + + diff --git a/spring-security-login-error-handling/pom.xml b/spring-security-login-error-handling/pom.xml new file mode 100644 index 0000000000..f806df0391 --- /dev/null +++ b/spring-security-login-error-handling/pom.xml @@ -0,0 +1,226 @@ + + + 4.0.0 + org.baeldung + spring-security-login-error-handling + spring-security-login-error-handling + war + 1.0.0-BUILD-SNAPSHOT + + 1.7 + 3.1.1.RELEASE + 3.2.4.RELEASE + 1.6.10 + 1.6.6 + + + org.springframework.boot + spring-boot-starter-parent + 1.1.1.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework + spring-context + + + + commons-logging + commons-logging + + + + + org.springframework + spring-core + + + + org.springframework + spring-webmvc + + + + org.springframework + spring-jdbc + + + + org.springframework + spring-beans + + + + org.springframework + spring-aop + + + org.springframework + spring-tx + + + org.springframework + spring-expression + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework.security + spring-security-config + runtime + + + + org.aspectj + aspectjrt + + + + javax.validation + validation-api + 1.1.0.Final + + + org.hibernate + hibernate-validator + + + + org.slf4j + slf4j-api + + + org.slf4j + jcl-over-slf4j + runtime + + + org.slf4j + slf4j-log4j12 + runtime + + + log4j + log4j + + + javax.mail + mail + + + javax.jms + jms + + + com.sun.jdmk + jmxtools + + + com.sun.jmx + jmxri + + + runtime + + + + + javax.inject + javax.inject + 1 + + + + + javax.servlet + servlet-api + 2.5 + provided + + + javax.servlet.jsp + jsp-api + 2.1 + provided + + + javax.servlet + jstl + + + + + org.springframework.security + spring-security-taglibs + + + + junit + junit + test + + + + + SpringSecurityLogin + + + src/main/resources + true + + + + + maven-eclipse-plugin + + + + org.springframework.ide.eclipse.core.springnature + + + org.springframework.ide.eclipse.core.springbuilder + + true + true + + + + org.apache.maven.plugins + maven-compiler-plugin + + + 1.7 + 1.7 + -Xlint:all + true + true + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.codehaus.mojo + exec-maven-plugin + + + org.test.int1.Main + + + + + diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..88862d603e --- /dev/null +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -0,0 +1,81 @@ +package org.baeldung.security; + +import java.io.IOException; +import java.util.Collection; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.web.DefaultRedirectStrategy; +import org.springframework.security.web.RedirectStrategy; +import org.springframework.security.web.WebAttributes; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { + protected Log logger = LogFactory.getLog(this.getClass()); + + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); + + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + handle(request, response, authentication); + HttpSession session = request.getSession(false); + if (session != null) { + session.setMaxInactiveInterval(30); + } + clearAuthenticationAttributes(request); + } + + protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + String targetUrl = determineTargetUrl(authentication); + + if (response.isCommitted()) { + logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); + return; + } + + redirectStrategy.sendRedirect(request, response, targetUrl); + } + + protected String determineTargetUrl(Authentication authentication) { + boolean isUser = false; + boolean isAdmin = false; + Collection authorities = authentication.getAuthorities(); + for (GrantedAuthority grantedAuthority : authorities) { + if (grantedAuthority.getAuthority().equals("ROLE_USER")) { + isUser = true; + break; + } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { + isAdmin = true; + break; + } + } + if (isUser) { + return "/homepage.html"; + } else if (isAdmin) { + return "/console.html"; + } else { + throw new IllegalStateException(); + } + } + + protected void clearAuthenticationAttributes(HttpServletRequest request) { + HttpSession session = request.getSession(false); + if (session == null) { + return; + } + session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); + } + + public void setRedirectStrategy(RedirectStrategy redirectStrategy) { + this.redirectStrategy = redirectStrategy; + } + + protected RedirectStrategy getRedirectStrategy() { + return redirectStrategy; + } +} \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..3cecdd9588 --- /dev/null +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java @@ -0,0 +1,77 @@ +package org.baeldung.spring; + +import java.util.Locale; + +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.i18n.CookieLocaleResolver; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@Configuration +@EnableWebMvc +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + // API + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/login.html"); + registry.addViewController("/logout.html"); + registry.addViewController("/homepage.html"); + registry.addViewController("/home.html"); + registry.addViewController("/invalidSession.html"); + registry.addViewController("/console.html"); + registry.addViewController("/admin.html"); + registry.addViewController("/registration.html"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("lang"); + registry.addInterceptor(localeChangeInterceptor); + } + + @Bean + public LocaleResolver localeResolver() { + CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); + cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); + return cookieLocaleResolver; + } + + @Bean + public MessageSource messageSource() { + ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); + messageSource.setBasename("classpath:messages"); + messageSource.setUseCodeAsDefaultMessage(true); + messageSource.setDefaultEncoding("UTF-8"); + messageSource.setCacheSeconds(0); + return messageSource; + } +} \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..99efdf4237 --- /dev/null +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -0,0 +1,13 @@ +package org.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ImportResource({ "classpath:webSecurityConfig.xml" }) +public class SecSecurityConfig { + + public SecSecurityConfig() { + super(); + } +} diff --git a/spring-security-login-error-handling/src/main/resources/logback.xml b/spring-security-login-error-handling/src/main/resources/logback.xml new file mode 100644 index 0000000000..1146dade63 --- /dev/null +++ b/spring-security-login-error-handling/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/resources/messages_en.properties b/spring-security-login-error-handling/src/main/resources/messages_en.properties new file mode 100644 index 0000000000..3e05a6b76a --- /dev/null +++ b/spring-security-login-error-handling/src/main/resources/messages_en.properties @@ -0,0 +1,9 @@ +message.username=Username required +message.password=Password required +message.unauth=Unauthorized Access !! +message.badCredentials=Invalid Username or Password +message.sessionExpired=Session Timed Out +message.logoutError=Sorry, error logging out +message.logoutSucc=You logged out successfully +message.regSucc=You registrated correctly, please log in +message.regError=There was a registration error please go back to registration \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties b/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties new file mode 100644 index 0000000000..842a899e43 --- /dev/null +++ b/spring-security-login-error-handling/src/main/resources/messages_es_ES.properties @@ -0,0 +1,9 @@ +message.username=Por favor ingrese el nombre de usuario +message.password=Por favor ingrese una clave +message.unauth=Acceso denegado !! +message.badCredentials=Usuario o clave invalida +message.sessionExpired=La sesion expiro +message.logoutError=Lo sentimos, hubo problemas en logout +message.logoutSucc=Logout con exito +message.regSucc=Se registro correctamente, por favor ingrese +message.regError=Hubo un error, por favor vuelva a registrarse \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml b/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..809fdd164d --- /dev/null +++ b/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-login-error-handling/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..b885d2c10a --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp new file mode 100644 index 0000000000..12f9f7aba9 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/admin.jsp @@ -0,0 +1,23 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> +<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> + + + + + + + + + + + +

Hello Admin

+
+ + ">Logout + ">Home + + + + diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp new file mode 100644 index 0000000000..05a930731b --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/console.jsp @@ -0,0 +1,23 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

This is the landing page for the admin

+ + + This text is only visible to a user +
+
+ + + This text is only visible to an admin +
+
+ + ">Logout + ">Administrator Page + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp new file mode 100644 index 0000000000..fe6e572b99 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/home.jsp @@ -0,0 +1,13 @@ +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ page session="true" %> + + + Home + + +

+ Welcome back home! +

+ + + diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp new file mode 100644 index 0000000000..fab96383df --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/homepage.jsp @@ -0,0 +1,28 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> +<%@ page session="true" %> + + + + + +

This is the homepage for the user

+ + + This text is only visible to a user +
+
+ + + This text is only visible to an admin +
+
+ + ">Logout + ">Home + ">Administrator Page + + + + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp new file mode 100644 index 0000000000..175c498117 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/invalidSession.jsp @@ -0,0 +1,12 @@ +<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> + + + Home + + +

+ +

+ + + diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp new file mode 100644 index 0000000000..95559b0455 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/login.jsp @@ -0,0 +1,77 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> +<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> + +<%@ page session="false"%> + +
+ +
+
+ +
+ +
+
+ + +
+ +
+ Register +
+ + + + + + + + + +

Login

+ English | + Spanish +
+ +
Name
+ + + + + + + + + + + +
User:
Password:
+ + +
Current Locale : ${pageContext.response.locale} + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/logout.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/logout.jsp new file mode 100644 index 0000000000..e8618b74e3 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/logout.jsp @@ -0,0 +1,24 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> +<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> + +
+ +
+
+ +
+ +
+
+ + + +Logged Out + + + + Login + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/registration.jsp b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/registration.jsp new file mode 100644 index 0000000000..474a1817b5 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/view/registration.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=US-ASCII" + pageEncoding="US-ASCII"%> + + + + +Registration + + +

This is the registration page

+ + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/webapp/WEB-INF/web.xml b/spring-security-login-error-handling/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..463b309377 --- /dev/null +++ b/spring-security-login-error-handling/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,41 @@ + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.spring + + + org.springframework.web.context.ContextLoaderListener + + + mvc + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc + / + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + localizationFilter + org.springframework.web.filter.RequestContextFilter + + + localizationFilter + /* + + \ No newline at end of file diff --git a/spring-security-login-error-handling/src/test/java/.springBeans b/spring-security-login-error-handling/src/test/java/.springBeans new file mode 100644 index 0000000000..8096aa036b --- /dev/null +++ b/spring-security-login-error-handling/src/test/java/.springBeans @@ -0,0 +1,15 @@ + + + 1 + + + + + + + + + + + + diff --git a/spring-security-login-error-handling/src/test/java/pom.xml b/spring-security-login-error-handling/src/test/java/pom.xml new file mode 100644 index 0000000000..5ff5926f60 --- /dev/null +++ b/spring-security-login-error-handling/src/test/java/pom.xml @@ -0,0 +1,225 @@ + + + 4.0.0 + com.egm + SpringSecurityLogin + SpringSecurityLogin + war + 1.0.0-BUILD-SNAPSHOT + + 1.7 + 3.1.1.RELEASE + 3.2.4.RELEASE + 1.6.10 + 1.6.6 + + + org.springframework.boot + spring-boot-starter-parent + 1.1.1.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework + spring-context + + + + commons-logging + commons-logging + + + + + org.springframework + spring-core + + + + org.springframework + spring-webmvc + + + + org.springframework + spring-jdbc + + + + org.springframework + spring-beans + + + + org.springframework + spring-aop + + + org.springframework + spring-tx + + + org.springframework + spring-expression + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework.security + spring-security-config + runtime + + + + org.aspectj + aspectjrt + + + + javax.validation + validation-api + 1.1.0.Final + + + org.hibernate + hibernate-validator + + + + org.slf4j + slf4j-api + + + org.slf4j + jcl-over-slf4j + runtime + + + org.slf4j + slf4j-log4j12 + runtime + + + log4j + log4j + + + javax.mail + mail + + + javax.jms + jms + + + com.sun.jdmk + jmxtools + + + com.sun.jmx + jmxri + + + runtime + + + + + javax.inject + javax.inject + 1 + + + + + javax.servlet + servlet-api + 2.5 + provided + + + javax.servlet.jsp + jsp-api + 2.1 + provided + + + javax.servlet + jstl + + + + org.springframework.security + spring-security-taglibs + + + + junit + junit + test + + + + + SpringSecurityLogin + + + src/main/resources + true + + + + + maven-eclipse-plugin + + + + org.springframework.ide.eclipse.core.springnature + + + org.springframework.ide.eclipse.core.springbuilder + + true + true + + + + org.apache.maven.plugins + maven-compiler-plugin + + + 1.7 + 1.7 + -Xlint:all + true + true + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.codehaus.mojo + exec-maven-plugin + + + org.test.int1.Main + + + + + From 1461358381cf1debe8eb76004367986dbd5a69da Mon Sep 17 00:00:00 2001 From: eugenp Date: Tue, 22 Jul 2014 01:10:21 +0300 Subject: [PATCH 29/32] minor cleanup work --- spring-security-login-error-handling/pom.xml | 41 ++-- ...SimpleUrlAuthenticationSuccessHandler.java | 6 +- .../java/org/baeldung/spring/MvcConfig.java | 1 + .../baeldung/spring/SecSecurityConfig.java | 1 + .../src/test/java/.springBeans | 15 -- .../src/test/java/pom.xml | 225 ------------------ 6 files changed, 29 insertions(+), 260 deletions(-) delete mode 100644 spring-security-login-error-handling/src/test/java/.springBeans delete mode 100644 spring-security-login-error-handling/src/test/java/pom.xml diff --git a/spring-security-login-error-handling/pom.xml b/spring-security-login-error-handling/pom.xml index f806df0391..81c3c4f785 100644 --- a/spring-security-login-error-handling/pom.xml +++ b/spring-security-login-error-handling/pom.xml @@ -7,19 +7,15 @@ spring-security-login-error-handling war 1.0.0-BUILD-SNAPSHOT - - 1.7 - 3.1.1.RELEASE - 3.2.4.RELEASE - 1.6.10 - 1.6.6 - + org.springframework.boot spring-boot-starter-parent 1.1.1.RELEASE + + org.springframework.boot @@ -39,22 +35,18 @@ org.springframework spring-core - org.springframework spring-webmvc - org.springframework spring-jdbc - org.springframework spring-beans - org.springframework @@ -81,21 +73,24 @@ spring-security-config runtime + org.aspectj aspectjrt + javax.validation - validation-api - 1.1.0.Final + validation-api + 1.1.0.Final org.hibernate hibernate-validator + org.slf4j @@ -160,11 +155,13 @@ jstl + org.springframework.security spring-security-taglibs + junit @@ -173,6 +170,7 @@ + SpringSecurityLogin @@ -181,10 +179,10 @@ true + maven-eclipse-plugin - org.springframework.ide.eclipse.core.springnature @@ -196,10 +194,10 @@ true + org.apache.maven.plugins maven-compiler-plugin - 1.7 1.7 @@ -208,19 +206,28 @@ true + org.apache.maven.plugins maven-war-plugin - + org.codehaus.mojo exec-maven-plugin - org.test.int1.Main + + + 1.7 + 3.1.1.RELEASE + 3.2.4.RELEASE + 1.6.10 + 1.6.6 + +
diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 88862d603e..825eaba71e 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -7,8 +7,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.DefaultRedirectStrategy; @@ -17,7 +17,7 @@ import org.springframework.security.web.WebAttributes; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { - protected Log logger = LogFactory.getLog(this.getClass()); + private final Logger logger = LoggerFactory.getLogger(getClass()); private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java index 3cecdd9588..2d83d6a5d9 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/MvcConfig.java @@ -74,4 +74,5 @@ public class MvcConfig extends WebMvcConfigurerAdapter { messageSource.setCacheSeconds(0); return messageSource; } + } \ No newline at end of file diff --git a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 99efdf4237..3e793a33f6 100644 --- a/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-login-error-handling/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -10,4 +10,5 @@ public class SecSecurityConfig { public SecSecurityConfig() { super(); } + } diff --git a/spring-security-login-error-handling/src/test/java/.springBeans b/spring-security-login-error-handling/src/test/java/.springBeans deleted file mode 100644 index 8096aa036b..0000000000 --- a/spring-security-login-error-handling/src/test/java/.springBeans +++ /dev/null @@ -1,15 +0,0 @@ - - - 1 - - - - - - - - - - - - diff --git a/spring-security-login-error-handling/src/test/java/pom.xml b/spring-security-login-error-handling/src/test/java/pom.xml deleted file mode 100644 index 5ff5926f60..0000000000 --- a/spring-security-login-error-handling/src/test/java/pom.xml +++ /dev/null @@ -1,225 +0,0 @@ - - - 4.0.0 - com.egm - SpringSecurityLogin - SpringSecurityLogin - war - 1.0.0-BUILD-SNAPSHOT - - 1.7 - 3.1.1.RELEASE - 3.2.4.RELEASE - 1.6.10 - 1.6.6 - - - org.springframework.boot - spring-boot-starter-parent - 1.1.1.RELEASE - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework - spring-context - - - - commons-logging - commons-logging - - - - - org.springframework - spring-core - - - - org.springframework - spring-webmvc - - - - org.springframework - spring-jdbc - - - - org.springframework - spring-beans - - - - org.springframework - spring-aop - - - org.springframework - spring-tx - - - org.springframework - spring-expression - - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.springframework.security - spring-security-config - runtime - - - - org.aspectj - aspectjrt - - - - javax.validation - validation-api - 1.1.0.Final - - - org.hibernate - hibernate-validator - - - - org.slf4j - slf4j-api - - - org.slf4j - jcl-over-slf4j - runtime - - - org.slf4j - slf4j-log4j12 - runtime - - - log4j - log4j - - - javax.mail - mail - - - javax.jms - jms - - - com.sun.jdmk - jmxtools - - - com.sun.jmx - jmxri - - - runtime - - - - - javax.inject - javax.inject - 1 - - - - - javax.servlet - servlet-api - 2.5 - provided - - - javax.servlet.jsp - jsp-api - 2.1 - provided - - - javax.servlet - jstl - - - - org.springframework.security - spring-security-taglibs - - - - junit - junit - test - - - - - SpringSecurityLogin - - - src/main/resources - true - - - - - maven-eclipse-plugin - - - - org.springframework.ide.eclipse.core.springnature - - - org.springframework.ide.eclipse.core.springbuilder - - true - true - - - - org.apache.maven.plugins - maven-compiler-plugin - - - 1.7 - 1.7 - -Xlint:all - true - true - - - - org.apache.maven.plugins - maven-war-plugin - - - - org.codehaus.mojo - exec-maven-plugin - - - org.test.int1.Main - - - - - From 5db4ad448c7eeb557de51933dc0c596a45c6b924 Mon Sep 17 00:00:00 2001 From: eugenp Date: Tue, 22 Jul 2014 01:14:07 +0300 Subject: [PATCH 30/32] maven work --- spring-security-login-error-handling/pom.xml | 46 +++++++------------- 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/spring-security-login-error-handling/pom.xml b/spring-security-login-error-handling/pom.xml index 81c3c4f785..aef8b966dd 100644 --- a/spring-security-login-error-handling/pom.xml +++ b/spring-security-login-error-handling/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 1.1.1.RELEASE + 1.1.4.RELEASE @@ -91,43 +91,25 @@ hibernate-validator - + + org.slf4j slf4j-api + + ch.qos.logback + logback-classic + + org.slf4j jcl-over-slf4j - runtime + - + org.slf4j - slf4j-log4j12 - runtime - - - log4j - log4j - - - javax.mail - mail - - - javax.jms - jms - - - com.sun.jdmk - jmxtools - - - com.sun.jmx - jmxri - - - runtime + log4j-over-slf4j @@ -227,7 +209,11 @@ 3.1.1.RELEASE 3.2.4.RELEASE 1.6.10 - 1.6.6 + + + 1.7.6 + 1.1.1 + From f5bcc39c75bba494ee1025dc4d1dc33486868375 Mon Sep 17 00:00:00 2001 From: eugenp Date: Tue, 22 Jul 2014 01:34:34 +0300 Subject: [PATCH 31/32] minor maven cleanup and formatting work --- spring-security-login-error-handling/pom.xml | 7 ---- .../src/main/resources/webSecurityConfig.xml | 34 +++++++++---------- 2 files changed, 16 insertions(+), 25 deletions(-) diff --git a/spring-security-login-error-handling/pom.xml b/spring-security-login-error-handling/pom.xml index aef8b966dd..d26e2d0d44 100644 --- a/spring-security-login-error-handling/pom.xml +++ b/spring-security-login-error-handling/pom.xml @@ -81,18 +81,12 @@ - - javax.validation - validation-api - 1.1.0.Final - org.hibernate hibernate-validator - org.slf4j slf4j-api @@ -135,7 +129,6 @@ javax.servlet jstl - diff --git a/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml b/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml index 809fdd164d..46550f03da 100644 --- a/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml +++ b/spring-security-login-error-handling/src/main/resources/webSecurityConfig.xml @@ -17,22 +17,20 @@ - - - - - - - - - - - - + default-target-url="/homepage.html" /> + + + + + + + + + + + + \ No newline at end of file From 52a134d5c0699b2ae504088189c25195140f925a Mon Sep 17 00:00:00 2001 From: eugenp Date: Tue, 22 Jul 2014 01:52:15 +0300 Subject: [PATCH 32/32] small spring upgrade --- spring-security-rest-full/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-security-rest-full/pom.xml b/spring-security-rest-full/pom.xml index cb5d3c4561..173f3bed6f 100644 --- a/spring-security-rest-full/pom.xml +++ b/spring-security-rest-full/pom.xml @@ -371,13 +371,13 @@ - 4.0.5.RELEASE + 4.0.6.RELEASE 3.2.4.RELEASE 4.3.5.Final - 5.1.30 - 1.6.0.RELEASE + 5.1.31 + 1.6.1.RELEASE