From 90a5a8c8d022758058844f4b6fdba0e83ad7d220 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Wed, 15 Feb 2017 21:46:45 +0530 Subject: [PATCH 01/23] Changes_for_BAEL-552-Update_SpringDataREST_article --- .../SpringDataRestValidatorTest.java | 186 ++++++++---------- 1 file changed, 86 insertions(+), 100 deletions(-) rename spring-data-rest/src/{main/test => test/java}/com/baeldung/validator/SpringDataRestValidatorTest.java (75%) diff --git a/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java similarity index 75% rename from spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java rename to spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java index b185c6d5ab..300fc081d3 100644 --- a/spring-data-rest/src/main/test/com/baeldung/validator/SpringDataRestValidatorTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorTest.java @@ -1,100 +1,86 @@ -package com.baeldung.validator; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.WebsiteUser; -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SpringDataRestApplication.class) -@WebAppConfiguration -public class SpringDataRestValidatorTest { - public static final String URL = "http://localhost"; - - private MockMvc mockMvc; - - @Autowired - protected WebApplicationContext wac; - - @Before - public void setup() { - mockMvc = webAppContextSetup(wac).build(); - } - - @Test - public void whenStartingApplication_thenCorrectStatusCode() throws Exception { - mockMvc.perform(get("/users")).andExpect(status().is2xxSuccessful()); - }; - - @Test - public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setEmail("john.doe@john.com"); - user.setName("John Doe"); - - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().is2xxSuccessful()) - .andExpect(redirectedUrl("http://localhost/users/1")); - } - - @Test - public void whenAddingNewUserWithoutName_thenErrorStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setEmail("john.doe@john.com"); - - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().isNotAcceptable()) - .andExpect(redirectedUrl(null)); - } - - @Test - public void whenAddingNewUserWithEmptyName_thenErrorStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setEmail("john.doe@john.com"); - user.setName(""); - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().isNotAcceptable()) - .andExpect(redirectedUrl(null)); - } - - @Test - public void whenAddingNewUserWithoutEmail_thenErrorStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setName("John Doe"); - - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().isNotAcceptable()) - .andExpect(redirectedUrl(null)); - } - - @Test - public void whenAddingNewUserWithEmptyEmail_thenErrorStatusCodeAndResponse() throws Exception { - WebsiteUser user = new WebsiteUser(); - user.setName("John Doe"); - user.setEmail(""); - mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))) - .andExpect(status().isNotAcceptable()) - .andExpect(redirectedUrl(null)); - } - -} +package com.baeldung.validator; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.SpringDataRestApplication; +import com.baeldung.models.WebsiteUser; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class) +@WebAppConfiguration +public class SpringDataRestValidatorTest { + public static final String URL = "http://localhost"; + + private MockMvc mockMvc; + + @Autowired + protected WebApplicationContext wac; + + @Before + public void setup() { + mockMvc = webAppContextSetup(wac).build(); + } + + @Test + public void whenStartingApplication_thenCorrectStatusCode() throws Exception { + mockMvc.perform(get("/users")).andExpect(status().is2xxSuccessful()); + }; + + @Test + public void whenAddingNewCorrectUser_thenCorrectStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + user.setName("John Doe"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().is2xxSuccessful()).andExpect(redirectedUrl("http://localhost/users/1")); + } + + @Test + public void whenAddingNewUserWithoutName_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithEmptyName_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setEmail("john.doe@john.com"); + user.setName(""); + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithoutEmail_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setName("John Doe"); + + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null)); + } + + @Test + public void whenAddingNewUserWithEmptyEmail_thenErrorStatusCodeAndResponse() throws Exception { + WebsiteUser user = new WebsiteUser(); + user.setName("John Doe"); + user.setEmail(""); + mockMvc.perform(post("/users", user).contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user))).andExpect(status().isNotAcceptable()).andExpect(redirectedUrl(null)); + } + +} From de376eb0fc7fe10c5a552ef1a8043b7fa0dc7bfd Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Fri, 17 Feb 2017 11:02:53 +0530 Subject: [PATCH 02/23] Update Application.java --- spring-boot/src/main/java/com/baeldung/utils/Application.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot/src/main/java/com/baeldung/utils/Application.java b/spring-boot/src/main/java/com/baeldung/utils/Application.java index 1f637eec11..a3d9f9130c 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/Application.java +++ b/spring-boot/src/main/java/com/baeldung/utils/Application.java @@ -12,7 +12,7 @@ public class Application { @RolesAllowed("*") public static void main(String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(Application.class, args); } } From 88a97726948c7dc422c1d3aa6087296e3f730c55 Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Fri, 17 Feb 2017 11:04:33 +0530 Subject: [PATCH 03/23] Update UtilsController.java --- .../java/com/baeldung/utils/controller/UtilsController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java index a14d0b26c6..7b4827cdf2 100644 --- a/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java +++ b/spring-boot/src/main/java/com/baeldung/utils/controller/UtilsController.java @@ -35,7 +35,7 @@ public class UtilsController { // } WebUtils.setSessionAttribute(request, "parameter", param); - model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); + model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); return "utils"; } From 8fe5a2ac727031afc043b89839844ff4fb4d5a97 Mon Sep 17 00:00:00 2001 From: lor6 Date: Fri, 17 Feb 2017 17:06:34 +0200 Subject: [PATCH 04/23] Bael 682 (#1124) * upload, read excel files with mvc * formatting * add excel files * update excel files --- spring-mvc-java/persons.xls | Bin 0 -> 33792 bytes spring-mvc-java/persons.xlsx | Bin 0 -> 13514 bytes spring-mvc-java/pom.xml | 16 -- .../com/baeldung/excel/ExcelPOIHelper.java | 264 +++++++++++------- .../java/com/baeldung/excel/JExcelHelper.java | 82 ------ .../main/java/com/baeldung/excel/MyCell.java | 57 ++++ .../baeldung/spring/web/config/WebConfig.java | 5 - .../web/controller/ExcelController.java | 50 +--- .../src/main/webapp/WEB-INF/view/excel.jsp | 80 +++--- 9 files changed, 254 insertions(+), 300 deletions(-) create mode 100644 spring-mvc-java/persons.xls create mode 100644 spring-mvc-java/persons.xlsx delete mode 100644 spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java create mode 100644 spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java diff --git a/spring-mvc-java/persons.xls b/spring-mvc-java/persons.xls new file mode 100644 index 0000000000000000000000000000000000000000..ea270f69cc8eb16b866db0414dde14c23ae9d365 GIT binary patch literal 33792 zcmeHw2|QF^*zlRLjeRFeO!l(xWKTlbLR3VSv1H4VRJKH=MWQ`v6;aY6ib`k^Er_yJ zXqUA4E782?%ovR^{Pn)?_kHj8eU9Imd+&3f?L6l>&spxd*W*XLFOOdk?F2N*7%+g} zL{`8|1;@a1Q_3|DfcJ?+bV)gyz;g(iPX8BKfE5QTl9>rO>pftpslWhc763W{78Ehw zg1-QC!R!uJ0}cRO14Dho)<)u&L=qzK|EtqHk`7)Nqytn77{N0P$bwK_AVSiNkMzq= z`aMs=D<}OL0X|3r)ABqSJ<eo$ z26~!52mnzd{)T}bIe8rcz&6TnyhI6L3a$6=JoF~yA;BmPm|!gfDH$ngC246j&)Ej< z3X}`?*%FMiU{4`F=DwRF!FR=2Bq_iGX8u7^Q5(w#UL#iWP*o{fEE;YjsJdVd&;Y;_ zsWJyo(QM?>U4aB}pKUM#kW!X{dV4CEdO|5GU^e`Nq||hC@YF>B>E5KOCSI}6M%jqo^&MtRNxVui30ylxit;{ zuh<9CVgR1Z0{voX?0I?Q7USWu_8*0xp8%dZ0sPPe@S_vJ^Cy6xod7nPmM@22EUNx(?fhY7|IlAV7*1X7~-=j;jKN)y26 z(1o)>o+SP>@r0cMAFW@qAHtC#8UG1z03dM&9Iuhe#W@BJgeY*XKX5!e9S^6G%T2)_ zwGY{U;JB3{cO^U(rSRvaz(@6@@#idFULkfNXlHV}L!(7fc_DwYohj{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mpy+d>h|p~08l5AZ5d-hAuprAd zfxcsuR)9DC^mKH5y><1J^?eBhWi35zFJ*l%9bIKTf}fVRwwIo-mo9v9dpb>9VA=xH z7MQlcv<0RuFl~Wp3rt&J+5*!Sn6|*Q1^%~K0L^dFd=|}l(X)K?PBq#Lg67TWnLe7= zqj&nzgc;4n(YzP!Z$Wc>G@pmxRU zDcY2y1vC2mu@21Wz8*ZHxjXvL90o8O!i@ga1=>r4?hnI^j{iR=N4Sd~eM}M$zov`+ zeFgf0?%yOKz(m^dgKUWW2#-U*0925E!2)pzlzkPb8zVqYugYL0!n-ME&zk>52F%K>4T*q4qOX`RE@# gks1#?Fu`wEhQT))kPhUpO8lKZdjE;?>r%=856^P^mH+?% literal 0 HcmV?d00001 diff --git a/spring-mvc-java/persons.xlsx b/spring-mvc-java/persons.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..1f58606532f81e6d03575f4e127b841c31a61304 GIT binary patch literal 13514 zcmeHuRd5{1677hYC5xGv87;P$naN@XihfAe*<8?Rh3+#)ns(!K3+J=!Z20q=i12fm3l5J?ka^ z(*b`3_y^5O%a6opxI)YXYa0k3agkE(8~SBbL|?_E#%RsaizWhhvwDKXQG7#`Jdzky zV6JL6eB)c{!IM4aEW@TR5MUcCsNMCiuNH>CYs9tNPBxavP@P*P&>H1Cn%)XZPGSTP zzi;zeu5tb>;5VZIqM%$XfJG5PjqG4VwWDa}htu}nO|uXWJIc_MPr&|&68d!Fu)@_r z|Cu*nI#xy{SAO39%u#og5c8eW{<}l>xT?Z%aw%NXll41nAHGPIZ;+fEGkci9jQ2!m z%(0j59l=yiAYl!qAa=SxsXW4UN&y~H-#d245uWD-_5&p>Q8Oj7R{(3}HH2{-t^1nL zpx9jS!?k9-$nHDU47?3)pCQ+hvKZrZoY;M6oxmA>K=3>QN%{5$22l75WzqD$nSuf- zy8&b*9FVg5j;7X5j10fM|BtHw#r*u!&@19)rNNkyL(T) ztFa)>2xb@Jem*|vddH5q4Tg5xOh(z?JW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3BK#`O`UBzm9|-?1sn)N6ziOTS0K5gZje+C&Rr&NQ zz~C>9=05;hfFd~{z#nbrUrm4Qas6TH4s3b-b1wg>JNu*K^()F>TNi&|000L-{noFI zj9;z)S}*>ybuBOu{@eOr)#G2ye=Yd^0l-M~`w;$r%74Ft{x#VC0SN#=GyeHI{X6t3 WNJ9Xf__szs0^lQ%2eQn+UHu<^-Hi7D literal 0 HcmV?d00001 diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 9513c81064..ef18cef3e0 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -161,26 +161,11 @@ - - org.apache.poi - poi - ${poi.version} - org.apache.poi poi-ooxml ${poi.version} - - org.apache.poi - poi-ooxml-schemas - ${poi.version} - - - org.jxls - jxls-jexcel - ${jexcel.version} - @@ -395,7 +380,6 @@ 3.16-beta1 - 1.0.6 diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java b/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java index 5cf74aff63..e3658e8f89 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java +++ b/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java @@ -1,140 +1,188 @@ package com.baeldung.excel; import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFFont; +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FillPatternType; + import java.io.File; -import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; -import org.springframework.stereotype.Service; +import java.util.List; -@Service public class ExcelPOIHelper { - public Map> readExcel(String fileLocation) throws IOException { + public Map> readExcel(String fileLocation) throws IOException { - Map> data = new HashMap>(); - FileInputStream file = new FileInputStream(new File(fileLocation)); - Workbook workbook = new XSSFWorkbook(file); - Sheet sheet = workbook.getSheetAt(0); - int i = 0; - for (Row row : sheet) { - data.put(i, new ArrayList()); - for (Cell cell : row) { - switch (cell.getCellTypeEnum()) { - case STRING: - data.get(i) - .add(cell.getRichStringCellValue() - .getString()); - break; - case NUMERIC: - if (DateUtil.isCellDateFormatted(cell)) { - data.get(i) - .add(cell.getDateCellValue() + ""); - } else { - data.get(i) - .add(cell.getNumericCellValue() + ""); - } - break; - case BOOLEAN: - data.get(i) - .add(cell.getBooleanCellValue() + ""); - break; - case FORMULA: - data.get(i) - .add(cell.getCellFormula() + ""); - break; - default: - data.get(i) - .add(" "); + Map> data = new HashMap<>(); + FileInputStream fis = new FileInputStream(new File(fileLocation)); + + if (fileLocation.endsWith(".xls")) { + data = readHSSFWorkbook(fis); + } else if (fileLocation.endsWith(".xlsx")) { + data = readXSSFWorkbook(fis); + } + + int maxNrCols = 0; + + for (List ls : data.values()) { + if (ls.size() > maxNrCols) { + maxNrCols = ls.size(); + } + } + + for (List ls : data.values()) { + if (ls.size() < maxNrCols) { + for (int i = ls.size(); i < maxNrCols; i++) { + ls.add(new MyCell("")); } } - i++; } - if (workbook != null){ - workbook.close(); + + return data; + } + + private String readCellContent(Cell cell) { + String content = ""; + switch (cell.getCellTypeEnum()) { + case STRING: + content = cell.getStringCellValue(); + break; + case NUMERIC: + if (DateUtil.isCellDateFormatted(cell)) { + content = cell.getDateCellValue() + ""; + } else { + content = cell.getNumericCellValue() + ""; + } + break; + case BOOLEAN: + content = cell.getBooleanCellValue() + ""; + break; + case FORMULA: + content = cell.getCellFormula() + ""; + break; + default: + content = ""; + } + return content; + } + + private Map> readHSSFWorkbook(FileInputStream fis) throws IOException { + Map> data = new HashMap<>(); + HSSFWorkbook workbook = null; + try { + workbook = new HSSFWorkbook(fis); + + HSSFSheet sheet = workbook.getSheetAt(0); + for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { + HSSFRow row = sheet.getRow(i); + data.put(i, new ArrayList()); + if (row != null) { + for (int j = 0; j < row.getLastCellNum(); j++) { + HSSFCell cell = row.getCell(j); + if (cell != null) { + HSSFCellStyle cellStyle = cell.getCellStyle(); + + MyCell myCell = new MyCell(); + + HSSFColor bgColor = cellStyle.getFillForegroundColorColor(); + if (bgColor != null) { + short[] rgbColor = bgColor.getTriplet(); + myCell.setBgColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")"); + } + HSSFFont font = cell.getCellStyle() + .getFont(workbook); + myCell.setTextSize(font.getFontHeightInPoints() + ""); + if (font.getBold()) { + myCell.setTextWeight("bold"); + } + HSSFColor textColor = font.getHSSFColor(workbook); + if (textColor != null) { + short[] rgbColor = textColor.getTriplet(); + myCell.setTextColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")"); + } + myCell.setContent(readCellContent(cell)); + data.get(i) + .add(myCell); + } else { + data.get(i) + .add(new MyCell("")); + } + } + } + } + } finally { + if (workbook != null) { + workbook.close(); + } } return data; } - public void writeExcel() throws IOException { - Workbook workbook = new XSSFWorkbook(); - + private Map> readXSSFWorkbook(FileInputStream fis) throws IOException { + XSSFWorkbook workbook = null; + Map> data = new HashMap<>(); try { - Sheet sheet = workbook.createSheet("Persons"); - sheet.setColumnWidth(0, 6000); - sheet.setColumnWidth(1, 4000); - Row header = sheet.createRow(0); + workbook = new XSSFWorkbook(fis); + XSSFSheet sheet = workbook.getSheetAt(0); - CellStyle headerStyle = workbook.createCellStyle(); + for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { + XSSFRow row = sheet.getRow(i); + data.put(i, new ArrayList()); + if (row != null) { + for (int j = 0; j < row.getLastCellNum(); j++) { + XSSFCell cell = row.getCell(j); + if (cell != null) { + XSSFCellStyle cellStyle = cell.getCellStyle(); - headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); - headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - - XSSFFont font = ((XSSFWorkbook) workbook).createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short) 16); - font.setBold(true); - headerStyle.setFont(font); - - Cell headerCell = header.createCell(0); - headerCell.setCellValue("Name"); - headerCell.setCellStyle(headerStyle); - - headerCell = header.createCell(1); - headerCell.setCellValue("Age"); - headerCell.setCellStyle(headerStyle); - - CellStyle style = workbook.createCellStyle(); - style.setWrapText(true); - - Row row = sheet.createRow(2); - Cell cell = row.createCell(0); - cell.setCellValue("John Smith"); - cell.setCellStyle(style); - - cell = row.createCell(1); - cell.setCellValue(20); - cell.setCellStyle(style); - - row = sheet.createRow(3); - cell = row.createCell(0); - cell.setCellValue("Ana Johnson"); - cell.setCellStyle(style); - - cell = row.createCell(1); - cell.setCellValue(30); - cell.setCellStyle(style); - - File currDir = new File("."); - String path = currDir.getAbsolutePath(); - String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx"; - - FileOutputStream outputStream = new FileOutputStream(fileLocation); - workbook.write(outputStream); - } finally { - if (workbook != null) { - try { - workbook.close(); - } catch (IOException e) { - e.printStackTrace(); + MyCell myCell = new MyCell(); + XSSFColor bgColor = cellStyle.getFillForegroundColorColor(); + if (bgColor != null) { + byte[] rgbColor = bgColor.getRGB(); + myCell.setBgColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")"); + } + XSSFFont font = cellStyle.getFont(); + myCell.setTextSize(font.getFontHeightInPoints() + ""); + if (font.getBold()) { + myCell.setTextWeight("bold"); + } + XSSFColor textColor = font.getXSSFColor(); + if (textColor != null) { + byte[] rgbColor = textColor.getRGB(); + myCell.setTextColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")"); + } + myCell.setContent(readCellContent(cell)); + data.get(i) + .add(myCell); + } else { + data.get(i) + .add(new MyCell("")); + } + } } } + } finally { + if (workbook != null) { + workbook.close(); + } } + return data; } } \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java b/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java deleted file mode 100644 index d0e33bf471..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.excel; - -import jxl.Sheet; -import jxl.Workbook; -import jxl.format.Colour; -import jxl.read.biff.BiffException; -import jxl.write.*; -import jxl.write.Number; -import org.springframework.stereotype.Service; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -@Service -public class JExcelHelper { - - public Map> readJExcel(String fileLocation) throws IOException, BiffException { - Map> data = new HashMap<>(); - - Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); - Sheet sheet = workbook.getSheet(0); - int rows = sheet.getRows(); - int columns = sheet.getColumns(); - - for (int i = 0; i < rows; i++) { - data.put(i, new ArrayList<>()); - for (int j = 0; j < columns; j++) { - data.get(i).add(sheet.getCell(j, i).getContents()); - } - } - return data; - } - - public void writeJExcel() throws IOException, WriteException { - WritableWorkbook workbook = null; - try { - File currDir = new File("."); - String path = currDir.getAbsolutePath(); - String fileLocation = path.substring(0, path.length() - 1) + "temp.xls"; - - workbook = Workbook.createWorkbook(new File(fileLocation)); - - WritableSheet sheet = workbook.createSheet("Sheet 1", 0); - - WritableCellFormat headerFormat = new WritableCellFormat(); - WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD); - headerFormat.setFont(font); - headerFormat.setBackground(Colour.LIGHT_BLUE); - headerFormat.setWrap(true); - Label headerLabel = new Label(0, 0, "Name", headerFormat); - sheet.setColumnView(0, 60); - sheet.addCell(headerLabel); - - headerLabel = new Label(1, 0, "Age", headerFormat); - sheet.setColumnView(0, 40); - sheet.addCell(headerLabel); - - WritableCellFormat cellFormat = new WritableCellFormat(); - cellFormat.setWrap(true); - - Label cellLabel = new Label(0, 2, "John Smith", cellFormat); - sheet.addCell(cellLabel); - Number cellNumber = new Number(1, 2, 20, cellFormat); - sheet.addCell(cellNumber); - - cellLabel = new Label(0, 3, "Ana Johnson", cellFormat); - sheet.addCell(cellLabel); - cellNumber = new Number(1, 3, 30, cellFormat); - sheet.addCell(cellNumber); - - workbook.write(); - } finally { - if (workbook != null) { - workbook.close(); - } - } - - } -} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java b/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java new file mode 100644 index 0000000000..409829bc35 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java @@ -0,0 +1,57 @@ +package com.baeldung.excel; + +public class MyCell { + private String content; + private String textColor; + private String bgColor; + private String textSize; + private String textWeight; + + public MyCell() { + } + + public MyCell(String content) { + this.content = content; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getTextColor() { + return textColor; + } + + public void setTextColor(String textColor) { + this.textColor = textColor; + } + + public String getBgColor() { + return bgColor; + } + + public void setBgColor(String bgColor) { + this.bgColor = bgColor; + } + + public String getTextSize() { + return textSize; + } + + public void setTextSize(String textSize) { + this.textSize = textSize; + } + + public String getTextWeight() { + return textWeight; + } + + public void setTextWeight(String textWeight) { + this.textWeight = textWeight; + } + +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 9578303554..11be08a79d 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -108,11 +108,6 @@ public class WebConfig extends WebMvcConfigurerAdapter { configurer.setUrlPathHelper(urlPathHelper); } - @Bean - public JExcelHelper jExcelHelper() { - return new JExcelHelper(); - } - @Bean public ExcelPOIHelper excelPOIHelper() { return new ExcelPOIHelper(); diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java index 810282dd65..f76f7441a5 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java @@ -10,20 +10,15 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import com.baeldung.excel.*; -import jxl.read.biff.BiffException; import java.util.Map; -import java.util.ArrayList; +import java.util.List; import javax.annotation.Resource; -import jxl.write.WriteException; @Controller public class ExcelController { private String fileLocation; - @Resource(name = "jExcelHelper") - private JExcelHelper jExcelHelper; - @Resource(name = "excelPOIHelper") private ExcelPOIHelper excelPOIHelper; @@ -45,36 +40,19 @@ public class ExcelController { } f.flush(); f.close(); - System.out.println(fileLocation); model.addAttribute("message", "File: " + file.getOriginalFilename() + " has been uploaded successfully!"); return "excel"; } - @RequestMapping(method = RequestMethod.GET, value = "/readJExcel") - public String readJExcel(Model model) throws IOException, BiffException { - - if (fileLocation != null) { - if (fileLocation.endsWith(".xls")) { - Map> data = jExcelHelper.readJExcel(fileLocation); - model.addAttribute("data", data); - } else { - model.addAttribute("message", "Not a valid .xls file!"); - } - } else { - model.addAttribute("message", "File missing! Please upload an excel file."); - } - return "excel"; - } - @RequestMapping(method = RequestMethod.GET, value = "/readPOI") public String readPOI(Model model) throws IOException { if (fileLocation != null) { - if (fileLocation.endsWith(".xlsx")) { - Map> data = excelPOIHelper.readExcel(fileLocation); + if (fileLocation.endsWith(".xlsx") || fileLocation.endsWith(".xls")) { + Map> data = excelPOIHelper.readExcel(fileLocation); model.addAttribute("data", data); } else { - model.addAttribute("message", "Not a valid .xlsx file!"); + model.addAttribute("message", "Not a valid excel file!"); } } else { model.addAttribute("message", "File missing! Please upload an excel file."); @@ -82,24 +60,4 @@ public class ExcelController { return "excel"; } - @RequestMapping(method = RequestMethod.POST, value = "/writeJExcel") - public String writeJExcel(Model model) throws IOException, BiffException, WriteException { - - jExcelHelper.writeJExcel(); - - model.addAttribute("message", "Write successful!"); - - return "excel"; - } - - @RequestMapping(method = RequestMethod.POST, value = "/writePOI") - public String writePOI(Model model) throws IOException { - - excelPOIHelper.writeExcel(); - - model.addAttribute("message", "Write successful!"); - - return "excel"; - } - } \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/excel.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/excel.jsp index b50687df15..bcb5a31371 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/excel.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/excel.jsp @@ -1,6 +1,6 @@ <%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + pageEncoding="ISO-8859-1"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> @@ -8,49 +8,43 @@ Excel Processing - - - - - - + + + -
- - -
-
-${message } -

-
- -
-

-Read file using JExcel     -Read file using Apache POI -

+
+ + +
+
+
+ +
+
${message } +
+
-File content: - - - - - - - - - -
${cell}
-
-

-
- -
-
-
- -
+
+ +
+
+
+ + + + + + + + + + +
+ ${cell.content} +
+
- \ No newline at end of file From 6c282a742ce71e04513f1a2c6d560754a7acd854 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 18 Feb 2017 07:31:10 +0100 Subject: [PATCH 05/23] BAEL-639: Fixing failing test --- .../DivisibilityTest.java | 4 +- .../MyParameterisedUnitTest.java | 28 +---- .../StringCaseTest.java | 2 +- .../SuiteTest.java | 2 +- .../SummationServiceTest.java | 9 +- .../src/test/resources/parameterised_test.xml | 10 -- core-java/src/test/resources/test_group.xml | 13 --- core-java/src/test/resources/test_suite.xml | 9 -- pom.xml | 1 + testng/pom.xml | 109 ++++++++++++++++++ .../java/baeldung/com}/DependentTests.java | 10 +- .../baeldung/com/ParametrizedTestNGTest.java | 36 ++---- .../java/baeldung/com}/RegistrationTest.java | 2 +- .../test/java/baeldung/com}/SignInTest.java | 2 +- .../baeldung/com/SummationServiceTest.java | 49 ++++---- .../src/test/java/baeldung/com/TestGroup.java | 44 +++++++ .../test/java/baeldung/com}/TimeOutTest.java | 6 +- testng/src/test/resources/logback.xml | 14 +++ .../src/test/resources/parameterised_test.xml | 17 +++ testng/src/test/resources/test_group.xml | 13 +++ testng/src/test/resources/test_suite.xml | 9 ++ 21 files changed, 265 insertions(+), 124 deletions(-) rename core-java/src/test/java/com/baeldung/{test/comparison => junit4vstestng}/DivisibilityTest.java (74%) rename core-java/src/test/java/com/baeldung/{test/comparison => junit4vstestng}/MyParameterisedUnitTest.java (59%) rename core-java/src/test/java/com/baeldung/{test/comparison => junit4vstestng}/StringCaseTest.java (90%) rename core-java/src/test/java/com/baeldung/{test/comparison => junit4vstestng}/SuiteTest.java (83%) rename core-java/src/test/java/com/baeldung/{test/comparison => junit4vstestng}/SummationServiceTest.java (94%) delete mode 100644 core-java/src/test/resources/parameterised_test.xml delete mode 100644 core-java/src/test/resources/test_group.xml delete mode 100644 core-java/src/test/resources/test_suite.xml create mode 100644 testng/pom.xml rename {core-java/src/test/java/com/baeldung/test/comparison => testng/src/test/java/baeldung/com}/DependentTests.java (82%) rename core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java => testng/src/test/java/baeldung/com/ParametrizedTestNGTest.java (51%) rename {core-java/src/test/java/com/baeldung/test/comparison => testng/src/test/java/baeldung/com}/RegistrationTest.java (78%) rename {core-java/src/test/java/com/baeldung/test/comparison => testng/src/test/java/baeldung/com}/SignInTest.java (78%) rename core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java => testng/src/test/java/baeldung/com/SummationServiceTest.java (79%) create mode 100644 testng/src/test/java/baeldung/com/TestGroup.java rename {core-java/src/test/java/com/baeldung/test/comparison => testng/src/test/java/baeldung/com}/TimeOutTest.java (70%) create mode 100644 testng/src/test/resources/logback.xml create mode 100644 testng/src/test/resources/parameterised_test.xml create mode 100644 testng/src/test/resources/test_group.xml create mode 100644 testng/src/test/resources/test_suite.xml diff --git a/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/DivisibilityTest.java similarity index 74% rename from core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/DivisibilityTest.java index 9ae13f5934..dec7dbe6aa 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/DivisibilityTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/DivisibilityTest.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package com.baeldung.junit4vstestng; import static org.junit.Assert.assertEquals; @@ -15,7 +15,7 @@ public class DivisibilityTest { } @Test - public void givenNumber_whenDivisiblebyTwo_thenCorrect() { + public void givenNumber_whenDivisibleByTwo_thenCorrect() { assertEquals(number % 2, 0); } } diff --git a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/MyParameterisedUnitTest.java similarity index 59% rename from core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/MyParameterisedUnitTest.java index 3372bbb577..95f9274af3 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/MyParameterisedUnitTest.java @@ -1,7 +1,4 @@ -package com.baeldung.test.comparison; - -import java.util.Arrays; -import java.util.Collection; +package com.baeldung.junit4vstestng; import org.junit.Assert; import org.junit.Before; @@ -10,16 +7,13 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import java.util.Arrays; +import java.util.Collection; + @RunWith(value = Parameterized.class) public class MyParameterisedUnitTest { private String name; - private NameCheck nameCheck; - - @Before - public void initialSetup() { - nameCheck = new NameCheck(); - } public MyParameterisedUnitTest(String myName) { this.name = myName; @@ -27,23 +21,13 @@ public class MyParameterisedUnitTest { @Parameters public static Collection data() { - Object[][] data = new Object[][] { { "Peter" }, { "Sam" }, { "Tim" }, { "Lucy" } }; + Object[][] data = new Object[][]{{"Peter"}, {"Sam"}, {"Tim"}, {"Lucy"}}; return Arrays.asList(data); } @Test public void givenName_whenValidLength_thenTrue() { - boolean valid = nameCheck.nameCheck(name); + boolean valid = name.length() > 0; Assert.assertEquals(valid, true); } } - -class NameCheck { - - public boolean nameCheck(String name) { - if (name.length() > 0) - return true; - return false; - } - -} diff --git a/core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/StringCaseTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/StringCaseTest.java index b4226b82e7..520017e4c1 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/StringCaseTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/StringCaseTest.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package com.baeldung.junit4vstestng; import static org.junit.Assert.assertEquals; diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java similarity index 83% rename from core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java index a30e5d312a..3d6d6cbbfb 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/SuiteTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package com.baeldung.junit4vstestng; import org.junit.runner.RunWith; import org.junit.runners.Suite; diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceTest.java similarity index 94% rename from core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceTest.java index b76a87c0fe..7d1bf3b7af 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceTest.java @@ -1,8 +1,4 @@ -package com.baeldung.test.comparison; - -import java.security.Security; -import java.util.ArrayList; -import java.util.List; +package com.baeldung.junit4vstestng; import org.junit.After; import org.junit.AfterClass; @@ -12,6 +8,9 @@ import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; +import java.util.ArrayList; +import java.util.List; + public class SummationServiceTest { private static List numbers; diff --git a/core-java/src/test/resources/parameterised_test.xml b/core-java/src/test/resources/parameterised_test.xml deleted file mode 100644 index 69a2c60460..0000000000 --- a/core-java/src/test/resources/parameterised_test.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/core-java/src/test/resources/test_group.xml b/core-java/src/test/resources/test_group.xml deleted file mode 100644 index 0c9a6c73df..0000000000 --- a/core-java/src/test/resources/test_group.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/core-java/src/test/resources/test_suite.xml b/core-java/src/test/resources/test_suite.xml deleted file mode 100644 index 36305aa5fc..0000000000 --- a/core-java/src/test/resources/test_suite.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index ecb07e987b..eb89b9cbaa 100644 --- a/pom.xml +++ b/pom.xml @@ -194,6 +194,7 @@ struts2 apache-velocity + testng diff --git a/testng/pom.xml b/testng/pom.xml new file mode 100644 index 0000000000..02f51d4d99 --- /dev/null +++ b/testng/pom.xml @@ -0,0 +1,109 @@ + + + 4.0.0 + com.baeldung + testng + 0.1.0-SNAPSHOT + jar + testng + + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + + + org.testng + testng + ${testng.version} + test + + + + + + testng + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + + true + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + + + + + + 1.7.21 + 1.1.7 + + + 6.10 + + + 3.6.0 + 2.19.1 + + + + + \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java b/testng/src/test/java/baeldung/com/DependentTests.java similarity index 82% rename from core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java rename to testng/src/test/java/baeldung/com/DependentTests.java index 3ef4949067..ab593e0439 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/DependentTests.java +++ b/testng/src/test/java/baeldung/com/DependentTests.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package baeldung.com; import org.testng.Assert; import org.testng.annotations.BeforeClass; @@ -6,9 +6,9 @@ import org.testng.annotations.Test; public class DependentTests { + private String validEmail = "abc@qwe.com"; private EmailValidator emailValidator; private LoginValidator loginValidator; - private String validEmail = "abc@qwe.com"; @BeforeClass public void setup() { @@ -23,7 +23,7 @@ public class DependentTests { } @Test(dependsOnMethods = { "givenEmail_ifValid_thenTrue" }) - public void givenValidEmail_whenLoggedin_thenTrue() { + public void givenValidEmail_whenLoggedIn_thenTrue() { boolean valid = loginValidator.validate(); Assert.assertEquals(valid, true); } @@ -31,7 +31,7 @@ public class DependentTests { class EmailValidator { - public boolean validate(String validEmail) { + boolean validate(String validEmail) { return true; } @@ -39,7 +39,7 @@ class EmailValidator { class LoginValidator { - public boolean validate() { + boolean validate() { return true; } diff --git a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java b/testng/src/test/java/baeldung/com/ParametrizedTestNGTest.java similarity index 51% rename from core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java rename to testng/src/test/java/baeldung/com/ParametrizedTestNGTest.java index 4096c3fb6f..e4f3aacf5b 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/MyParameterisedUnitTestNg.java +++ b/testng/src/test/java/baeldung/com/ParametrizedTestNGTest.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package baeldung.com; import org.testng.Assert; import org.testng.annotations.BeforeClass; @@ -6,29 +6,22 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; -public class MyParameterisedUnitTestNg { +public class ParametrizedTestNGTest { - private PrimeNumberCheck primeNumberChecker; - - @BeforeClass - public void intialSetup() { - primeNumberChecker = new PrimeNumberCheck(); - } - - @Test(enabled = false) - @Parameters({ "num", "expectedResult" }) - public void givenNumber_ifPrime_thenCorrect(int number, boolean expectedResult) { - Assert.assertEquals(expectedResult, primeNumberChecker.validate(number)); + @Test + @Parameters({ "name", "expectedResult" }) + public void givenNumber_ifPrime_thenCorrect(String name, boolean expectedResult) { + Assert.assertEquals(expectedResult, name.length() > 0); } @DataProvider(name = "test1") public static Object[][] primeNumbers() { - return new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false }, { 23, true } }; + return new Object[][] { { "Peter", true }, { "Sam", true }, { "Tim", true }, { "Lucy", true } }; } @Test(dataProvider = "test1") - public void givenNumber_whenPrime_thenCorrect(Integer inputNumber, Boolean expectedResult) { - Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); + public void givenNumber_whenPrime_thenCorrect(String name, boolean expectedResult) { + Assert.assertEquals(expectedResult, name.length() > 0); } @Test(dataProvider = "myDataProvider") @@ -47,17 +40,6 @@ public class MyParameterisedUnitTestNg { } -class PrimeNumberCheck { - - public Object validate(int number) { - for (int i = 2; i < number; i++) { - if (number % i == 0) - return false; - } - return true; - } - -} class User { private String name; diff --git a/core-java/src/test/java/com/baeldung/test/comparison/RegistrationTest.java b/testng/src/test/java/baeldung/com/RegistrationTest.java similarity index 78% rename from core-java/src/test/java/com/baeldung/test/comparison/RegistrationTest.java rename to testng/src/test/java/baeldung/com/RegistrationTest.java index 86836425a9..7cb17c9cb8 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/RegistrationTest.java +++ b/testng/src/test/java/baeldung/com/RegistrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package baeldung.com; import org.testng.annotations.Test; diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SignInTest.java b/testng/src/test/java/baeldung/com/SignInTest.java similarity index 78% rename from core-java/src/test/java/com/baeldung/test/comparison/SignInTest.java rename to testng/src/test/java/baeldung/com/SignInTest.java index 9669f60b6b..4884154345 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/SignInTest.java +++ b/testng/src/test/java/baeldung/com/SignInTest.java @@ -1,4 +1,4 @@ -package com.baeldung.test.comparison; +package baeldung.com; import org.testng.annotations.Test; diff --git a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java b/testng/src/test/java/baeldung/com/SummationServiceTest.java similarity index 79% rename from core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java rename to testng/src/test/java/baeldung/com/SummationServiceTest.java index fb02f28d06..471d7a7c8a 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/SummationServiceTestTestNg.java +++ b/testng/src/test/java/baeldung/com/SummationServiceTest.java @@ -1,19 +1,13 @@ -package com.baeldung.test.comparison; +package baeldung.com; + +import org.testng.Assert; +import org.testng.TestNG; +import org.testng.annotations.*; import java.util.ArrayList; import java.util.List; -import org.testng.Assert; -import org.testng.TestNG; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeGroups; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class SummationServiceTestTestNg extends TestNG { +public class SummationServiceTest extends TestNG { private List numbers; @@ -29,14 +23,16 @@ public class SummationServiceTestTestNg extends TestNG { numbers = null; } - @BeforeMethod - public void runBeforeEachTest() { - testCount++; + @BeforeSuite(groups = "regression") + public void runBeforeRegressionSuite() { + numbers = new ArrayList<>(); + numbers.add(-11); + numbers.add(2); } - @AfterMethod - public void runAfterEachTest() { - + @AfterSuite(groups = "regression") + public void runAfterRegressionSuite() { + numbers = null; } @BeforeGroups("negative_tests") @@ -62,6 +58,17 @@ public class SummationServiceTestTestNg extends TestNG { numbers.clear(); } + @BeforeMethod + public void runBeforeEachTest() { + testCount++; + } + + @AfterMethod + public void runAfterEachTest() { + + } + + @Test(groups = "positive_tests", enabled = false) public void givenNumbers_sumEquals_thenCorrect() { int sum = numbers.stream().reduce(0, Integer::sum); @@ -78,12 +85,6 @@ public class SummationServiceTestTestNg extends TestNG { public void givenNegativeNumber_sumLessthanZero_thenCorrect() { int sum = numbers.stream().reduce(0, Integer::sum); Assert.assertTrue(sum < 0); - ; - } - - @Test(groups = "sanity") - public void givenNumbers_doSum() { - } @Test(expectedExceptions = ArithmeticException.class) diff --git a/testng/src/test/java/baeldung/com/TestGroup.java b/testng/src/test/java/baeldung/com/TestGroup.java new file mode 100644 index 0000000000..08bb5c996e --- /dev/null +++ b/testng/src/test/java/baeldung/com/TestGroup.java @@ -0,0 +1,44 @@ +package baeldung.com; + +import org.testng.annotations.AfterGroups; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; + +public class TestGroup { + + @BeforeGroups("database") + public void setupDB() { + System.out.println("setupDB()"); + } + + @AfterGroups("database") + public void cleanDB() { + System.out.println("cleanDB()"); + } + + @Test(groups= "selenium-test") + public void runSelenium() { + System.out.println("runSelenium()"); + } + + @Test(groups= "selenium-test") + public void runSelenium1() { + System.out.println("runSelenium()1"); + } + + @Test(groups = "database") + public void testConnectOracle() { + System.out.println("testConnectOracle()"); + } + + @Test(groups = "database") + public void testConnectMsSQL() { + System.out.println("testConnectMsSQL"); + } + + @Test(dependsOnGroups = {"database","selenium-test"}) + public void runFinal() { + System.out.println("runFinal"); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java b/testng/src/test/java/baeldung/com/TimeOutTest.java similarity index 70% rename from core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java rename to testng/src/test/java/baeldung/com/TimeOutTest.java index 6e06132009..d54a914e08 100644 --- a/core-java/src/test/java/com/baeldung/test/comparison/TimeOutTest.java +++ b/testng/src/test/java/baeldung/com/TimeOutTest.java @@ -1,11 +1,11 @@ -package com.baeldung.test.comparison; +package baeldung.com; import org.testng.annotations.Test; public class TimeOutTest { + @Test(timeOut = 1000, enabled = false) public void givenExecution_takeMoreTime_thenFail() { - while (true) - ; + while (true) ; } } diff --git a/testng/src/test/resources/logback.xml b/testng/src/test/resources/logback.xml new file mode 100644 index 0000000000..e9ae1894a6 --- /dev/null +++ b/testng/src/test/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/parameterised_test.xml b/testng/src/test/resources/parameterised_test.xml new file mode 100644 index 0000000000..2381ba67d0 --- /dev/null +++ b/testng/src/test/resources/parameterised_test.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/test_group.xml b/testng/src/test/resources/test_group.xml new file mode 100644 index 0000000000..d636a4174d --- /dev/null +++ b/testng/src/test/resources/test_group.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/test_suite.xml b/testng/src/test/resources/test_suite.xml new file mode 100644 index 0000000000..201ed3f645 --- /dev/null +++ b/testng/src/test/resources/test_suite.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file From 2ee0a8a7a13145df12259429012f9c57b5509509 Mon Sep 17 00:00:00 2001 From: tschiman Date: Sat, 11 Feb 2017 19:52:16 +0100 Subject: [PATCH 06/23] BAEL-684 Adding spring JPA to resource servers --- .../gateway/GatewayApplicationLiveTest.java | 69 ------ .../bootstrap/gateway/IntegrationTest.java | 201 ++++++++++++++++++ .../spring-cloud-bootstrap/svc-book/pom.xml | 11 + .../svcbook/BookServiceApplication.java | 24 --- .../bootstrap/svcbook/SecurityConfig.java | 8 +- .../bootstrap/svcbook/{ => book}/Book.java | 19 +- .../svcbook/book/BookController.java | 40 ++++ .../svcbook/book/BookNotFoundException.java | 11 + .../svcbook/book/BookRepository.java | 6 + .../bootstrap/svcbook/book/BookService.java | 55 +++++ .../spring-cloud-bootstrap/svc-rating/pom.xml | 11 + .../svcrating/RatingServiceApplication.java | 28 --- .../bootstrap/svcrating/SecurityConfig.java | 8 +- .../svcrating/{ => rating}/Rating.java | 14 +- .../svcrating/rating/RatingController.java | 38 ++++ .../rating/RatingNotFoundException.java | 11 + .../svcrating/rating/RatingRepository.java | 9 + .../svcrating/rating/RatingService.java | 57 +++++ 18 files changed, 487 insertions(+), 133 deletions(-) delete mode 100644 spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java create mode 100644 spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationTest.java rename spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/{ => book}/Book.java (57%) create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java rename spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/{ => rating}/Rating.java (62%) create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java create mode 100644 spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java deleted file mode 100644 index aa39232bb2..0000000000 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.spring.cloud.bootstrap.gateway; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.*; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; - -public class GatewayApplicationLiveTest { - - @Test - public void testAccess() throws Exception { - TestRestTemplate testRestTemplate = new TestRestTemplate(); - String testUrl = "http://localhost:8080"; - - ResponseEntity response = testRestTemplate.getForEntity(testUrl + "/book-service/books", String.class); - Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertNotNull(response.getBody()); - - //try the protected resource and confirm the redirect to login - response = testRestTemplate.getForEntity(testUrl + "/book-service/books/1", String.class); - Assert.assertEquals(HttpStatus.FOUND, response.getStatusCode()); - Assert.assertEquals("http://localhost:8080/login", response.getHeaders().get("Location").get(0)); - - //login as user/password - MultiValueMap form = new LinkedMultiValueMap<>(); - form.add("username", "user"); - form.add("password", "password"); - response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); - - //extract the session from the cookie and propagate it to the next request - String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; - HttpHeaders headers = new HttpHeaders(); - headers.add("Cookie", sessionCookie); - HttpEntity httpEntity = new HttpEntity<>(headers); - - //request the protected resource - response = testRestTemplate.exchange(testUrl + "/book-service/books/1", HttpMethod.GET, httpEntity, String.class); - Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertNotNull(response.getBody()); - - //request the admin protected resource to determine it is still protected - response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class); - Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); - - //login as the admin - form.clear(); - form.add("username", "admin"); - form.add("password", "admin"); - response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); - - //extract the session from the cookie and propagate it to the next request - sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; - headers = new HttpHeaders(); - headers.add("Cookie", sessionCookie); - httpEntity = new HttpEntity<>(headers); - - //request the protected resource - response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class); - Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - Assert.assertNotNull(response.getBody()); - - //request the discovery resources as the admin - response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class); - Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); - } - -} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationTest.java new file mode 100644 index 0000000000..16057edc48 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationTest.java @@ -0,0 +1,201 @@ +package com.baeldung.spring.cloud.bootstrap.gateway; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.apache.http.entity.ContentType; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +public class IntegrationTest { + + private TestRestTemplate testRestTemplate = new TestRestTemplate(); + private String testUrl = "http://localhost:8080"; + + @Test + public void testAccess() throws Exception { + ResponseEntity response = testRestTemplate.getForEntity(testUrl + "/book-service/books", String.class); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assert.assertNotNull(response.getBody()); + + //try the protected resource and confirm the redirect to login + response = testRestTemplate.getForEntity(testUrl + "/book-service/books/1", String.class); + Assert.assertEquals(HttpStatus.FOUND, response.getStatusCode()); + Assert.assertEquals("http://localhost:8080/login", response.getHeaders().get("Location").get(0)); + + //login as user/password + MultiValueMap form = new LinkedMultiValueMap<>(); + form.add("username", "user"); + form.add("password", "password"); + response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); + + //extract the session from the cookie and propagate it to the next request + String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + HttpHeaders headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + HttpEntity httpEntity = new HttpEntity<>(headers); + + addBook(); + + //request the protected resource + response = testRestTemplate.exchange(testUrl + "/book-service/books/1", HttpMethod.GET, httpEntity, String.class); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assert.assertNotNull(response.getBody()); + + addRatings(); + + //request the admin protected resource to determine it is still protected + response = testRestTemplate.exchange(testUrl + "/rating-service/ratings", HttpMethod.GET, httpEntity, String.class); + Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + + //login as the admin + form.clear(); + form.add("username", "admin"); + form.add("password", "admin"); + response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); + + //extract the session from the cookie and propagate it to the next request + sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + httpEntity = new HttpEntity<>(headers); + + //request the protected resource + response = testRestTemplate.exchange(testUrl + "/rating-service/ratings", HttpMethod.GET, httpEntity, String.class); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + Assert.assertNotNull(response.getBody()); + + //request the discovery resources as the admin + response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + } + + private void addRatings() { + //login as user/password + MultiValueMap form = new LinkedMultiValueMap<>(); + form.add("username", "user"); + form.add("password", "password"); + ResponseEntity response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); + + //extract the session from the cookie and propagate it to the next request + String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + HttpHeaders headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + headers.add("ContentType", ContentType.APPLICATION_JSON.getMimeType()); + Rating rating = new Rating(1L, 4); + + HttpEntity httpEntity = new HttpEntity<>(rating, headers); + + //request the protected resource + ResponseEntity bookResponse = testRestTemplate.postForEntity(testUrl + "/rating-service/ratings", httpEntity, Rating.class); + Assert.assertEquals(HttpStatus.OK, bookResponse.getStatusCode()); + Assert.assertEquals(rating.getBookId(), bookResponse.getBody().getBookId()); + Assert.assertEquals(rating.getStars(), bookResponse.getBody().getStars()); + } + + private void addBook(){ + //login as user/password + MultiValueMap form = new LinkedMultiValueMap<>(); + form.add("username", "admin"); + form.add("password", "admin"); + ResponseEntity response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class); + + //extract the session from the cookie and propagate it to the next request + String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0]; + HttpHeaders headers = new HttpHeaders(); + headers.add("Cookie", sessionCookie); + headers.add("ContentType", ContentType.APPLICATION_JSON.getMimeType()); + Book book = new Book("Baeldung", "How to spring cloud"); + + HttpEntity httpEntity = new HttpEntity<>(book, headers); + + //request the protected resource + ResponseEntity bookResponse = testRestTemplate.postForEntity(testUrl + "/book-service/books", httpEntity, Book.class); + Assert.assertEquals(HttpStatus.OK, bookResponse.getStatusCode()); + Assert.assertEquals(book.getAuthor(), bookResponse.getBody().getAuthor()); + Assert.assertEquals(book.getTitle(), bookResponse.getBody().getTitle()); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Book { + + private Long id; + private String author; + private String title; + + public Book() { + } + + public Book(String author, String title) { + this.author = author; + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Rating { + private Long id; + private Long bookId; + private int stars; + + public Rating() { + } + + public Rating(Long bookId, int stars) { + this.bookId = bookId; + this.stars = stars; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getBookId() { + return bookId; + } + + public void setBookId(Long bookId) { + this.bookId = bookId; + } + + public int getStars() { + return stars; + } + + public void setStars(int stars) { + this.stars = stars; + } + } + + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml index 9a99054ed5..c351c444f6 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml @@ -42,6 +42,17 @@ spring-boot-starter-data-redis + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime + + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java index 25ad2a83b2..c5499cd924 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java @@ -3,35 +3,11 @@ package com.baeldung.spring.cloud.bootstrap.svcbook; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Arrays; -import java.util.List; @SpringBootApplication @EnableEurekaClient -@RestController -@RequestMapping("/books") public class BookServiceApplication { public static void main(String[] args) { SpringApplication.run(BookServiceApplication.class, args); } - - private List bookList = Arrays.asList( - new Book(1L, "Baeldung goes to the market", "Tim Schimandle"), - new Book(2L, "Baeldung goes to the park", "Slavisa") - ); - - @GetMapping("") - public List findAllBooks() { - return bookList; - } - - @GetMapping("/{bookId}") - public Book findBook(@PathVariable Long bookId) { - return bookList.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null); - } } diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java index 300b4d7c5a..6aa996c575 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java @@ -2,6 +2,7 @@ package com.baeldung.spring.cloud.bootstrap.svcbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -22,8 +23,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http.httpBasic() .disable() .authorizeRequests() - .antMatchers("/books").permitAll() - .antMatchers("/books/*").hasAnyRole("USER", "ADMIN") + .antMatchers(HttpMethod.GET, "/books").permitAll() + .antMatchers(HttpMethod.GET, "/books/*").permitAll() + .antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN") + .antMatchers(HttpMethod.PATCH, "/books/*").hasRole("ADMIN") + .antMatchers(HttpMethod.DELETE, "/books/*").hasRole("ADMIN") .anyRequest().authenticated() .and() .csrf() diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java similarity index 57% rename from spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java rename to spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java index e652437454..33ea8dcb81 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java @@ -1,16 +1,21 @@ -package com.baeldung.spring.cloud.bootstrap.svcbook; +package com.baeldung.spring.cloud.bootstrap.svcbook.book; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +@JsonIgnoreProperties(ignoreUnknown = true) public class Book { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String author; private String title; - public Book(Long id, String title, String author) { - this.id = id; - this.author = author; - this.title = title; - } - public Book() { } diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java new file mode 100644 index 0000000000..d00f114b8c --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookController.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook.book; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/books") +public class BookController { + + @Autowired + private BookService bookService; + + @GetMapping("") + public List findAllBooks() { + return bookService.findAllBooks(); + } + + @GetMapping("/{bookId}") + public Book findBook(@PathVariable Long bookId) { + return bookService.findBookById(bookId); + } + + @PostMapping("") + public Book createBook(@RequestBody Book book) { + return bookService.createBook(book); + } + + @DeleteMapping("/{bookId}") + public void deleteBook(@PathVariable Long bookId) { + bookService.deleteBook(bookId); + } + + @PatchMapping("/{bookId") + public Book updateBook(@RequestBody Map updates, @PathVariable Long bookId) { + return bookService.updateBook(updates, bookId); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java new file mode 100644 index 0000000000..f0a4797387 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookNotFoundException.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook.book; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.NOT_FOUND) +class BookNotFoundException extends RuntimeException { + BookNotFoundException(String message) { + super(message); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java new file mode 100644 index 0000000000..66fd3880c5 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook.book; + +import org.springframework.data.jpa.repository.JpaRepository; + +interface BookRepository extends JpaRepository{ +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java new file mode 100644 index 0000000000..cfcbf15757 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/BookService.java @@ -0,0 +1,55 @@ +package com.baeldung.spring.cloud.bootstrap.svcbook.book; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +@Transactional(readOnly = true) +public class BookService { + + @Autowired + private BookRepository bookRepository; + + public List findAllBooks() { + return bookRepository.findAll(); + } + + public Book findBookById(Long bookId) { + return Optional.ofNullable(bookRepository.findOne(bookId)) + .orElseThrow(() -> new BookNotFoundException("Book not found. ID: " + bookId)); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Book createBook(Book book) { + Book newBook = new Book(); + newBook.setTitle(book.getTitle()); + newBook.setAuthor(book.getAuthor()); + return bookRepository.save(newBook); + } + + @Transactional(propagation = Propagation.REQUIRED) + public void deleteBook(Long bookId) { + bookRepository.delete(bookId); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Book updateBook(Map updates, Long bookId) { + Book book = findBookById(bookId); + updates.keySet().forEach(key -> { + switch (key) { + case "author": + book.setAuthor(updates.get(key)); + break; + case "title": + book.setTitle(updates.get(key)); + } + }); + return bookRepository.save(book); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml index 35da8beba8..2285286812 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml @@ -42,6 +42,17 @@ spring-boot-starter-data-redis + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime + + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java index 11fb5f06b6..61074e0bcc 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java @@ -3,39 +3,11 @@ package com.baeldung.spring.cloud.bootstrap.svcrating; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; @SpringBootApplication @EnableEurekaClient -@RestController -@RequestMapping("/ratings") public class RatingServiceApplication { public static void main(String[] args) { SpringApplication.run(RatingServiceApplication.class, args); } - - private List ratingList = Arrays.asList( - new Rating(1L, 1L, 2), - new Rating(2L, 1L, 3), - new Rating(3L, 2L, 4), - new Rating(4L, 2L, 5) - ); - - @GetMapping("") - public List findRatingsByBookId(@RequestParam Long bookId) { - return bookId == null || bookId.equals(0L) ? Collections.EMPTY_LIST : ratingList.stream().filter(r -> r.getBookId().equals(bookId)).collect(Collectors.toList()); - } - - @GetMapping("/all") - public List findAllRatings() { - return ratingList; - } } \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java index 371dc810d5..171fbba7af 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java @@ -2,6 +2,7 @@ package com.baeldung.spring.cloud.bootstrap.svcrating; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -22,8 +23,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http.httpBasic() .disable() .authorizeRequests() - .antMatchers("/ratings").hasRole("USER") - .antMatchers("/ratings/all").hasRole("ADMIN") + .regexMatchers("^/ratings\\?bookId.*$").authenticated() + .antMatchers(HttpMethod.POST,"/ratings").authenticated() + .antMatchers(HttpMethod.PATCH,"/ratings/*").hasRole("ADMIN") + .antMatchers(HttpMethod.DELETE,"/ratings/*").hasRole("ADMIN") + .antMatchers(HttpMethod.GET,"/ratings").hasRole("ADMIN") .anyRequest().authenticated() .and() .csrf() diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java similarity index 62% rename from spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java rename to spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java index 5dd3572098..ae44f9ae2e 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/Rating.java +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java @@ -1,6 +1,18 @@ -package com.baeldung.spring.cloud.bootstrap.svcrating; +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +@JsonIgnoreProperties(ignoreUnknown = true) public class Rating { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long bookId; private int stars; diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java new file mode 100644 index 0000000000..83452ad747 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingController.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/ratings") +public class RatingController { + + @Autowired + private RatingService ratingService; + + @GetMapping("") + public List findRatingsByBookId(@RequestParam(required = false, defaultValue = "0") Long bookId) { + if (bookId.equals(0L)) { + return ratingService.findAllRatings(); + } + return ratingService.findRatingsByBookId(bookId); + } + + @PostMapping("") + public Rating createRating(@RequestBody Rating rating) { + return ratingService.createRating(rating); + } + + @DeleteMapping("/{ratingId}") + public void deleteRating(@PathVariable Long ratingId) { + ratingService.deleteRating(ratingId); + } + + @PatchMapping("/{ratingId") + public Rating updateRating(@RequestBody Map updates, @PathVariable Long ratingId) { + return ratingService.updateRating(updates, ratingId); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java new file mode 100644 index 0000000000..473d636a71 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingNotFoundException.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.NOT_FOUND) +class RatingNotFoundException extends RuntimeException { + RatingNotFoundException(String message) { + super(message); + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java new file mode 100644 index 0000000000..08d781b5a3 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; + +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +interface RatingRepository extends JpaRepository{ + List findRatingsByBookId(Long bookId); +} diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java new file mode 100644 index 0000000000..a2360b7be5 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/RatingService.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.cloud.bootstrap.svcrating.rating; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +@Transactional(readOnly = true) +public class RatingService { + + @Autowired + private RatingRepository ratingRepository; + + public Rating findRatingById(Long ratingId) { + return Optional.ofNullable(ratingRepository.findOne(ratingId)) + .orElseThrow(() -> new RatingNotFoundException("Rating not found. ID: " + ratingId)); + } + + public List findRatingsByBookId(Long bookId) { + return ratingRepository.findRatingsByBookId(bookId); + } + + public List findAllRatings() { + return ratingRepository.findAll(); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Rating createRating(Rating rating) { + Rating newRating = new Rating(); + newRating.setBookId(rating.getBookId()); + newRating.setStars(rating.getStars()); + return ratingRepository.save(newRating); + } + + @Transactional(propagation = Propagation.REQUIRED) + public void deleteRating(Long ratingId) { + ratingRepository.delete(ratingId); + } + + @Transactional(propagation = Propagation.REQUIRED) + public Rating updateRating(Map updates, Long ratingId) { + Rating rating = findRatingById(ratingId); + updates.keySet().forEach(key -> { + switch (key) { + case "stars": + rating.setStars(Integer.parseInt(updates.get(key))); + break; + } + }); + return ratingRepository.save(rating); + } +} From f800e9dc4f32f118117c06362a61332e274cdf1e Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 18 Feb 2017 07:47:36 +0100 Subject: [PATCH 07/23] BAEL-684 - suffix testname to match surefire configuration --- .../gateway/{IntegrationTest.java => IntegrationLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/{IntegrationTest.java => IntegrationLiveTest.java} (99%) diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationLiveTest.java similarity index 99% rename from spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationTest.java rename to spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationLiveTest.java index 16057edc48..47a4b744eb 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationTest.java +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/IntegrationLiveTest.java @@ -9,7 +9,7 @@ import org.springframework.http.*; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -public class IntegrationTest { +public class IntegrationLiveTest { private TestRestTemplate testRestTemplate = new TestRestTemplate(); private String testUrl = "http://localhost:8080"; From 2bf21cbff37fb78efad08fea90a9d26ecbe141ca Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sat, 18 Feb 2017 08:31:42 +0100 Subject: [PATCH 08/23] Refactor ExcelPOIHelper to Stream API --- .../com/baeldung/excel/ExcelPOIHelper.java | 31 +++++++++---------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java b/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java index e3658e8f89..0519a8f3c7 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java +++ b/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java @@ -24,6 +24,7 @@ import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.List; +import java.util.stream.IntStream; public class ExcelPOIHelper { @@ -38,27 +39,23 @@ public class ExcelPOIHelper { data = readXSSFWorkbook(fis); } - int maxNrCols = 0; + int maxNrCols = data.values().stream() + .mapToInt(List::size) + .max() + .orElse(0); - for (List ls : data.values()) { - if (ls.size() > maxNrCols) { - maxNrCols = ls.size(); - } - } - - for (List ls : data.values()) { - if (ls.size() < maxNrCols) { - for (int i = ls.size(); i < maxNrCols; i++) { - ls.add(new MyCell("")); - } - } - } + data.values().stream() + .filter(ls -> ls.size() < maxNrCols) + .forEach(ls -> { + IntStream.range(ls.size(), maxNrCols) + .forEach(i -> ls.add(new MyCell(""))); + }); return data; } private String readCellContent(Cell cell) { - String content = ""; + String content; switch (cell.getCellTypeEnum()) { case STRING: content = cell.getStringCellValue(); @@ -91,7 +88,7 @@ public class ExcelPOIHelper { HSSFSheet sheet = workbook.getSheetAt(0); for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { HSSFRow row = sheet.getRow(i); - data.put(i, new ArrayList()); + data.put(i, new ArrayList<>()); if (row != null) { for (int j = 0; j < row.getLastCellNum(); j++) { HSSFCell cell = row.getCell(j); @@ -144,7 +141,7 @@ public class ExcelPOIHelper { for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { XSSFRow row = sheet.getRow(i); - data.put(i, new ArrayList()); + data.put(i, new ArrayList<>()); if (row != null) { for (int j = 0; j < row.getLastCellNum(); j++) { XSSFCell cell = row.getCell(j); From 51756367ce8b8d9db7e2898559bbcf642f870f7d Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sat, 18 Feb 2017 21:24:41 +0530 Subject: [PATCH 09/23] adding testcase for WebUtils and ServletRequestUtils (#1193) * rest with spark java * 4 * Update Application.java * indentation changes * spring @requestmapping shortcuts * removing spring requestmapping and pushing spring-mvc-java * Joining/Splitting Strings with Java and Stream API * adding more join/split functionality * changing package name * testcase change * adding webutils * adding testcase for WebUtils and ServletRequestUtils * adding testcase --- .../baeldung/utils/UtilsControllerTest.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 spring-boot/src/test/java/com/baeldung/utils/UtilsControllerTest.java diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerTest.java b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerTest.java new file mode 100644 index 0000000000..7aed45dbb0 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerTest.java @@ -0,0 +1,41 @@ +package com.baeldung.utils; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +import com.baeldung.utils.controller.UtilsController; + +public class UtilsControllerTest { + + @InjectMocks + private UtilsController utilsController; + + private MockMvc mockMvc; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) + .build(); + + } + + @Test + public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { + String param = "testparam"; + this.mockMvc.perform( + post("/setParam") + .param("param", param) + .sessionAttr("parameter", param)) + .andExpect(status().isOk()); + } + +} From 333953b204e473c06b7c86c72a164538e51f60e6 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Sat, 18 Feb 2017 22:56:41 +0100 Subject: [PATCH 10/23] BAEL-183 - refactoring and moving testng to dedicated module --- ...edUnitTest.java => ParametrizedTests.java} | 17 ++-- .../junit4vstestng/RegistrationTest.java | 15 ++++ .../baeldung/junit4vstestng/SignInTest.java | 14 ++++ .../baeldung/junit4vstestng/SuiteTest.java | 2 +- pom.xml | 3 +- testng/pom.xml | 6 ++ .../java/baeldung/com/DependentTests.java | 35 ++------- .../baeldung/com/ParametrizedTestNGTest.java | 63 --------------- .../java/baeldung/com/ParametrizedTests.java | 77 +++++++++++++++++++ .../java/baeldung/com/RegistrationTest.java | 7 +- .../test/java/baeldung/com/SignInTest.java | 8 +- .../baeldung/com/SummationServiceTest.java | 3 + .../src/test/resources/parameterised_test.xml | 17 ---- .../src/test/resources/parametrized_test.xml | 10 +++ testng/src/test/resources/test_group.xml | 2 +- testng/src/test/resources/test_setup.xml | 17 ++++ testng/src/test/resources/test_suite.xml | 2 +- 17 files changed, 172 insertions(+), 126 deletions(-) rename core-java/src/test/java/com/baeldung/junit4vstestng/{MyParameterisedUnitTest.java => ParametrizedTests.java} (53%) create mode 100644 core-java/src/test/java/com/baeldung/junit4vstestng/RegistrationTest.java create mode 100644 core-java/src/test/java/com/baeldung/junit4vstestng/SignInTest.java delete mode 100644 testng/src/test/java/baeldung/com/ParametrizedTestNGTest.java create mode 100644 testng/src/test/java/baeldung/com/ParametrizedTests.java delete mode 100644 testng/src/test/resources/parameterised_test.xml create mode 100644 testng/src/test/resources/parametrized_test.xml create mode 100644 testng/src/test/resources/test_setup.xml diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/MyParameterisedUnitTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/ParametrizedTests.java similarity index 53% rename from core-java/src/test/java/com/baeldung/junit4vstestng/MyParameterisedUnitTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/ParametrizedTests.java index 95f9274af3..e9a9c6a07a 100644 --- a/core-java/src/test/java/com/baeldung/junit4vstestng/MyParameterisedUnitTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/ParametrizedTests.java @@ -11,23 +11,24 @@ import java.util.Arrays; import java.util.Collection; @RunWith(value = Parameterized.class) -public class MyParameterisedUnitTest { +public class ParametrizedTests { - private String name; + private int value; + private boolean isEven; - public MyParameterisedUnitTest(String myName) { - this.name = myName; + public ParametrizedTests(int value, boolean isEven) { + this.value = value; + this.isEven = isEven; } @Parameters public static Collection data() { - Object[][] data = new Object[][]{{"Peter"}, {"Sam"}, {"Tim"}, {"Lucy"}}; + Object[][] data = new Object[][]{{1, false}, {2, true}, {4, true}}; return Arrays.asList(data); } @Test - public void givenName_whenValidLength_thenTrue() { - boolean valid = name.length() > 0; - Assert.assertEquals(valid, true); + public void givenParametrizedNumber_ifEvenCheckOK_thenCorrect() { + Assert.assertEquals(isEven, value % 2 == 0); } } diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/RegistrationTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/RegistrationTest.java new file mode 100644 index 0000000000..4aa1fa1a17 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/RegistrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.junit4vstestng; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class RegistrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationTest.class); + + @Test + public void whenCalledFromSuite_thanOK() { + LOGGER.info("Registration successful"); + } +} diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SignInTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SignInTest.java new file mode 100644 index 0000000000..bb908ff37e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SignInTest.java @@ -0,0 +1,14 @@ +package com.baeldung.junit4vstestng; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SignInTest { + private static final Logger LOGGER = LoggerFactory.getLogger(SignInTest.class); + + @Test + public void whenCalledFromSuite_thanOK() { + LOGGER.info("SignIn successful"); + } +} diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java index 3d6d6cbbfb..effd7fa10a 100644 --- a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java @@ -4,7 +4,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses({ StringCaseTest.class, DivisibilityTest.class }) +@Suite.SuiteClasses({ RegistrationTest.class, SignInTest.class }) public class SuiteTest { } diff --git a/pom.xml b/pom.xml index eb89b9cbaa..82df776044 100644 --- a/pom.xml +++ b/pom.xml @@ -182,6 +182,7 @@ spring-reactor testing + testng video-tutorials @@ -194,8 +195,6 @@ struts2 apache-velocity - testng - diff --git a/testng/pom.xml b/testng/pom.xml index 02f51d4d99..272b1d316d 100644 --- a/testng/pom.xml +++ b/testng/pom.xml @@ -43,6 +43,12 @@ true + + + src/main/resources + true + + diff --git a/testng/src/test/java/baeldung/com/DependentTests.java b/testng/src/test/java/baeldung/com/DependentTests.java index ab593e0439..b60f8a6c0d 100644 --- a/testng/src/test/java/baeldung/com/DependentTests.java +++ b/testng/src/test/java/baeldung/com/DependentTests.java @@ -1,46 +1,25 @@ package baeldung.com; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.testng.Assert; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class DependentTests { - private String validEmail = "abc@qwe.com"; - private EmailValidator emailValidator; - private LoginValidator loginValidator; + private static final Logger LOGGER = LoggerFactory.getLogger(DependentTests.class); - @BeforeClass - public void setup() { - emailValidator = new EmailValidator(); - loginValidator = new LoginValidator(); - } + private String email = "abc@qwe.com"; @Test public void givenEmail_ifValid_thenTrue() { - boolean valid = emailValidator.validate(validEmail); + boolean valid = email.contains("@"); Assert.assertEquals(valid, true); } - @Test(dependsOnMethods = { "givenEmail_ifValid_thenTrue" }) + @Test(dependsOnMethods = {"givenEmail_ifValid_thenTrue"}) public void givenValidEmail_whenLoggedIn_thenTrue() { - boolean valid = loginValidator.validate(); - Assert.assertEquals(valid, true); + LOGGER.info("Email {} valid >> logging in", email); } } -class EmailValidator { - - boolean validate(String validEmail) { - return true; - } - -} - -class LoginValidator { - - boolean validate() { - return true; - } - -} diff --git a/testng/src/test/java/baeldung/com/ParametrizedTestNGTest.java b/testng/src/test/java/baeldung/com/ParametrizedTestNGTest.java deleted file mode 100644 index e4f3aacf5b..0000000000 --- a/testng/src/test/java/baeldung/com/ParametrizedTestNGTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package baeldung.com; - -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -public class ParametrizedTestNGTest { - - @Test - @Parameters({ "name", "expectedResult" }) - public void givenNumber_ifPrime_thenCorrect(String name, boolean expectedResult) { - Assert.assertEquals(expectedResult, name.length() > 0); - } - - @DataProvider(name = "test1") - public static Object[][] primeNumbers() { - return new Object[][] { { "Peter", true }, { "Sam", true }, { "Tim", true }, { "Lucy", true } }; - } - - @Test(dataProvider = "test1") - public void givenNumber_whenPrime_thenCorrect(String name, boolean expectedResult) { - Assert.assertEquals(expectedResult, name.length() > 0); - } - - @Test(dataProvider = "myDataProvider") - public void parameterCheckTest(User user) { - Assert.assertEquals("sam", user.getName()); - Assert.assertEquals(12, user.getAge()); - } - - @DataProvider(name = "myDataProvider") - public Object[][] parameterProvider() { - User usr = new User(); - usr.setName("sam"); - usr.setAge(12); - return new Object[][] { { usr } }; - } - -} - - -class User { - private String name; - private int age; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } -} diff --git a/testng/src/test/java/baeldung/com/ParametrizedTests.java b/testng/src/test/java/baeldung/com/ParametrizedTests.java new file mode 100644 index 0000000000..d3813f5382 --- /dev/null +++ b/testng/src/test/java/baeldung/com/ParametrizedTests.java @@ -0,0 +1,77 @@ +package baeldung.com; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +public class ParametrizedTests { + + private static final Logger LOGGER = LoggerFactory.getLogger(ParametrizedTests.class); + + @Test + @Parameters({"value", "isEven"}) + public void givenNumberFromXML_ifEvenCheckOK_thenCorrect(int value, boolean isEven) { + Assert.assertEquals(isEven, value % 2 == 0); + } + + @DataProvider(name = "numbers") + public static Object[][] evenNumbers() { + return new Object[][]{{1, false}, {2, true}, {4, true}}; + } + + @Test(dataProvider = "numbers") + public void givenNumberFromDataProvider_ifEvenCheckOK_thenCorrect(Integer number, boolean expected) { + Assert.assertEquals(expected, number % 2 == 0); + } + + @Test(dataProvider = "numbersObject") + public void givenNumberObjectFromDataProvider_ifEvenCheckOK_thenCorrect(EvenNumber number) { + Assert.assertEquals(number.isEven(), number.getValue() % 2 == 0); + } + + @DataProvider(name = "numbersObject") + public Object[][] parameterProvider() { + return new Object[][]{{new EvenNumber(1, false)}, {new EvenNumber(2, true)}, {new EvenNumber(4, true),}}; + } + +} + + +class EvenNumber { + private int value; + private boolean isEven; + + public EvenNumber(int number, boolean isEven) { + this.value = number; + this.isEven = isEven; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public boolean isEven() { + return isEven; + } + + public void setEven(boolean even) { + isEven = even; + } + + @Override + public String toString() { + return "EvenNumber{" + + "value=" + value + + ", isEven=" + isEven + + '}'; + } +} + + diff --git a/testng/src/test/java/baeldung/com/RegistrationTest.java b/testng/src/test/java/baeldung/com/RegistrationTest.java index 7cb17c9cb8..ec551d9c27 100644 --- a/testng/src/test/java/baeldung/com/RegistrationTest.java +++ b/testng/src/test/java/baeldung/com/RegistrationTest.java @@ -1,11 +1,14 @@ package baeldung.com; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.testng.annotations.Test; public class RegistrationTest { + private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationTest.class); @Test - public void givenEmail_ifValid_thenCorrect() { - + public void whenCalledFromSuite_thanOK() { + LOGGER.info("Registration successful"); } } diff --git a/testng/src/test/java/baeldung/com/SignInTest.java b/testng/src/test/java/baeldung/com/SignInTest.java index 4884154345..f0547374d1 100644 --- a/testng/src/test/java/baeldung/com/SignInTest.java +++ b/testng/src/test/java/baeldung/com/SignInTest.java @@ -1,12 +1,14 @@ package baeldung.com; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.testng.annotations.Test; public class SignInTest { + private static final Logger LOGGER = LoggerFactory.getLogger(SignInTest.class); @Test - public void givenUsername_ifValid_thenCorrect() { - + public void whenCalledFromSuite_thanOK() { + LOGGER.info("SignIn successful"); } - } diff --git a/testng/src/test/java/baeldung/com/SummationServiceTest.java b/testng/src/test/java/baeldung/com/SummationServiceTest.java index 471d7a7c8a..f377a009df 100644 --- a/testng/src/test/java/baeldung/com/SummationServiceTest.java +++ b/testng/src/test/java/baeldung/com/SummationServiceTest.java @@ -1,5 +1,7 @@ package baeldung.com; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.TestNG; import org.testng.annotations.*; @@ -8,6 +10,7 @@ import java.util.ArrayList; import java.util.List; public class SummationServiceTest extends TestNG { + private static final Logger LOGGER = LoggerFactory.getLogger(DependentTests.class); private List numbers; diff --git a/testng/src/test/resources/parameterised_test.xml b/testng/src/test/resources/parameterised_test.xml deleted file mode 100644 index 2381ba67d0..0000000000 --- a/testng/src/test/resources/parameterised_test.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/testng/src/test/resources/parametrized_test.xml b/testng/src/test/resources/parametrized_test.xml new file mode 100644 index 0000000000..932af30e4e --- /dev/null +++ b/testng/src/test/resources/parametrized_test.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/test_group.xml b/testng/src/test/resources/test_group.xml index d636a4174d..26868375f2 100644 --- a/testng/src/test/resources/test_group.xml +++ b/testng/src/test/resources/test_group.xml @@ -1,6 +1,6 @@ - + diff --git a/testng/src/test/resources/test_setup.xml b/testng/src/test/resources/test_setup.xml new file mode 100644 index 0000000000..7d9708193e --- /dev/null +++ b/testng/src/test/resources/test_setup.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/testng/src/test/resources/test_suite.xml b/testng/src/test/resources/test_suite.xml index 201ed3f645..0fe5d1cc40 100644 --- a/testng/src/test/resources/test_suite.xml +++ b/testng/src/test/resources/test_suite.xml @@ -1,6 +1,6 @@ - + From 46f854c03be775b12477f238eec62b66a6e7b9e7 Mon Sep 17 00:00:00 2001 From: lor6 Date: Sun, 19 Feb 2017 05:01:49 +0200 Subject: [PATCH 11/23] apache bval project (#1178) * apache bval project * update tests * remove extra lines --- apache-bval/pom.xml | 51 ++++++++ .../main/java/com/baeldung/model/User.java | 120 ++++++++++++++++++ .../com/baeldung/validation/Password.java | 25 ++++ .../validation/PasswordValidator.java | 35 +++++ .../baeldung/validation/ValidationTest.java | 97 ++++++++++++++ 5 files changed, 328 insertions(+) create mode 100644 apache-bval/pom.xml create mode 100644 apache-bval/src/main/java/com/baeldung/model/User.java create mode 100644 apache-bval/src/main/java/com/baeldung/validation/Password.java create mode 100644 apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java create mode 100644 apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml new file mode 100644 index 0000000000..5d556af56f --- /dev/null +++ b/apache-bval/pom.xml @@ -0,0 +1,51 @@ + + 4.0.0 + apache-bval + apache-bval + 0.0.1-SNAPSHOT + + + + org.apache.bval + bval-jsr + ${bval.version} + + + javax.validation + validation-api + 1.1.0.Final + + + org.apache.bval + bval-extras + ${bval.version} + + + + junit + junit + ${junit.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + 3.6.0 + 4.12 + 1.1.2 + + \ No newline at end of file diff --git a/apache-bval/src/main/java/com/baeldung/model/User.java b/apache-bval/src/main/java/com/baeldung/model/User.java new file mode 100644 index 0000000000..477136ddb4 --- /dev/null +++ b/apache-bval/src/main/java/com/baeldung/model/User.java @@ -0,0 +1,120 @@ +package com.baeldung.model; + +import java.io.File; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +import org.apache.bval.constraints.Email; +import org.apache.bval.constraints.NotEmpty; +import org.apache.bval.extras.constraints.checkdigit.IBAN; +import org.apache.bval.extras.constraints.creditcard.Visa; +import org.apache.bval.extras.constraints.file.Directory; +import org.apache.bval.extras.constraints.net.InetAddress; + +import com.baeldung.validation.Password; + +public class User { + @NotNull + @Email + private String email; + + @NotEmpty + @Password + private String password; + + @Size(min = 1, max = 20) + private String name; + + @Min(18) + private int age; + + @Visa + private String cardNumber = ""; + + @IBAN + private String iban = ""; + + @InetAddress + private String website = ""; + + @Directory + private File mainDirectory=new File("."); + + public User() { + } + + public User(String email, String password, String name, int age) { + super(); + this.email = email; + this.password = password; + this.name = name; + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getCardNumber() { + return cardNumber; + } + + public void setCardNumber(String cardNumber) { + this.cardNumber = cardNumber; + } + + public String getIban() { + return iban; + } + + public void setIban(String iban) { + this.iban = iban; + } + + public String getWebsite() { + return website; + } + + public void setWebsite(String website) { + this.website = website; + } + + public File getMainDirectory() { + return mainDirectory; + } + + public void setMainDirectory(File mainDirectory) { + this.mainDirectory = mainDirectory; + } + +} diff --git a/apache-bval/src/main/java/com/baeldung/validation/Password.java b/apache-bval/src/main/java/com/baeldung/validation/Password.java new file mode 100644 index 0000000000..4ae06b2fb0 --- /dev/null +++ b/apache-bval/src/main/java/com/baeldung/validation/Password.java @@ -0,0 +1,25 @@ +package com.baeldung.validation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.Payload; + +import static java.lang.annotation.ElementType.*; + +@Constraint(validatedBy = { PasswordValidator.class }) +@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface Password { + String message() default "Invalid password"; + + Class[] groups() default {}; + + Class[] payload() default {}; + + int length() default 6; + + int nonAlpha() default 1; +} diff --git a/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java b/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java new file mode 100644 index 0000000000..19038d04d5 --- /dev/null +++ b/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java @@ -0,0 +1,35 @@ +package com.baeldung.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class PasswordValidator implements ConstraintValidator { + + private int length; + private int nonAlpha; + + @Override + public void initialize(Password password) { + this.length = password.length(); + this.nonAlpha = password.nonAlpha(); + + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if (value.length() < length) { + return false; + } + int nonAlphaNr = 0; + for (int i = 0; i < value.length(); i++) { + if (!Character.isLetterOrDigit(value.charAt(i))) { + nonAlphaNr++; + } + } + if (nonAlphaNr < nonAlpha) { + return false; + } + return true; + } + +} diff --git a/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java b/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java new file mode 100644 index 0000000000..cd58d4460a --- /dev/null +++ b/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java @@ -0,0 +1,97 @@ +package com.baeldung.validation; + +import java.io.File; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.apache.bval.jsr.ApacheValidationProvider; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.*; + +import com.baeldung.model.User; + +public class ValidationTest { + private static ValidatorFactory validatorFactory; + private static Validator validator; + + @BeforeClass + public static void setup() { + validatorFactory = Validation.byProvider(ApacheValidationProvider.class) + .configure() + .buildValidatorFactory(); + validator = validatorFactory.getValidator(); + } + + @Test + public void givenUser_whenValidate_thenValidationViolations() { + User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15); + + Set> violations = validator.validate(user); + assertTrue("no violations", violations.size() > 0); + } + + @Test + public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() { + User user = new User("ana@yahoo.com", "pass", "Ana", 12); + + Set> propertyViolations = validator.validateProperty(user, "age"); + assertEquals("size is not 1", 1, propertyViolations.size()); + } + + @Test + public void givenValidAge_whenValidateValue_thenNoConstraintViolation() { + User user = new User("ana@yahoo.com", "pass", "Ana", 18); + + Set> valueViolations = validator.validateValue(User.class, "age", 20); + assertEquals("size is not 0", 0, valueViolations.size()); + } + + @Test + public void whenValidateNonJSR_thenCorrect() { + User user = new User("ana@yahoo.com", "pass", "Ana", 20); + user.setCardNumber("1234"); + user.setIban("1234"); + user.setWebsite("10.0.2.50"); + user.setMainDirectory(new File(".")); + + Set> violations = validator.validateProperty(user, "iban"); + assertEquals("size is not 1", 1, violations.size()); + + violations = validator.validateProperty(user, "website"); + assertEquals("size is not 0", 0, violations.size()); + + violations = validator.validateProperty(user, "mainDirectory"); + assertEquals("size is not 0", 0, violations.size()); + } + + @Test + public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() { + User user = new User("ana@yahoo.com", "password", "Ana", 20); + Set> violations = validator.validateProperty(user, "password"); + assertEquals("message incorrect", "Invalid password", violations.iterator() + .next() + .getMessage()); + } + + @Test + public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() { + User user = new User("ana@yahoo.com", "password#", "Ana", 20); + + Set> violations = validator.validateProperty(user, "password"); + assertEquals("size is not 0", 0, violations.size()); + } + + @AfterClass + public static void close() { + if (validatorFactory != null) { + validatorFactory.close(); + } + } +} From e5ecd86f27adedff215716f6916e72caccdfda83 Mon Sep 17 00:00:00 2001 From: mariiakulik Date: Sun, 19 Feb 2017 22:22:43 +0100 Subject: [PATCH 12/23] README files update (#1195) * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.MD * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.MD * Create README.md * Update README.md * Create README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.MD * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Delete README.md --- JGit/README.md | 3 +++ algorithms/README.md | 3 +++ apache-thrift/README.md | 3 +++ apache-velocity/README.md | 3 +++ core-java-9/README.md | 2 ++ core-java/README.md | 21 +++++++++++++++++++ .../test/java/com/baeldung/java/map/README.md | 2 -- couchbase-sdk/README.md | 1 + disruptor/README.md | 3 +++ ejb/README.md | 3 +++ guava/README.md | 8 +++++++ httpclient/README.md | 1 + jackson/README.md | 1 + java-mongodb/README.md | 3 +++ javaslang/README.md | 2 ++ jee7/README.md | 1 + kotlin/README.md | 3 +++ metrics/README.md | 3 +++ pdf/README.md | 1 + rxjava/README.md | 4 ++++ spring-all/README.md | 2 ++ spring-amqp/README.md | 3 +++ spring-boot/README.MD | 3 +++ spring-data-mongodb/README.md | 1 + spring-data-neo4j/README.md | 1 + spring-hibernate4/README.md | 2 ++ spring-jersey/README.md | 2 ++ spring-mobile/README.md | 4 ++++ spring-mvc-email/README.md | 6 +++++- spring-mvc-java/README.md | 2 ++ spring-mvc-simple/README.md | 3 +++ spring-reactor/README.md | 3 +++ spring-security-rest/README.md | 1 + spring-sleuth/README.md | 3 +++ static-analysis/README.md | 3 +++ 35 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 JGit/README.md create mode 100644 algorithms/README.md create mode 100644 apache-thrift/README.md create mode 100644 apache-velocity/README.md delete mode 100644 core-java/src/test/java/com/baeldung/java/map/README.md create mode 100644 ejb/README.md create mode 100644 java-mongodb/README.md create mode 100644 kotlin/README.md create mode 100644 metrics/README.md create mode 100644 rxjava/README.md create mode 100644 spring-amqp/README.md create mode 100644 spring-mobile/README.md create mode 100644 spring-mvc-simple/README.md create mode 100644 spring-reactor/README.md create mode 100644 spring-sleuth/README.md create mode 100644 static-analysis/README.md diff --git a/JGit/README.md b/JGit/README.md new file mode 100644 index 0000000000..5c65f1101b --- /dev/null +++ b/JGit/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [A Guide to JGit](http://www.baeldung.com/jgit) diff --git a/algorithms/README.md b/algorithms/README.md new file mode 100644 index 0000000000..4789768fad --- /dev/null +++ b/algorithms/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra) diff --git a/apache-thrift/README.md b/apache-thrift/README.md new file mode 100644 index 0000000000..d8b9195dcc --- /dev/null +++ b/apache-thrift/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Working with Apache Thrift](http://www.baeldung.com/apache-thrift) diff --git a/apache-velocity/README.md b/apache-velocity/README.md new file mode 100644 index 0000000000..53c67f847e --- /dev/null +++ b/apache-velocity/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to Apache Velocity](http://www.baeldung.com/apache-velocity) diff --git a/core-java-9/README.md b/core-java-9/README.md index 1b44239e40..53ad79e59c 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -6,3 +6,5 @@ ### Relevant Articles: - [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api) +- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods) +- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) diff --git a/core-java/README.md b/core-java/README.md index 341dbdf910..a34908d8ae 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -58,3 +58,24 @@ - [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue) - [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch) - [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm) +- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map) +- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue) +- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector) +- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception) +- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap) +- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern) +- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) +- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool) +- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) +- [Spring Security – Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers) +- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions) +- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda) +- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn) +- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions) +- [Guide to the Guava BiMap](http://www.baeldung.com/guava-bimap) +- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream) +- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) +- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions) +- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap) +- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap) +- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap) diff --git a/core-java/src/test/java/com/baeldung/java/map/README.md b/core-java/src/test/java/com/baeldung/java/map/README.md deleted file mode 100644 index 0bba153763..0000000000 --- a/core-java/src/test/java/com/baeldung/java/map/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap) diff --git a/couchbase-sdk/README.md b/couchbase-sdk/README.md index 9cdcdea012..f124a0192c 100644 --- a/couchbase-sdk/README.md +++ b/couchbase-sdk/README.md @@ -4,6 +4,7 @@ - [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk) - [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring) - [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase) +- [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view) ### Overview This Maven project contains the Java code for the Couchbase entities and Spring services diff --git a/disruptor/README.md b/disruptor/README.md index e69de29bb2..779b1e89c4 100644 --- a/disruptor/README.md +++ b/disruptor/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Concurrency with LMAX Disruptor – An Introduction](http://www.baeldung.com/lmax-disruptor-concurrency) diff --git a/ejb/README.md b/ejb/README.md new file mode 100644 index 0000000000..08392bc80d --- /dev/null +++ b/ejb/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro) diff --git a/guava/README.md b/guava/README.md index 40e7f19f41..ee224bae5f 100644 --- a/guava/README.md +++ b/guava/README.md @@ -16,3 +16,11 @@ - [Guava – Sets](http://www.baeldung.com/guava-sets) - [Guava – Maps](http://www.baeldung.com/guava-maps) - [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial) +- [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering) +- [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions) +- [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader) +- [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus) +- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap) +- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset) +- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap) +- [Guide to Guava Table](http://www.baeldung.com/guava-table) diff --git a/httpclient/README.md b/httpclient/README.md index a848edfea6..2a98c2feac 100644 --- a/httpclient/README.md +++ b/httpclient/README.md @@ -19,3 +19,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Multipart Upload with HttpClient 4](http://www.baeldung.com/httpclient-multipart-upload) - [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial) - [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide) +- [Advanced HttpClient Configuration](http://www.baeldung.com/httpclient-advanced-config) diff --git a/jackson/README.md b/jackson/README.md index 67a03589a8..d9faa377f1 100644 --- a/jackson/README.md +++ b/jackson/README.md @@ -25,3 +25,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [More Jackson Annotations](http://www.baeldung.com/jackson-advanced-annotations) - [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance) - [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat) +- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional) diff --git a/java-mongodb/README.md b/java-mongodb/README.md new file mode 100644 index 0000000000..01245ac6cf --- /dev/null +++ b/java-mongodb/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb) diff --git a/javaslang/README.md b/javaslang/README.md index 334ac02f60..e451883516 100644 --- a/javaslang/README.md +++ b/javaslang/README.md @@ -1,2 +1,4 @@ ### Relevant Articles: - [Introduction to Javaslang](http://www.baeldung.com/javaslang) +- [Guide to Try in Javaslang](http://www.baeldung.com/javaslang-try) +- [Guide to Pattern Matching in Javaslang](http://www.baeldung.com/javaslang-pattern-matching) diff --git a/jee7/README.md b/jee7/README.md index 44ca9c2f6e..bc242c3340 100644 --- a/jee7/README.md +++ b/jee7/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Scheduling in Java EE](http://www.baeldung.com/scheduling-in-java-enterprise-edition) +- [JSON Processing in Java EE 7](http://www.baeldung.com/jee7-json) diff --git a/kotlin/README.md b/kotlin/README.md new file mode 100644 index 0000000000..6447a26f5c --- /dev/null +++ b/kotlin/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to the Kotlin Language](http://www.baeldung.com/kotlin) diff --git a/metrics/README.md b/metrics/README.md new file mode 100644 index 0000000000..c98024c479 --- /dev/null +++ b/metrics/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Intro to Dropwizard Metrics](http://www.baeldung.com/dropwizard-metrics) diff --git a/pdf/README.md b/pdf/README.md index 7160df4081..5454d2b2de 100644 --- a/pdf/README.md +++ b/pdf/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [PDF Conversions in Java](http://www.baeldung.com/pdf-conversions-java) +- [Creating PDF Files in Java](http://www.baeldung.com/java-pdf-creation) diff --git a/rxjava/README.md b/rxjava/README.md new file mode 100644 index 0000000000..7670dd4ed3 --- /dev/null +++ b/rxjava/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [Dealing with Backpressure with RxJava](http://www.baeldung.com/rxjava-backpressure) +- [How to Test RxJava?](http://www.baeldung.com/rxjava-testing) diff --git a/spring-all/README.md b/spring-all/README.md index 90ae69300a..a8ea7c58c7 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -16,3 +16,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) - [Introduction To Ehcache](http://www.baeldung.com/ehcache) +- [A Guide to the Spring Task Scheduler](http://www.baeldung.com/spring-task-scheduler) +- [Guide to Spring Retry](http://www.baeldung.com/spring-retry) diff --git a/spring-amqp/README.md b/spring-amqp/README.md new file mode 100644 index 0000000000..b0d16c9305 --- /dev/null +++ b/spring-amqp/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Messaging With Spring AMQP](http://www.baeldung.com/spring-amqp) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 05173ef318..d0a02c69fc 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -7,3 +7,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) - [Introduction to WebJars](http://www.baeldung.com/maven-webjars) - [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) +- [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan) +- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) +- [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot) diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index d656bc897c..c2a1f703b5 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -9,3 +9,4 @@ - [Custom Cascading in Spring Data MongoDB](http://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb) - [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs) - [Introduction to Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-tutorial) +- [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations) diff --git a/spring-data-neo4j/README.md b/spring-data-neo4j/README.md index 0f13d9dbc9..03c9ed333d 100644 --- a/spring-data-neo4j/README.md +++ b/spring-data-neo4j/README.md @@ -2,6 +2,7 @@ ### Relevant Articles: - [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-intro) +- [A Guide to Neo4J with Java](http://www.baeldung.com/java-neo4j) ### Build the Project with Tests Running ``` diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 7888e8b4ee..02888c4ad0 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -12,6 +12,7 @@ - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate/) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) - [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) +- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) ### Quick Start @@ -22,3 +23,4 @@ mvn install mvn cargo:run ``` - **note**: starts on port `8082` + diff --git a/spring-jersey/README.md b/spring-jersey/README.md index 2767ceb9a7..8b2eecc0e1 100644 --- a/spring-jersey/README.md +++ b/spring-jersey/README.md @@ -1,3 +1,5 @@ ========= ## REST API with Jersey & Spring Example Project +- [REST API with Jersey and Spring](http://www.baeldung.com/jersey-rest-api-with-spring) +- [JAX-RS Client with Jersey](http://www.baeldung.com/jersey-jax-rs-client) diff --git a/spring-mobile/README.md b/spring-mobile/README.md new file mode 100644 index 0000000000..e3d23bcda6 --- /dev/null +++ b/spring-mobile/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [A Guide to Spring Mobile](http://www.baeldung.com/spring-mobile) + diff --git a/spring-mvc-email/README.md b/spring-mvc-email/README.md index 0de6532393..aa880188d7 100644 --- a/spring-mvc-email/README.md +++ b/spring-mvc-email/README.md @@ -1,3 +1,7 @@ +## Relevant articles: + +- [Guide to Spring Email](http://www.baeldung.com/spring-email) + ## Spring MVC Email Example Spring MVC project to send email from web form. @@ -10,4 +14,4 @@ Type http://localhost:8080 in your browser to open the application. ### Sending test emails -Follow UI links to send simple email, email using template or email with attachment. \ No newline at end of file +Follow UI links to send simple email, email using template or email with attachment. diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 0f267c5ec9..575e4f583e 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -18,3 +18,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) +- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) +- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md new file mode 100644 index 0000000000..ffb02c846a --- /dev/null +++ b/spring-mvc-simple/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [HandlerAdapters in Spring MVC](http://www.baeldung.com/spring-mvc-handler-adapters) diff --git a/spring-reactor/README.md b/spring-reactor/README.md new file mode 100644 index 0000000000..0da2d6be51 --- /dev/null +++ b/spring-reactor/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to Spring Reactor](http://www.baeldung.com/spring-reactor) diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index a1dfa32c6d..92b759a66a 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -13,3 +13,4 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Custom Error Message Handling for REST API](http://www.baeldung.com/global-error-handler-in-a-spring-rest-api) - [An Intro to Spring HATEOAS](http://www.baeldung.com/spring-hateoas-tutorial) - [Spring Security Context Propagation with @Async](http://www.baeldung.com/spring-security-async-principal-propagation) +- [Servlet 3 Async Support with Spring MVC and Spring Security](http://www.baeldung.com/spring-mvc-async-security) diff --git a/spring-sleuth/README.md b/spring-sleuth/README.md new file mode 100644 index 0000000000..47aa126939 --- /dev/null +++ b/spring-sleuth/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Spring Cloud Sleuth in a Monolith Application](http://www.baeldung.com/spring-cloud-sleuth-single-application) diff --git a/static-analysis/README.md b/static-analysis/README.md new file mode 100644 index 0000000000..74cc64b90d --- /dev/null +++ b/static-analysis/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to PMD](http://www.baeldung.com/pmd) From 7c337eb6c08ec8500f22e328d715b60d682744c6 Mon Sep 17 00:00:00 2001 From: buddhini81 Date: Mon, 20 Feb 2017 05:24:42 +0530 Subject: [PATCH 13/23] Adding Code for BAEL-394 (#1163) * Code for evaluation article Article : Field vs. Constructor Injection * Correct typo in attribute name * Delete EbookRepositiry.java * Add corrected class * Update LibraryUtils.java * Update Member.java * Update Reservation.java * Adding new file AccountServlet * Adding new files for BAEL-394 * Add new files for BAEL-394 * Add new file for BAEL-394 * Indentation of annotations fixed * Indentation of annotations fixed * Indentation of annotations fixed * Removing this class since it is not relevant * New example added for @WebListener --- .../javaeeannotations/AccountServlet.java | 57 +++++++++++++++++++ .../BankAppServletContextListener.java | 17 ++++++ .../javaeeannotations/LoggingFilter.java | 36 ++++++++++++ .../UploadCustomerDocumentsServlet.java | 29 ++++++++++ jee7/src/main/webapp/WEB-INF/web.xml | 11 ++++ jee7/src/main/webapp/index.jsp | 16 ++++++ jee7/src/main/webapp/login.jsp | 12 ++++ jee7/src/main/webapp/upload.jsp | 16 ++++++ .../src/main/java/com/baeldung/Ebook.java | 20 +++++++ .../java/com/baeldung/EbookRepository.java | 5 ++ .../main/java/com/baeldung/LibraryUtils.java | 12 ++++ .../src/main/java/com/baeldung/Member.java | 20 +++++++ .../main/java/com/baeldung/Reservation.java | 14 +++++ 13 files changed, 265 insertions(+) create mode 100644 jee7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java create mode 100644 jee7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java create mode 100644 jee7/src/main/java/com/baeldung/javaeeannotations/LoggingFilter.java create mode 100644 jee7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java create mode 100644 jee7/src/main/webapp/WEB-INF/web.xml create mode 100644 jee7/src/main/webapp/index.jsp create mode 100644 jee7/src/main/webapp/login.jsp create mode 100644 jee7/src/main/webapp/upload.jsp create mode 100644 spring-core/src/main/java/com/baeldung/Ebook.java create mode 100644 spring-core/src/main/java/com/baeldung/EbookRepository.java create mode 100644 spring-core/src/main/java/com/baeldung/LibraryUtils.java create mode 100644 spring-core/src/main/java/com/baeldung/Member.java create mode 100644 spring-core/src/main/java/com/baeldung/Reservation.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java b/jee7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java new file mode 100644 index 0000000000..e3f1667595 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java @@ -0,0 +1,57 @@ +package com.baeldung.javaeeannotations; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.HttpMethodConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet( + name = "BankAccountServlet", + description = "Represents a Bank Account and it's transactions", + urlPatterns = {"/account", "/bankAccount" }, + initParams = { @WebInitParam(name = "type", value = "savings") } + ) +@ServletSecurity( + value = @HttpConstraint(rolesAllowed = {"admin"}), + httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"admin"})} + ) +public class AccountServlet extends javax.servlet.http.HttpServlet { + + String accountType = null; + + @Override + public void init(ServletConfig config) throws ServletException { + accountType = config.getInitParameter("type"); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + PrintWriter writer = response.getWriter(); + writer.println("Hello, I am an AccountServlet!"); + writer.flush(); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { + double accountBalance = 1000d; + double interestRate = Double.parseDouble(request.getAttribute("interest").toString()); + + String paramDepositAmt = request.getParameter("dep"); + double depositAmt = Double.parseDouble(paramDepositAmt); + + accountBalance = accountBalance + depositAmt; + + PrintWriter writer = response.getWriter(); + writer.println(" Balance of " + accountType + " account is: " + + accountBalance + "
This account bares an interest rate of " + interestRate + + " % "); + writer.flush(); + + } +} diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java b/jee7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java new file mode 100644 index 0000000000..6b43dd8a84 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java @@ -0,0 +1,17 @@ +package com.baeldung.javaeeannotations; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +@WebListener +public class BankAppServletContextListener implements ServletContextListener { + + public void contextInitialized(ServletContextEvent sce) { + sce.getServletContext().setAttribute("ATTR_DEFAULT_LANGUAGE", "english"); + } + + public void contextDestroyed(ServletContextEvent sce) { + System.out.println("CONTEXT DESTROYED"); + } +} diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/LoggingFilter.java b/jee7/src/main/java/com/baeldung/javaeeannotations/LoggingFilter.java new file mode 100644 index 0000000000..97de5ec0de --- /dev/null +++ b/jee7/src/main/java/com/baeldung/javaeeannotations/LoggingFilter.java @@ -0,0 +1,36 @@ +package com.baeldung.javaeeannotations; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebFilter( + urlPatterns = "/bankAccount/*", + filterName = "LoggingFilter", + description = "Filter all account transaction URLs" + ) +public class LoggingFilter implements javax.servlet.Filter { + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse res = (HttpServletResponse) response; + + res.sendRedirect(req.getContextPath() + "/login.jsp"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + +} diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java b/jee7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java new file mode 100644 index 0000000000..8a6c709b81 --- /dev/null +++ b/jee7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java @@ -0,0 +1,29 @@ +package com.baeldung.javaeeannotations; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.annotation.MultipartConfig; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.Part; + +@WebServlet(urlPatterns = { "/uploadCustDocs" }) +@MultipartConfig( + fileSizeThreshold = 1024 * 1024 * 20, + maxFileSize = 1024 * 1024 * 20, + maxRequestSize = 1024 * 1024 * 25, + location = "D:/custDocs" + ) +public class UploadCustomerDocumentsServlet extends HttpServlet { + + protected void doPost( + HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + for (Part part : request.getParts()) { + part.write("myFile"); + } + } + +} diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee7/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..0a3d84d2d4 --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + + BASIC + default + + + \ No newline at end of file diff --git a/jee7/src/main/webapp/index.jsp b/jee7/src/main/webapp/index.jsp new file mode 100644 index 0000000000..0c389ef5b1 --- /dev/null +++ b/jee7/src/main/webapp/index.jsp @@ -0,0 +1,16 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +My Account + + +
+ Width: +    + +
+ + \ No newline at end of file diff --git a/jee7/src/main/webapp/login.jsp b/jee7/src/main/webapp/login.jsp new file mode 100644 index 0000000000..885df0c3d9 --- /dev/null +++ b/jee7/src/main/webapp/login.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Login + + +Login Here... + + \ No newline at end of file diff --git a/jee7/src/main/webapp/upload.jsp b/jee7/src/main/webapp/upload.jsp new file mode 100644 index 0000000000..020483b99f --- /dev/null +++ b/jee7/src/main/webapp/upload.jsp @@ -0,0 +1,16 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Insert title here + + +
+ +
+ +
+ + \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/Ebook.java b/spring-core/src/main/java/com/baeldung/Ebook.java new file mode 100644 index 0000000000..fc29ddfcf5 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/Ebook.java @@ -0,0 +1,20 @@ +package com.baeldung; + +public class Ebook { + + private int bookId; + private String bookTitle; + + public int getBookId() { + return bookId; + } + public void setBookId(int bookId) { + this.bookId = bookId; + } + public String getBookTitle() { + return bookTitle; + } + public void setBookTitle(String bookTitle) { + this.bookTitle = bookTitle; + } +} diff --git a/spring-core/src/main/java/com/baeldung/EbookRepository.java b/spring-core/src/main/java/com/baeldung/EbookRepository.java new file mode 100644 index 0000000000..661283c355 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/EbookRepository.java @@ -0,0 +1,5 @@ +package com.baeldung; + +public interface EbookRepository { + String titleById(int id); +} diff --git a/spring-core/src/main/java/com/baeldung/LibraryUtils.java b/spring-core/src/main/java/com/baeldung/LibraryUtils.java new file mode 100644 index 0000000000..49af60c89d --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/LibraryUtils.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.beans.factory.annotation.Autowired; + +public class LibraryUtils { + @Autowired + private EbookRepository eBookRepository; + + public String findBook(int id) { + return eBookRepository.titleById(id); + } +} diff --git a/spring-core/src/main/java/com/baeldung/Member.java b/spring-core/src/main/java/com/baeldung/Member.java new file mode 100644 index 0000000000..ceebb32017 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/Member.java @@ -0,0 +1,20 @@ +package com.baeldung; + +public class Member { + + private int memberId; + private String memberName; + + public int getMemberId() { + return memberId; + } + public void setMemberId(int memberId) { + this.memberId = memberId; + } + public String getMemberName() { + return memberName; + } + public void setMemberName(String memberName) { + this.memberName = memberName; + } +} diff --git a/spring-core/src/main/java/com/baeldung/Reservation.java b/spring-core/src/main/java/com/baeldung/Reservation.java new file mode 100644 index 0000000000..ed33bb6464 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/Reservation.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import org.springframework.beans.factory.annotation.Autowired; + +public class Reservation { + private Member member; + private Ebook eBook; + + @Autowired + public Reservation(Member member, Ebook eBook) { + this.member = member; + this.eBook = eBook; + } +} From 689219c7187577afbd460d733e5e5153f4b0f990 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 19 Feb 2017 22:02:57 -0600 Subject: [PATCH 14/23] Create README.md --- apache-bval/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 apache-bval/README.md diff --git a/apache-bval/README.md b/apache-bval/README.md new file mode 100644 index 0000000000..80ea149993 --- /dev/null +++ b/apache-bval/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Intro to Apache BVal](http://www.baeldung.com/apache-bval) From 99c8ee52282b30d97cbab7fd717a43356d80b4a8 Mon Sep 17 00:00:00 2001 From: dhruba619 Date: Mon, 20 Feb 2017 12:52:19 +0530 Subject: [PATCH 15/23] BAEL-41 Intro to Log4J2 code simplification and refactoring --- log4j2/pom.xml | 179 +++++++++--------- .../AsyncFileAppenderUsingJsonLayoutTest.java | 32 ---- ...ConsoleAppenderUsingDefaultLayoutTest.java | 21 -- ...enderUsingPatternLayoutWithColorsTest.java | 51 ----- .../log4j2/tests/CustomLoggingTest.java | 121 ++++++++++++ .../FailoverSyslogConsoleAppenderTest.java | 27 --- .../log4j2/tests/JDBCAppenderTest.java | 51 ----- ...RollingFileAppenderUsingXMLLayoutTest.java | 34 ---- .../log4j2/tests/jdbc/ConnectionFactory.java | 1 - ...log4j2-async-file-appender_json-layout.xml | 17 -- ...log4j2-console-appender_pattern-layout.xml | 27 --- ...syslog-console-appender_pattern-layout.xml | 20 -- ...onsole-appender_pattern-layout_colored.xml | 3 +- .../test/resources/log4j2-jdbc-appender.xml | 19 -- ...og4j2-rolling-file-appender_xml-layout.xml | 18 -- log4j2/src/test/resources/log4j2.xml | 66 ++++++- 16 files changed, 273 insertions(+), 414 deletions(-) delete mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java delete mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java delete mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java create mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java delete mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java delete mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java delete mode 100644 log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java delete mode 100644 log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml delete mode 100644 log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml delete mode 100644 log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml delete mode 100644 log4j2/src/test/resources/log4j2-jdbc-appender.xml delete mode 100644 log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml diff --git a/log4j2/pom.xml b/log4j2/pom.xml index 893c79be72..a4c8f19f69 100644 --- a/log4j2/pom.xml +++ b/log4j2/pom.xml @@ -1,105 +1,104 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - log4j2 + log4j2 - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + - - - - org.apache.logging.log4j - log4j-core - ${log4j-core.version} - + + + + org.apache.logging.log4j + log4j-core + ${log4j-core.version} + - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson.version} + - - - com.h2database - h2 - ${h2.version} - - - org.apache.commons - commons-dbcp2 - ${commons-dbcp2.version} - + + + com.h2database + h2 + ${h2.version} + + + org.apache.commons + commons-dbcp2 + ${commons-dbcp2.version} + - - - org.apache.logging.log4j - log4j-core - ${log4j-core.version} - test-jar - test - - - junit - junit - ${junit.version} - test - - + + + org.apache.logging.log4j + log4j-core + ${log4j-core.version} + test-jar + test + + + junit + junit + ${junit.version} + test + + - - + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - - true - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + + true + + - - + + - - 2.8.5 - 1.4.193 - 2.1.1 - 2.7 - 4.12 - - 3.6.0 - 2.19.1 - + + 2.8.5 + 1.4.193 + 2.1.1 + 2.7 + 4.12 + 3.6.0 + 2.19.1 + diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java deleted file mode 100644 index 0472c2219e..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/AsyncFileAppenderUsingJsonLayoutTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.nio.file.Files; -import java.nio.file.Paths; - -import static org.junit.Assert.assertTrue; - -@RunWith(JUnit4.class) -public class AsyncFileAppenderUsingJsonLayoutTest { - @Rule - public LoggerContextRule contextRule = - new LoggerContextRule("log4j2-async-file-appender_json-layout.xml"); - - @Test - public void givenLoggerWithAsyncConfig_shouldLogToJsonFile() - throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - final int count = 88; - for (int i = 0; i < count; i++) { - logger.info("This is async JSON message #{} at INFO level.", count); - } - long logEventsCount = Files.lines(Paths.get("target/logfile.json")).count(); - assertTrue(logEventsCount > 0 && logEventsCount <= count); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java deleted file mode 100644 index 9831030d02..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingDefaultLayoutTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class ConsoleAppenderUsingDefaultLayoutTest { - @Test - public void givenLoggerWithDefaultConfig_shouldLogToConsole() - throws Exception { - Logger logger = LogManager.getLogger(getClass()); - Exception e = new RuntimeException("This is only a test!"); - logger.info("This is a simple message at INFO level. " + - "It will be hidden."); - logger.error("This is a simple message at ERROR level. " + - "This is the minimum visible level.", e); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java deleted file mode 100644 index 86b005538f..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/ConsoleAppenderUsingPatternLayoutWithColorsTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; -import org.apache.logging.log4j.ThreadContext; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class ConsoleAppenderUsingPatternLayoutWithColorsTest { - @Rule - public LoggerContextRule contextRule = - new LoggerContextRule("log4j2-console-appender_pattern-layout.xml"); - - @Test - public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors() - throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - logger.trace("This is a colored message at TRACE level."); - logger.debug("This is a colored message at DEBUG level. " + - "This is the minimum visible level."); - logger.info("This is a colored message at INFO level."); - logger.warn("This is a colored message at WARN level."); - Exception e = new RuntimeException("This is only a test!"); - logger.error("This is a colored message at ERROR level.", e); - logger.fatal("This is a colored message at FATAL level."); - } - - @Test - public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception { - Logger logger = contextRule.getLogger("ConnTrace"); - Marker appError = MarkerManager.getMarker("APP_ERROR"); - logger.error(appError, "This marker message at ERROR level should be hidden."); - Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE"); - logger.trace(connectionTrace, "This is a marker message at TRACE level."); - } - - @Test - public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception { - Logger logger = contextRule.getLogger("UserAudit"); - ThreadContext.put("userId", "1000"); - logger.info("This is a log-visible user login. Maybe from an admin account?"); - ThreadContext.put("userId", "1001"); - logger.info("This is a log-invisible user login."); - boolean b = true; - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java new file mode 100644 index 0000000000..d88a967562 --- /dev/null +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java @@ -0,0 +1,121 @@ +package com.baeldung.logging.log4j2.tests; + +import static org.junit.Assert.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.ResultSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.ThreadContext; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory; + +@RunWith(JUnit4.class) +public class CustomLoggingTest { + + @BeforeClass + public static void setup() throws Exception { + Connection connection = ConnectionFactory.getConnection(); + connection.createStatement() + .execute("CREATE TABLE logs(" + "when TIMESTAMP," + "logger VARCHAR(255)," + "level VARCHAR(255)," + "message VARCHAR(4096)," + "throwable TEXT)"); + connection.commit(); + } + + @Test + public void givenLoggerWithDefaultConfig_shouldLogToConsole() throws Exception { + Logger logger = LogManager.getLogger(getClass()); + Exception e = new RuntimeException("This is only a test!"); + logger.info("This is a simple message at INFO level. " + "It will be hidden."); + logger.error("This is a simple message at ERROR level. " + "This is the minimum visible level.", e); + } + + @Test + public void givenLoggerWithConsoleConfig_shouldLogToConsoleInColors() throws Exception { + Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER"); + logger.trace("This is a colored message at TRACE level."); + logger.debug("This is a colored message at DEBUG level. " + "This is the minimum visible level."); + logger.info("This is a colored message at INFO level."); + logger.warn("This is a colored message at WARN level."); + Exception e = new RuntimeException("This is only a test!"); + logger.error("This is a colored message at ERROR level.", e); + logger.fatal("This is a colored message at FATAL level."); + } + + @Test + public void givenLoggerWithConsoleConfig_shouldFilterByMarker() throws Exception { + Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_MARKER"); + Marker appError = MarkerManager.getMarker("APP_ERROR"); + logger.error(appError, "This marker message at ERROR level should be hidden."); + Marker connectionTrace = MarkerManager.getMarker("CONN_TRACE"); + logger.trace(connectionTrace, "This is a marker message at TRACE level."); + } + + @Test + public void givenLoggerWithConsoleConfig_shouldFilterByThreadContext() throws Exception { + Logger logger = LogManager.getLogger("CONSOLE_PATTERN_APPENDER_THREAD_CONTEXT"); + ThreadContext.put("userId", "1000"); + logger.info("This is a log-visible user login. Maybe from an admin account?"); + ThreadContext.put("userId", "1001"); + logger.info("This is a log-invisible user login."); + + } + + @Test + public void givenLoggerWithAsyncConfig_shouldLogToJsonFile() throws Exception { + Logger logger = LogManager.getLogger("ASYNC_JSON_FILE_APPENDER"); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is async JSON message #{} at INFO level.", count); + } + long logEventsCount = Files.lines(Paths.get("target/logfile.json")) + .count(); + assertTrue(logEventsCount > 0 && logEventsCount <= count); + } + + @Test + public void givenLoggerWithFailoverConfig_shouldLog() throws Exception { + Logger logger = LogManager.getLogger("FAIL_OVER_SYSLOG_APPENDER"); + logger.trace("This is a syslog message at TRACE level."); + logger.debug("This is a syslog message at DEBUG level."); + logger.info("This is a syslog message at INFO level. This is the minimum visible level."); + logger.warn("This is a syslog message at WARN level."); + Exception e = new RuntimeException("This is only a test!"); + logger.error("This is a syslog message at ERROR level.", e); + logger.fatal("This is a syslog message at FATAL level."); + } + + @Test + public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception { + Logger logger = LogManager.getLogger("JDBC_APPENDER"); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is JDBC message #{} at INFO level.", count); + } + Connection connection = ConnectionFactory.getConnection(); + ResultSet resultSet = connection.createStatement() + .executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs"); + int logCount = 0; + if (resultSet.next()) { + logCount = resultSet.getInt("ROW_COUNT"); + } + assertTrue(logCount == count); + } + + @Test + public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception { + Logger logger = LogManager.getLogger("XML_ROLLING_FILE_APPENDER"); + final int count = 88; + for (int i = 0; i < count; i++) { + logger.info("This is rolling file XML message #{} at INFO level.", i); + } + } + +} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java deleted file mode 100644 index 0653394e5a..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/FailoverSyslogConsoleAppenderTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) -public class FailoverSyslogConsoleAppenderTest { - @Rule - public LoggerContextRule contextRule = - new LoggerContextRule("log4j2-failover-syslog-console-appender_pattern-layout.xml"); - - @Test - public void givenLoggerWithFailoverConfig_shouldLog() throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - logger.trace("This is a syslog message at TRACE level."); - logger.debug("This is a syslog message at DEBUG level."); - logger.info("This is a syslog message at INFO level. This is the minimum visible level."); - logger.warn("This is a syslog message at WARN level."); - Exception e = new RuntimeException("This is only a test!"); - logger.error("This is a syslog message at ERROR level.", e); - logger.fatal("This is a syslog message at FATAL level."); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java deleted file mode 100644 index 1b8d33e2bf..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JDBCAppenderTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import com.baeldung.logging.log4j2.tests.jdbc.ConnectionFactory; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.sql.Connection; -import java.sql.ResultSet; - -import static org.junit.Assert.assertTrue; - -@RunWith(JUnit4.class) -public class JDBCAppenderTest { - @Rule - public LoggerContextRule contextRule = new LoggerContextRule("log4j2-jdbc-appender.xml"); - - @BeforeClass - public static void setup() throws Exception { - Connection connection = ConnectionFactory.getConnection(); - connection.createStatement() - .execute("CREATE TABLE logs(" + - "when TIMESTAMP," + - "logger VARCHAR(255)," + - "level VARCHAR(255)," + - "message VARCHAR(4096)," + - "throwable TEXT)"); - //connection.commit(); - } - - @Test - public void givenLoggerWithJdbcConfig_shouldLogToDataSource() throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - final int count = 88; - for (int i = 0; i < count; i++) { - logger.info("This is JDBC message #{} at INFO level.", count); - } - Connection connection = ConnectionFactory.getConnection(); - ResultSet resultSet = connection.createStatement() - .executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs"); - int logCount = 0; - if (resultSet.next()) { - logCount = resultSet.getInt("ROW_COUNT"); - } - assertTrue(logCount == count); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java deleted file mode 100644 index 3ab69d263c..0000000000 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/RollingFileAppenderUsingXMLLayoutTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.logging.log4j2.tests; - -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.junit.LoggerContextRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertTrue; - -@RunWith(JUnit4.class) -public class RollingFileAppenderUsingXMLLayoutTest { - @Rule - public LoggerContextRule contextRule = - new LoggerContextRule("log4j2-rolling-file-appender_xml-layout.xml"); - - @Test - public void givenLoggerWithRollingFileConfig_shouldLogToXMLFile() throws Exception { - Logger logger = contextRule.getLogger(getClass().getSimpleName()); - final int count = 88; - for (int i = 0; i < count; i++) { - logger.info("This is rolling file XML message #{} at INFO level.", i); - } - String[] logEvents = Files.readAllLines(Paths.get("target/logfile.xml")).stream() - .collect(Collectors.joining(System.lineSeparator())) - .split("\\n\\n+"); - assertTrue(logEvents.length == 39); - } -} diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java index 73b323f335..cc594f293c 100644 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java @@ -2,7 +2,6 @@ package com.baeldung.logging.log4j2.tests.jdbc; import org.apache.commons.dbcp2.BasicDataSource; import org.h2.Driver; - import java.sql.Connection; import java.sql.SQLException; diff --git a/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml b/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml deleted file mode 100644 index c291eacd59..0000000000 --- a/log4j2/src/test/resources/log4j2-async-file-appender_json-layout.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml b/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml deleted file mode 100644 index d6621f9166..0000000000 --- a/log4j2/src/test/resources/log4j2-console-appender_pattern-layout.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml b/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml deleted file mode 100644 index 62ba37f28c..0000000000 --- a/log4j2/src/test/resources/log4j2-failover-syslog-console-appender_pattern-layout.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml b/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml index c2b9c65430..fd61e4581f 100644 --- a/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml +++ b/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml @@ -1,4 +1,5 @@ - + diff --git a/log4j2/src/test/resources/log4j2-jdbc-appender.xml b/log4j2/src/test/resources/log4j2-jdbc-appender.xml deleted file mode 100644 index 6b50f7d5a4..0000000000 --- a/log4j2/src/test/resources/log4j2-jdbc-appender.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml b/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml deleted file mode 100644 index 9de1a29186..0000000000 --- a/log4j2/src/test/resources/log4j2-rolling-file-appender_xml-layout.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/log4j2/src/test/resources/log4j2.xml b/log4j2/src/test/resources/log4j2.xml index 8f7608aa78..83c1184f1f 100644 --- a/log4j2/src/test/resources/log4j2.xml +++ b/log4j2/src/test/resources/log4j2.xml @@ -1,13 +1,69 @@ - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + - + \ No newline at end of file From fae4d381c1b4662f86918f45423698533bbc7461 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Mon, 20 Feb 2017 08:51:46 -0600 Subject: [PATCH 16/23] Update README.md --- spring-mvc-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 575e4f583e..4d3e58558b 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -20,3 +20,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) +- [Uploading and Displaying Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) From 99dbc3efd11ba5567b6f3e8ab30922506febbf09 Mon Sep 17 00:00:00 2001 From: slavisa-baeldung Date: Mon, 20 Feb 2017 20:03:32 +0100 Subject: [PATCH 17/23] BAEL-41 - Log4j 2 appenders, layout, filters --- .../baeldung/logging/log4j2/tests/CustomLoggingTest.java | 7 ++++--- .../logging/log4j2/tests/jdbc/ConnectionFactory.java | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java index d88a967562..1562b67068 100644 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingTest.java @@ -6,6 +6,7 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Connection; import java.sql.ResultSet; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -25,7 +26,7 @@ public class CustomLoggingTest { public static void setup() throws Exception { Connection connection = ConnectionFactory.getConnection(); connection.createStatement() - .execute("CREATE TABLE logs(" + "when TIMESTAMP," + "logger VARCHAR(255)," + "level VARCHAR(255)," + "message VARCHAR(4096)," + "throwable TEXT)"); + .execute("CREATE TABLE logs(" + "when TIMESTAMP," + "logger VARCHAR(255)," + "level VARCHAR(255)," + "message VARCHAR(4096)," + "throwable TEXT)"); connection.commit(); } @@ -76,7 +77,7 @@ public class CustomLoggingTest { logger.info("This is async JSON message #{} at INFO level.", count); } long logEventsCount = Files.lines(Paths.get("target/logfile.json")) - .count(); + .count(); assertTrue(logEventsCount > 0 && logEventsCount <= count); } @@ -101,7 +102,7 @@ public class CustomLoggingTest { } Connection connection = ConnectionFactory.getConnection(); ResultSet resultSet = connection.createStatement() - .executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs"); + .executeQuery("SELECT COUNT(*) AS ROW_COUNT FROM logs"); int logCount = 0; if (resultSet.next()) { logCount = resultSet.getInt("ROW_COUNT"); diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java index cc594f293c..73b323f335 100644 --- a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java +++ b/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java @@ -2,6 +2,7 @@ package com.baeldung.logging.log4j2.tests.jdbc; import org.apache.commons.dbcp2.BasicDataSource; import org.h2.Driver; + import java.sql.Connection; import java.sql.SQLException; From 494d6d57e1ee74b2a6699da15c3fcdb67fe08984 Mon Sep 17 00:00:00 2001 From: GuenHamza Date: Mon, 20 Feb 2017 22:17:08 +0000 Subject: [PATCH 18/23] Add Cobertura Plugin configuration (#1185) --- algorithms/pom.xml | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/algorithms/pom.xml b/algorithms/pom.xml index 0c85a19534..f72457650a 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -41,4 +41,23 @@
- \ No newline at end of file + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.7 + + + + com/baeldung/algorithms/dijkstra/* + + + com/baeldung/algorithms/dijkstra/* + + + + + + + From fda362f79d114473afba5e82698299fce3c111e1 Mon Sep 17 00:00:00 2001 From: Andrew Evans Date: Mon, 20 Feb 2017 15:17:48 -0700 Subject: [PATCH 19/23] Spring Groovy Config with fixed pom (#1200) * 'bean_injection' * 'bean_injection' * 'changes' * code * git ignore * pom fix * pom fix --- .../com/baeldung/annotationinjection/App.java | 48 +++++++++++++ .../annotationinjection/AppConfig.java | 23 +++++++ .../baeldung/annotationinjection/AppTest.java | 52 ++++++++++++++ .../annotationinjection/AutowireObject.java | 6 ++ .../annotationinjection/ImportConfig.java | 20 ++++++ .../annotationinjection/InjectedClass.java | 39 +++++++++++ spring-groovy-config/.gitignore | 1 + .../org.eclipse.core.resources.prefs | 4 ++ .../.settings/org.eclipse.jdt.core.prefs | 5 ++ .../org.eclipse.jdt.groovy.core.prefs | 2 + .../.settings/org.eclipse.m2e.core.prefs | 4 ++ .../groovyContextWithConstructor.groovy | 9 +++ .../config/groovyPropConfig.groovy | 5 ++ .../config/groovyPropConfigWithClosure.groovy | 8 +++ .../config/groovyTestWithRefBean.groovy | 10 +++ spring-groovy-config/pom.xml | 67 +++++++++++++++++++ .../spring_groovy_config/ClassWithRef.java | 18 +++++ .../spring_groovy_config/GroovyClass.groovy | 9 +++ .../spring_groovy_config/MainApp.java | 14 ++++ .../spring_groovy_config/TestClass.java | 22 ++++++ .../spring_groovy_config/TestClassB.java | 26 +++++++ .../spring_groovy_config/AppTest.java | 57 ++++++++++++++++ 22 files changed, 449 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/App.java create mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/AppConfig.java create mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/AppTest.java create mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/AutowireObject.java create mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/ImportConfig.java create mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/InjectedClass.java create mode 100644 spring-groovy-config/.gitignore create mode 100644 spring-groovy-config/.settings/org.eclipse.core.resources.prefs create mode 100644 spring-groovy-config/.settings/org.eclipse.jdt.core.prefs create mode 100644 spring-groovy-config/.settings/org.eclipse.jdt.groovy.core.prefs create mode 100644 spring-groovy-config/.settings/org.eclipse.m2e.core.prefs create mode 100644 spring-groovy-config/config/groovyContextWithConstructor.groovy create mode 100644 spring-groovy-config/config/groovyPropConfig.groovy create mode 100644 spring-groovy-config/config/groovyPropConfigWithClosure.groovy create mode 100644 spring-groovy-config/config/groovyTestWithRefBean.groovy create mode 100644 spring-groovy-config/pom.xml create mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/ClassWithRef.java create mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/GroovyClass.groovy create mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/MainApp.java create mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClass.java create mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClassB.java create mode 100644 spring-groovy-config/src/test/java/com/baeldung/spring_groovy_config/AppTest.java diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/App.java b/spring-core/src/main/java/com/baeldung/annotationinjection/App.java new file mode 100644 index 0000000000..dc9560286d --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/annotationinjection/App.java @@ -0,0 +1,48 @@ +package com.baeldung.java_bean_injection; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.java_bean_injection.*; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + + +import junit.framework.TestResult; +import junit.framework.TestFailure; + +import java.util.Enumeration; + + +/** + * Bean Injection Test Application + * + */ +public class App +{ + public static void main( String[] args ) + { + + TestResult result = new TestResult(); + AppTest.suite().run(result); + System.out.println(String.format("Tests: %d",result.runCount())); + System.out.println(String.format("Errors: %d",result.errorCount())); + System.out.println(String.format("Failures: %d",result.failureCount())); + if(result.failureCount() > 0){ + Enumeration failures = result.failures(); + int failNum = 0; + TestFailure failure = null; + while(failures.hasMoreElements()){ + failure = failures.nextElement(); + + System.out.println(failure.exceptionMessage()); + System.out.println(String.format("Test Failure %d\n",failNum)); + System.out.println(failure.trace()); + System.out.print("\n"); + } + } + + } +} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/AppConfig.java b/spring-core/src/main/java/com/baeldung/annotationinjection/AppConfig.java new file mode 100644 index 0000000000..138bda6b1b --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/annotationinjection/AppConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.java_bean_injection; + +import org.springframework.beans.factory.annotation.*; +import org.springframework.context.annotation.*; +import org.springframework.stereotype.*; + +import com.baeldung.java_bean_injection.*; + +@Configuration +@PropertySource(value="classpath:inject.properties") +@Import(ImportConfig.class) +public class AppConfig { + @Value("${contructor.arg1}") String constructorArg; + + @Bean + public InjectedClass injectedClass(){ + InjectedClass ic = new InjectedClass(constructorArg); + ic.setMyInt(10); + ic.setTestString("test"); + return ic; + } + +} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/AppTest.java b/spring-core/src/main/java/com/baeldung/annotationinjection/AppTest.java new file mode 100644 index 0000000000..fa7b46f06b --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/annotationinjection/AppTest.java @@ -0,0 +1,52 @@ +package com.baeldung.java_bean_injection; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.java_bean_injection.*; + +import java.io.File; +import java.util.Scanner; + +/** + * Unit test for simple App. + */ +public class AppTest extends TestCase{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(); + context.register(AppConfig.class); + context.refresh(); + InjectedClass injectedClass = (InjectedClass) context.getBean(InjectedClass.class); + assertTrue(injectedClass.getMyInt() == 10); + assertTrue(injectedClass.getTestString().equals("test")); + assertNotNull(injectedClass.obj); + assertTrue(injectedClass.myConstructorArg.equals("test")); + } +} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/AutowireObject.java b/spring-core/src/main/java/com/baeldung/annotationinjection/AutowireObject.java new file mode 100644 index 0000000000..df5859f0af --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/annotationinjection/AutowireObject.java @@ -0,0 +1,6 @@ +package com.baeldung.java_bean_injection; + + +public class AutowireObject { + +} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/ImportConfig.java b/spring-core/src/main/java/com/baeldung/annotationinjection/ImportConfig.java new file mode 100644 index 0000000000..e37d94931b --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/annotationinjection/ImportConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.java_bean_injection; + +import org.springframework.context.annotation.*; + +import com.baeldung.java_bean_injection.*; + +@Configuration +public class ImportConfig { + + @Bean(name="autobean") + public AutowireObject autowireObject(){ + return new AutowireObject(); + } + + + @Bean(name="autobean2") + public AutowireObject autowireObject2(){ + return new AutowireObject(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/InjectedClass.java b/spring-core/src/main/java/com/baeldung/annotationinjection/InjectedClass.java new file mode 100644 index 0000000000..55fe733db5 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/annotationinjection/InjectedClass.java @@ -0,0 +1,39 @@ +package com.baeldung.java_bean_injection; + +import org.springframework.beans.factory.annotation.*; +import org.springframework.context.annotation.*; + +import com.baeldung.java_bean_injection.*; + + +public class InjectedClass { + private int myInt; + private String testString; + String myConstructorArg; + + + @Autowired + @Qualifier("autobean") + AutowireObject obj; + + public InjectedClass(String constArg){ + this.myConstructorArg = constArg; + } + + public void setMyInt(int myInt){ + this.myInt = myInt; + } + + public void setTestString(String testString){ + this.testString = testString; + } + + public int getMyInt(){ + return this.myInt; + } + + public String getTestString(){ + return this.testString; + } + +} diff --git a/spring-groovy-config/.gitignore b/spring-groovy-config/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/spring-groovy-config/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/spring-groovy-config/.settings/org.eclipse.core.resources.prefs b/spring-groovy-config/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000000..f9fe34593f --- /dev/null +++ b/spring-groovy-config/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/spring-groovy-config/.settings/org.eclipse.jdt.core.prefs b/spring-groovy-config/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..abec6ca389 --- /dev/null +++ b/spring-groovy-config/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/spring-groovy-config/.settings/org.eclipse.jdt.groovy.core.prefs b/spring-groovy-config/.settings/org.eclipse.jdt.groovy.core.prefs new file mode 100644 index 0000000000..ae98feaa79 --- /dev/null +++ b/spring-groovy-config/.settings/org.eclipse.jdt.groovy.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +groovy.compiler.level=24 diff --git a/spring-groovy-config/.settings/org.eclipse.m2e.core.prefs b/spring-groovy-config/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000000..f897a7f1cb --- /dev/null +++ b/spring-groovy-config/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/spring-groovy-config/config/groovyContextWithConstructor.groovy b/spring-groovy-config/config/groovyContextWithConstructor.groovy new file mode 100644 index 0000000000..dbde5f3822 --- /dev/null +++ b/spring-groovy-config/config/groovyContextWithConstructor.groovy @@ -0,0 +1,9 @@ +import com.baeldung.spring_groovy_config.TestClass + +beans{ + testString String, 'Test String' + testClass(TestClass){ + beanDefinition -> + beanDefinition.constructorArgs = ["Test String",10.2] + } +} \ No newline at end of file diff --git a/spring-groovy-config/config/groovyPropConfig.groovy b/spring-groovy-config/config/groovyPropConfig.groovy new file mode 100644 index 0000000000..08d3acf354 --- /dev/null +++ b/spring-groovy-config/config/groovyPropConfig.groovy @@ -0,0 +1,5 @@ +import com.baeldung.spring_groovy_config.TestClassB + +beans{ + testClassB(TestClassB,testStringB:"Test String",testIntB:10.2) +} \ No newline at end of file diff --git a/spring-groovy-config/config/groovyPropConfigWithClosure.groovy b/spring-groovy-config/config/groovyPropConfigWithClosure.groovy new file mode 100644 index 0000000000..3ca306bdd7 --- /dev/null +++ b/spring-groovy-config/config/groovyPropConfigWithClosure.groovy @@ -0,0 +1,8 @@ +import com.baeldung.spring_groovy_config.TestClassB + +beans{ + testClassB(TestClassB){ + testStringB = "Test String" + testIntB = 10 + } +} \ No newline at end of file diff --git a/spring-groovy-config/config/groovyTestWithRefBean.groovy b/spring-groovy-config/config/groovyTestWithRefBean.groovy new file mode 100644 index 0000000000..d079480d46 --- /dev/null +++ b/spring-groovy-config/config/groovyTestWithRefBean.groovy @@ -0,0 +1,10 @@ +import com.baeldung.spring_groovy_config.GroovyClass +import com.baeldung.spring_groovy_config.ClassWithRef + +beans{ + groovyClass(GroovyClass, groovyInt:5) + classWithRef(ClassWithRef){ + myClass = groovyClass + } + +} \ No newline at end of file diff --git a/spring-groovy-config/pom.xml b/spring-groovy-config/pom.xml new file mode 100644 index 0000000000..f6c63ae232 --- /dev/null +++ b/spring-groovy-config/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + com.baeldung + spring-groovy-config + 0.0.1-SNAPSHOT + jar + spring-groovy-config + http://maven.apache.org + + UTF-8 + + + + + maven-compiler-plugin + + 3.1 + + groovy-eclipse-compiler + + + + org.codehaus.groovy + groovy-eclipse-compiler + 2.9.1-01 + + + + org.codehaus.groovy + groovy-eclipse-batch + 2.3.7-01 + + + + + + + + org.codehaus.groovy + groovy-all + 2.4.8 + + + junit + junit + 4.12 + test + + + org.springframework + spring-context + 4.3.6.RELEASE + + + org.springframework + spring-core + 4.3.6.RELEASE + + + org.springframework + spring-test + 4.3.6.RELEASE + + + + diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/ClassWithRef.java b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/ClassWithRef.java new file mode 100644 index 0000000000..ec8987f387 --- /dev/null +++ b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/ClassWithRef.java @@ -0,0 +1,18 @@ +package com.baeldung.spring_groovy_config; + +import org.springframework.stereotype.Component; + +import com.baeldung.spring_groovy_config.GroovyClass; + +@Component +public class ClassWithRef { + private GroovyClass myClass = null; + + public void setMyClass(GroovyClass myClass){ + this.myClass = myClass; + } + + public GroovyClass getMyClass(){ + return this.myClass; + } +} diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/GroovyClass.groovy b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/GroovyClass.groovy new file mode 100644 index 0000000000..2a1ef6a2c5 --- /dev/null +++ b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/GroovyClass.groovy @@ -0,0 +1,9 @@ +package com.baeldung.spring_groovy_config + +class GroovyClass { + int groovyInt = 0 + + def getGroovyInt(){ + return groovyInt + } +} diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/MainApp.java b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/MainApp.java new file mode 100644 index 0000000000..ac85963cf7 --- /dev/null +++ b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/MainApp.java @@ -0,0 +1,14 @@ +package com.baeldung.spring_groovy_config; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.GenericGroovyApplicationContext; + +public class MainApp { + public static void main(String[] args){ + ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyTestWithRefBean.groovy"); + ClassWithRef test = (ClassWithRef) context.getBean("classWithRef"); + } +} diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClass.java b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClass.java new file mode 100644 index 0000000000..75b6b5fc5b --- /dev/null +++ b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClass.java @@ -0,0 +1,22 @@ +package com.baeldung.spring_groovy_config; + +import org.springframework.stereotype.Component; + +@Component +public class TestClass { + private String testString; + private double testDouble; + + public TestClass(String testString, double testDouble){ + this.testString = testString; + this.testDouble = testDouble; + } + + public String getTestString(){ + return this.testString; + } + + public double getTestDouble(){ + return this.testDouble; + } +} diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClassB.java b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClassB.java new file mode 100644 index 0000000000..d2387c87e5 --- /dev/null +++ b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClassB.java @@ -0,0 +1,26 @@ +package com.baeldung.spring_groovy_config; + +import org.springframework.stereotype.Component; + +@Component +public class TestClassB { + private String testStringB; + private int testIntB; + + public void setTestStringB(String testStringB){ + this.testStringB = testStringB; + } + + public String getTestStringB(){ + return this.testStringB; + } + + + public void setTestIntB(int testIntB){ + this.testIntB = testIntB; + } + + public int getTestIntB(){ + return this.testIntB; + } +} diff --git a/spring-groovy-config/src/test/java/com/baeldung/spring_groovy_config/AppTest.java b/spring-groovy-config/src/test/java/com/baeldung/spring_groovy_config/AppTest.java new file mode 100644 index 0000000000..93de401e0c --- /dev/null +++ b/spring-groovy-config/src/test/java/com/baeldung/spring_groovy_config/AppTest.java @@ -0,0 +1,57 @@ +package com.baeldung.spring_groovy_config; + +import com.baeldung.spring_groovy_config.*; +import groovy.lang.Binding; +import junit.framework.TestCase; +import static org.junit.Assert.*; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.context.support.GenericGroovyApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; +/** + * Spring Framework Tests for Groovy. + */ +public class AppTest{ + + @Test + public void testSimple(){ + ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyContextWithConstructor.groovy"); + TestClass test = (TestClass) context.getBean("testClass"); + assertNotNull(test.getTestString()); + assertEquals(test.getTestString(),"Test String"); + assertTrue(test.getTestDouble() == 10.2); + + String testString = context.getBean("testString",String.class); + assertEquals(testString,"Test String"); + } + + + @Test + public void testProperties(){ + ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyPropConfig.groovy"); + TestClassB test = (TestClassB) context.getBean("testClassB"); + assertNotNull(test.getTestStringB()); + assertEquals(test.getTestStringB(),"Test String"); + assertTrue(test.getTestIntB() == 10); + } + + @Test + public void testPropertiesWithClosure(){ + ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyPropConfigWithClosure.groovy"); + TestClassB test = (TestClassB) context.getBean("testClassB"); + assertNotNull(test.getTestStringB()); + assertEquals(test.getTestStringB(),"Test String"); + assertTrue(test.getTestIntB() == 10); + } + + + @Test + public void testWithRef(){ + ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyTestWithRefBean.groovy"); + ClassWithRef test = (ClassWithRef) context.getBean("classWithRef"); + assertEquals(test.getMyClass().getGroovyInt(),5); + } +} From 3371c9047a3d7d704ff0583dd4551a40be89183e Mon Sep 17 00:00:00 2001 From: Nancy Bosecker Date: Mon, 20 Feb 2017 17:28:16 -0800 Subject: [PATCH 20/23] Moved code to apache-solrj from spring-data-solr, updated code to 6.4.0 solrj, fixed dependencies in both modules (#1196) * Solr w Apache SolrJ * Solr w Apache SolrJ * updated test names and moved add to @before method * create apache-solrj module, moved code from spring-data-solr --- apache-solrj/pom.xml | 50 +++++++++++++++++++ .../solrjava/SolrJavaIntegration.java | 43 ++++++++++++++++ .../solrjava/SolrJavaIntegrationTest.java | 24 +++------ pom.xml | 1 + spring-data-solr/pom.xml | 6 --- 5 files changed, 100 insertions(+), 24 deletions(-) create mode 100644 apache-solrj/pom.xml create mode 100644 apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java rename {spring-data-solr => apache-solrj}/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java (64%) diff --git a/apache-solrj/pom.xml b/apache-solrj/pom.xml new file mode 100644 index 0000000000..74daeae55c --- /dev/null +++ b/apache-solrj/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + com.baeldung + apache-solrj + 0.0.1-SNAPSHOT + jar + apache-solrj + + + 4.12 + 2.19.1 + + + + + org.apache.solr + solr-solrj + 6.4.0 + + + junit + junit + ${junit.version} + test + + + + + + + maven-compiler-plugin + 2.3.2 + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 1.8 + 1.8 + + **/*IntegrationTest.java + **/*LiveTest.java + + + + + + \ No newline at end of file diff --git a/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java b/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java new file mode 100644 index 0000000000..f2d21f0993 --- /dev/null +++ b/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java @@ -0,0 +1,43 @@ +package com.baeldung.solrjava; + +import java.io.IOException; + +import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.impl.HttpSolrClient; +import org.apache.solr.client.solrj.impl.XMLResponseParser; +import org.apache.solr.common.SolrInputDocument; + +public class SolrJavaIntegration { + + private HttpSolrClient solrClient; + + public SolrJavaIntegration(String clientUrl) { + + solrClient = new HttpSolrClient.Builder(clientUrl).build(); + solrClient.setParser(new XMLResponseParser()); + } + + public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException { + + SolrInputDocument document = new SolrInputDocument(); + document.addField("id", documentId); + document.addField("name", itemName); + document.addField("price", itemPrice); + solrClient.add(document); + solrClient.commit(); + } + + public void deleteSolrDocument(String documentId) throws SolrServerException, IOException { + + solrClient.deleteById(documentId); + solrClient.commit(); + } + + protected HttpSolrClient getSolrClient() { + return solrClient; + } + + protected void setSolrClient(HttpSolrClient solrClient) { + this.solrClient = solrClient; + } +} diff --git a/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java similarity index 64% rename from spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java rename to apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java index ce90ccaf16..22f9eae8ee 100644 --- a/spring-data-solr/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java +++ b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java @@ -6,32 +6,21 @@ import java.io.IOException; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; -import org.apache.solr.client.solrj.impl.HttpSolrClient; -import org.apache.solr.client.solrj.impl.XMLResponseParser; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; -import org.apache.solr.common.SolrInputDocument; import org.junit.Before; import org.junit.Test; public class SolrJavaIntegrationTest { - private HttpSolrClient solr; - private SolrInputDocument document; + private SolrJavaIntegration solrJavaIntegration; @Before public void setUp() throws Exception { - solr = new HttpSolrClient("http://localhost:8983/solr/bigboxstore"); - solr.setParser(new XMLResponseParser()); - - document = new SolrInputDocument(); - document.addField("id", "123456"); - document.addField("name", "Kenmore Dishwasher"); - document.addField("price", "599.99"); - solr.add(document); - solr.commit(); + solrJavaIntegration = new SolrJavaIntegration("http://localhost:8983/solr/bigboxstore"); + solrJavaIntegration.addSolrDocument("123456", "Kenmore Dishwasher", "599.99"); } @Test @@ -41,7 +30,7 @@ public class SolrJavaIntegrationTest { query.set("q", "id:123456"); QueryResponse response = null; - response = solr.query(query); + response = solrJavaIntegration.getSolrClient().query(query); SolrDocumentList docList = response.getResults(); assertEquals(docList.getNumFound(), 1); @@ -55,14 +44,13 @@ public class SolrJavaIntegrationTest { @Test public void whenDelete_thenVerifyDeleted() throws SolrServerException, IOException { - solr.deleteById("123456"); - solr.commit(); + solrJavaIntegration.deleteSolrDocument("123456"); SolrQuery query = new SolrQuery(); query.set("q", "id:123456"); QueryResponse response = null; - response = solr.query(query); + response = solrJavaIntegration.getSolrClient().query(query); SolrDocumentList docList = response.getResults(); assertEquals(docList.getNumFound(), 0); diff --git a/pom.xml b/pom.xml index 82df776044..aa58b1d2e9 100644 --- a/pom.xml +++ b/pom.xml @@ -194,6 +194,7 @@ struts2 apache-velocity + apache-solrj diff --git a/spring-data-solr/pom.xml b/spring-data-solr/pom.xml index 2aa9f86a96..e43b3ff774 100644 --- a/spring-data-solr/pom.xml +++ b/spring-data-solr/pom.xml @@ -51,12 +51,6 @@ ${spring.version} test
- From a75ed7e70ac5f7ec46b372661d015200da20a9c6 Mon Sep 17 00:00:00 2001 From: Daniele Demichelis Date: Tue, 21 Feb 2017 04:38:52 +0100 Subject: [PATCH 21/23] BAEL-554 Spring Remoting with Hessian and Burlap (#1166) * Burlap & Hessian server added * Burlap & Hessian client work * Fixed main * Fixed formatting --- spring-remoting/pom.xml | 12 +++--- .../remoting-hessian-burlap/client/pom.xml | 35 ++++++++++++++++++ .../com/baeldung/client/BurlapClient.java | 28 ++++++++++++++ .../com/baeldung/client/HessianClient.java | 28 ++++++++++++++ .../remoting-hessian-burlap/pom.xml | 20 ++++++++++ .../remoting-hessian-burlap/server/pom.xml | 30 +++++++++++++++ .../main/java/com/baeldung/server/Server.java | 37 +++++++++++++++++++ 7 files changed, 185 insertions(+), 5 deletions(-) create mode 100644 spring-remoting/remoting-hessian-burlap/client/pom.xml create mode 100644 spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java create mode 100644 spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java create mode 100644 spring-remoting/remoting-hessian-burlap/pom.xml create mode 100644 spring-remoting/remoting-hessian-burlap/server/pom.xml create mode 100644 spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index a43dd52a3e..52d670a726 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -3,16 +3,17 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung + spring-remoting + pom + 1.0-SNAPSHOT + spring-remoting + Parent for all projects related to Spring Remoting. org.springframework.boot spring-boot-starter-parent 1.4.3.RELEASE - com.baeldung - spring-remoting - 1.0-SNAPSHOT - Parent for all projects related to Spring Remoting. - pom 1.8 @@ -34,6 +35,7 @@ remoting-http + remoting-hessian-burlap \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/pom.xml b/spring-remoting/remoting-hessian-burlap/client/pom.xml new file mode 100644 index 0000000000..11250e63d2 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/client/pom.xml @@ -0,0 +1,35 @@ + + + + remoting-hessian-burlap + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + spring-remoting-hessian-burlap-client + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + ${project.groupId} + api + + + com.caucho + hessian + 4.0.38 + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java b/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java new file mode 100644 index 0000000000..477c29eb26 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/BurlapClient.java @@ -0,0 +1,28 @@ +package com.baeldung.client; + +import com.baeldung.api.BookingException; +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.caucho.BurlapProxyFactoryBean; + +import static java.lang.System.out; + +@Configuration +public class BurlapClient { + + @Bean + public BurlapProxyFactoryBean burlapInvoker() { + BurlapProxyFactoryBean invoker = new BurlapProxyFactoryBean(); + invoker.setServiceUrl("http://localhost:8080/b_booking"); + invoker.setServiceInterface(CabBookingService.class); + return invoker; + } + + public static void main(String[] args) throws BookingException { + CabBookingService service = SpringApplication.run(BurlapClient.class, args).getBean(CabBookingService.class); + out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); + } + +} diff --git a/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java b/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java new file mode 100644 index 0000000000..b5f366094e --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/client/src/main/java/com/baeldung/client/HessianClient.java @@ -0,0 +1,28 @@ +package com.baeldung.client; + +import com.baeldung.api.BookingException; +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.caucho.HessianProxyFactoryBean; + +import static java.lang.System.out; + +@Configuration +public class HessianClient { + + @Bean + public HessianProxyFactoryBean hessianInvoker() { + HessianProxyFactoryBean invoker = new HessianProxyFactoryBean(); + invoker.setServiceUrl("http://localhost:8080/booking"); + invoker.setServiceInterface(CabBookingService.class); + return invoker; + } + + public static void main(String[] args) throws BookingException { + CabBookingService service = SpringApplication.run(HessianClient.class, args).getBean(CabBookingService.class); + out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); + } + +} diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml new file mode 100644 index 0000000000..682e460880 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -0,0 +1,20 @@ + + + + spring-remoting + com.baeldung + 1.0-SNAPSHOT + + pom + + server + client + + 4.0.0 + + remoting-hessian-burlap + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/server/pom.xml b/spring-remoting/remoting-hessian-burlap/server/pom.xml new file mode 100644 index 0000000000..c97092b247 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/server/pom.xml @@ -0,0 +1,30 @@ + + + + remoting-hessian-burlap + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + remoting-hessian-burlap-server + + + + com.baeldung + spring-remoting-http-server + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-web + + + com.caucho + hessian + 4.0.38 + + + \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java b/spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java new file mode 100644 index 0000000000..9b7e463871 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/server/src/main/java/com/baeldung/server/Server.java @@ -0,0 +1,37 @@ +package com.baeldung.server; + +import com.baeldung.api.CabBookingService; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.remoting.caucho.BurlapServiceExporter; +import org.springframework.remoting.caucho.HessianServiceExporter; +import org.springframework.remoting.support.RemoteExporter; + +@Configuration @ComponentScan @EnableAutoConfiguration public class Server { + + @Bean CabBookingService bookingService() { + return new CabBookingServiceImpl(); + } + + @Bean(name = "/booking") RemoteExporter hessianService(CabBookingService service) { + HessianServiceExporter exporter = new HessianServiceExporter(); + exporter.setService(bookingService()); + exporter.setServiceInterface(CabBookingService.class); + return exporter; + } + + @Bean(name = "/b_booking") RemoteExporter burlapService(CabBookingService service) { + BurlapServiceExporter exporter = new BurlapServiceExporter(); + exporter.setService(bookingService()); + exporter.setServiceInterface(CabBookingService.class); + return exporter; + } + + public static void main(String[] args) { + SpringApplication.run(Server.class, args); + } + +} \ No newline at end of file From d3d11a18f3d05e37ddd284cb6b4b2c06283c7a0f Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Tue, 21 Feb 2017 07:35:07 +0100 Subject: [PATCH 22/23] Revert "Spring Groovy Config with fixed pom" (#1209) --- .../com/baeldung/annotationinjection/App.java | 48 ------------- .../annotationinjection/AppConfig.java | 23 ------- .../baeldung/annotationinjection/AppTest.java | 52 -------------- .../annotationinjection/AutowireObject.java | 6 -- .../annotationinjection/ImportConfig.java | 20 ------ .../annotationinjection/InjectedClass.java | 39 ----------- spring-groovy-config/.gitignore | 1 - .../org.eclipse.core.resources.prefs | 4 -- .../.settings/org.eclipse.jdt.core.prefs | 5 -- .../org.eclipse.jdt.groovy.core.prefs | 2 - .../.settings/org.eclipse.m2e.core.prefs | 4 -- .../groovyContextWithConstructor.groovy | 9 --- .../config/groovyPropConfig.groovy | 5 -- .../config/groovyPropConfigWithClosure.groovy | 8 --- .../config/groovyTestWithRefBean.groovy | 10 --- spring-groovy-config/pom.xml | 67 ------------------- .../spring_groovy_config/ClassWithRef.java | 18 ----- .../spring_groovy_config/GroovyClass.groovy | 9 --- .../spring_groovy_config/MainApp.java | 14 ---- .../spring_groovy_config/TestClass.java | 22 ------ .../spring_groovy_config/TestClassB.java | 26 ------- .../spring_groovy_config/AppTest.java | 57 ---------------- 22 files changed, 449 deletions(-) delete mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/App.java delete mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/AppConfig.java delete mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/AppTest.java delete mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/AutowireObject.java delete mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/ImportConfig.java delete mode 100644 spring-core/src/main/java/com/baeldung/annotationinjection/InjectedClass.java delete mode 100644 spring-groovy-config/.gitignore delete mode 100644 spring-groovy-config/.settings/org.eclipse.core.resources.prefs delete mode 100644 spring-groovy-config/.settings/org.eclipse.jdt.core.prefs delete mode 100644 spring-groovy-config/.settings/org.eclipse.jdt.groovy.core.prefs delete mode 100644 spring-groovy-config/.settings/org.eclipse.m2e.core.prefs delete mode 100644 spring-groovy-config/config/groovyContextWithConstructor.groovy delete mode 100644 spring-groovy-config/config/groovyPropConfig.groovy delete mode 100644 spring-groovy-config/config/groovyPropConfigWithClosure.groovy delete mode 100644 spring-groovy-config/config/groovyTestWithRefBean.groovy delete mode 100644 spring-groovy-config/pom.xml delete mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/ClassWithRef.java delete mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/GroovyClass.groovy delete mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/MainApp.java delete mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClass.java delete mode 100644 spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClassB.java delete mode 100644 spring-groovy-config/src/test/java/com/baeldung/spring_groovy_config/AppTest.java diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/App.java b/spring-core/src/main/java/com/baeldung/annotationinjection/App.java deleted file mode 100644 index dc9560286d..0000000000 --- a/spring-core/src/main/java/com/baeldung/annotationinjection/App.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.java_bean_injection; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.baeldung.java_bean_injection.*; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - - -import junit.framework.TestResult; -import junit.framework.TestFailure; - -import java.util.Enumeration; - - -/** - * Bean Injection Test Application - * - */ -public class App -{ - public static void main( String[] args ) - { - - TestResult result = new TestResult(); - AppTest.suite().run(result); - System.out.println(String.format("Tests: %d",result.runCount())); - System.out.println(String.format("Errors: %d",result.errorCount())); - System.out.println(String.format("Failures: %d",result.failureCount())); - if(result.failureCount() > 0){ - Enumeration failures = result.failures(); - int failNum = 0; - TestFailure failure = null; - while(failures.hasMoreElements()){ - failure = failures.nextElement(); - - System.out.println(failure.exceptionMessage()); - System.out.println(String.format("Test Failure %d\n",failNum)); - System.out.println(failure.trace()); - System.out.print("\n"); - } - } - - } -} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/AppConfig.java b/spring-core/src/main/java/com/baeldung/annotationinjection/AppConfig.java deleted file mode 100644 index 138bda6b1b..0000000000 --- a/spring-core/src/main/java/com/baeldung/annotationinjection/AppConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.java_bean_injection; - -import org.springframework.beans.factory.annotation.*; -import org.springframework.context.annotation.*; -import org.springframework.stereotype.*; - -import com.baeldung.java_bean_injection.*; - -@Configuration -@PropertySource(value="classpath:inject.properties") -@Import(ImportConfig.class) -public class AppConfig { - @Value("${contructor.arg1}") String constructorArg; - - @Bean - public InjectedClass injectedClass(){ - InjectedClass ic = new InjectedClass(constructorArg); - ic.setMyInt(10); - ic.setTestString("test"); - return ic; - } - -} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/AppTest.java b/spring-core/src/main/java/com/baeldung/annotationinjection/AppTest.java deleted file mode 100644 index fa7b46f06b..0000000000 --- a/spring-core/src/main/java/com/baeldung/annotationinjection/AppTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.java_bean_injection; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.baeldung.java_bean_injection.*; - -import java.io.File; -import java.util.Scanner; - -/** - * Unit test for simple App. - */ -public class AppTest extends TestCase{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(); - context.register(AppConfig.class); - context.refresh(); - InjectedClass injectedClass = (InjectedClass) context.getBean(InjectedClass.class); - assertTrue(injectedClass.getMyInt() == 10); - assertTrue(injectedClass.getTestString().equals("test")); - assertNotNull(injectedClass.obj); - assertTrue(injectedClass.myConstructorArg.equals("test")); - } -} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/AutowireObject.java b/spring-core/src/main/java/com/baeldung/annotationinjection/AutowireObject.java deleted file mode 100644 index df5859f0af..0000000000 --- a/spring-core/src/main/java/com/baeldung/annotationinjection/AutowireObject.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.java_bean_injection; - - -public class AutowireObject { - -} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/ImportConfig.java b/spring-core/src/main/java/com/baeldung/annotationinjection/ImportConfig.java deleted file mode 100644 index e37d94931b..0000000000 --- a/spring-core/src/main/java/com/baeldung/annotationinjection/ImportConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.java_bean_injection; - -import org.springframework.context.annotation.*; - -import com.baeldung.java_bean_injection.*; - -@Configuration -public class ImportConfig { - - @Bean(name="autobean") - public AutowireObject autowireObject(){ - return new AutowireObject(); - } - - - @Bean(name="autobean2") - public AutowireObject autowireObject2(){ - return new AutowireObject(); - } -} diff --git a/spring-core/src/main/java/com/baeldung/annotationinjection/InjectedClass.java b/spring-core/src/main/java/com/baeldung/annotationinjection/InjectedClass.java deleted file mode 100644 index 55fe733db5..0000000000 --- a/spring-core/src/main/java/com/baeldung/annotationinjection/InjectedClass.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.java_bean_injection; - -import org.springframework.beans.factory.annotation.*; -import org.springframework.context.annotation.*; - -import com.baeldung.java_bean_injection.*; - - -public class InjectedClass { - private int myInt; - private String testString; - String myConstructorArg; - - - @Autowired - @Qualifier("autobean") - AutowireObject obj; - - public InjectedClass(String constArg){ - this.myConstructorArg = constArg; - } - - public void setMyInt(int myInt){ - this.myInt = myInt; - } - - public void setTestString(String testString){ - this.testString = testString; - } - - public int getMyInt(){ - return this.myInt; - } - - public String getTestString(){ - return this.testString; - } - -} diff --git a/spring-groovy-config/.gitignore b/spring-groovy-config/.gitignore deleted file mode 100644 index b83d22266a..0000000000 --- a/spring-groovy-config/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/spring-groovy-config/.settings/org.eclipse.core.resources.prefs b/spring-groovy-config/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index f9fe34593f..0000000000 --- a/spring-groovy-config/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/test/java=UTF-8 -encoding/=UTF-8 diff --git a/spring-groovy-config/.settings/org.eclipse.jdt.core.prefs b/spring-groovy-config/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index abec6ca389..0000000000 --- a/spring-groovy-config/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/spring-groovy-config/.settings/org.eclipse.jdt.groovy.core.prefs b/spring-groovy-config/.settings/org.eclipse.jdt.groovy.core.prefs deleted file mode 100644 index ae98feaa79..0000000000 --- a/spring-groovy-config/.settings/org.eclipse.jdt.groovy.core.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -groovy.compiler.level=24 diff --git a/spring-groovy-config/.settings/org.eclipse.m2e.core.prefs b/spring-groovy-config/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/spring-groovy-config/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/spring-groovy-config/config/groovyContextWithConstructor.groovy b/spring-groovy-config/config/groovyContextWithConstructor.groovy deleted file mode 100644 index dbde5f3822..0000000000 --- a/spring-groovy-config/config/groovyContextWithConstructor.groovy +++ /dev/null @@ -1,9 +0,0 @@ -import com.baeldung.spring_groovy_config.TestClass - -beans{ - testString String, 'Test String' - testClass(TestClass){ - beanDefinition -> - beanDefinition.constructorArgs = ["Test String",10.2] - } -} \ No newline at end of file diff --git a/spring-groovy-config/config/groovyPropConfig.groovy b/spring-groovy-config/config/groovyPropConfig.groovy deleted file mode 100644 index 08d3acf354..0000000000 --- a/spring-groovy-config/config/groovyPropConfig.groovy +++ /dev/null @@ -1,5 +0,0 @@ -import com.baeldung.spring_groovy_config.TestClassB - -beans{ - testClassB(TestClassB,testStringB:"Test String",testIntB:10.2) -} \ No newline at end of file diff --git a/spring-groovy-config/config/groovyPropConfigWithClosure.groovy b/spring-groovy-config/config/groovyPropConfigWithClosure.groovy deleted file mode 100644 index 3ca306bdd7..0000000000 --- a/spring-groovy-config/config/groovyPropConfigWithClosure.groovy +++ /dev/null @@ -1,8 +0,0 @@ -import com.baeldung.spring_groovy_config.TestClassB - -beans{ - testClassB(TestClassB){ - testStringB = "Test String" - testIntB = 10 - } -} \ No newline at end of file diff --git a/spring-groovy-config/config/groovyTestWithRefBean.groovy b/spring-groovy-config/config/groovyTestWithRefBean.groovy deleted file mode 100644 index d079480d46..0000000000 --- a/spring-groovy-config/config/groovyTestWithRefBean.groovy +++ /dev/null @@ -1,10 +0,0 @@ -import com.baeldung.spring_groovy_config.GroovyClass -import com.baeldung.spring_groovy_config.ClassWithRef - -beans{ - groovyClass(GroovyClass, groovyInt:5) - classWithRef(ClassWithRef){ - myClass = groovyClass - } - -} \ No newline at end of file diff --git a/spring-groovy-config/pom.xml b/spring-groovy-config/pom.xml deleted file mode 100644 index f6c63ae232..0000000000 --- a/spring-groovy-config/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-groovy-config - 0.0.1-SNAPSHOT - jar - spring-groovy-config - http://maven.apache.org - - UTF-8 - - - - - maven-compiler-plugin - - 3.1 - - groovy-eclipse-compiler - - - - org.codehaus.groovy - groovy-eclipse-compiler - 2.9.1-01 - - - - org.codehaus.groovy - groovy-eclipse-batch - 2.3.7-01 - - - - - - - - org.codehaus.groovy - groovy-all - 2.4.8 - - - junit - junit - 4.12 - test - - - org.springframework - spring-context - 4.3.6.RELEASE - - - org.springframework - spring-core - 4.3.6.RELEASE - - - org.springframework - spring-test - 4.3.6.RELEASE - - - - diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/ClassWithRef.java b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/ClassWithRef.java deleted file mode 100644 index ec8987f387..0000000000 --- a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/ClassWithRef.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.spring_groovy_config; - -import org.springframework.stereotype.Component; - -import com.baeldung.spring_groovy_config.GroovyClass; - -@Component -public class ClassWithRef { - private GroovyClass myClass = null; - - public void setMyClass(GroovyClass myClass){ - this.myClass = myClass; - } - - public GroovyClass getMyClass(){ - return this.myClass; - } -} diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/GroovyClass.groovy b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/GroovyClass.groovy deleted file mode 100644 index 2a1ef6a2c5..0000000000 --- a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/GroovyClass.groovy +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.spring_groovy_config - -class GroovyClass { - int groovyInt = 0 - - def getGroovyInt(){ - return groovyInt - } -} diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/MainApp.java b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/MainApp.java deleted file mode 100644 index ac85963cf7..0000000000 --- a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/MainApp.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.spring_groovy_config; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.GenericGroovyApplicationContext; - -public class MainApp { - public static void main(String[] args){ - ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyTestWithRefBean.groovy"); - ClassWithRef test = (ClassWithRef) context.getBean("classWithRef"); - } -} diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClass.java b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClass.java deleted file mode 100644 index 75b6b5fc5b..0000000000 --- a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClass.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.spring_groovy_config; - -import org.springframework.stereotype.Component; - -@Component -public class TestClass { - private String testString; - private double testDouble; - - public TestClass(String testString, double testDouble){ - this.testString = testString; - this.testDouble = testDouble; - } - - public String getTestString(){ - return this.testString; - } - - public double getTestDouble(){ - return this.testDouble; - } -} diff --git a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClassB.java b/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClassB.java deleted file mode 100644 index d2387c87e5..0000000000 --- a/spring-groovy-config/src/main/java/com/baeldung/spring_groovy_config/TestClassB.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.spring_groovy_config; - -import org.springframework.stereotype.Component; - -@Component -public class TestClassB { - private String testStringB; - private int testIntB; - - public void setTestStringB(String testStringB){ - this.testStringB = testStringB; - } - - public String getTestStringB(){ - return this.testStringB; - } - - - public void setTestIntB(int testIntB){ - this.testIntB = testIntB; - } - - public int getTestIntB(){ - return this.testIntB; - } -} diff --git a/spring-groovy-config/src/test/java/com/baeldung/spring_groovy_config/AppTest.java b/spring-groovy-config/src/test/java/com/baeldung/spring_groovy_config/AppTest.java deleted file mode 100644 index 93de401e0c..0000000000 --- a/spring-groovy-config/src/test/java/com/baeldung/spring_groovy_config/AppTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.spring_groovy_config; - -import com.baeldung.spring_groovy_config.*; -import groovy.lang.Binding; -import junit.framework.TestCase; -import static org.junit.Assert.*; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.support.FileSystemXmlApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.context.support.GenericGroovyApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -/** - * Spring Framework Tests for Groovy. - */ -public class AppTest{ - - @Test - public void testSimple(){ - ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyContextWithConstructor.groovy"); - TestClass test = (TestClass) context.getBean("testClass"); - assertNotNull(test.getTestString()); - assertEquals(test.getTestString(),"Test String"); - assertTrue(test.getTestDouble() == 10.2); - - String testString = context.getBean("testString",String.class); - assertEquals(testString,"Test String"); - } - - - @Test - public void testProperties(){ - ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyPropConfig.groovy"); - TestClassB test = (TestClassB) context.getBean("testClassB"); - assertNotNull(test.getTestStringB()); - assertEquals(test.getTestStringB(),"Test String"); - assertTrue(test.getTestIntB() == 10); - } - - @Test - public void testPropertiesWithClosure(){ - ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyPropConfigWithClosure.groovy"); - TestClassB test = (TestClassB) context.getBean("testClassB"); - assertNotNull(test.getTestStringB()); - assertEquals(test.getTestStringB(),"Test String"); - assertTrue(test.getTestIntB() == 10); - } - - - @Test - public void testWithRef(){ - ApplicationContext context = new GenericGroovyApplicationContext("file:config/groovyTestWithRefBean.groovy"); - ClassWithRef test = (ClassWithRef) context.getBean("classWithRef"); - assertEquals(test.getMyClass().getGroovyInt(),5); - } -} From 72d5bfca82ffe4a4f98612e3e7da39a11558438e Mon Sep 17 00:00:00 2001 From: Adam InTae Gerard Date: Tue, 21 Feb 2017 18:15:35 -0600 Subject: [PATCH 23/23] BAEL-9 #3 (#1207) * BAEL-9 #3 * pom.xml fix --- pom.xml | 1 + spring-boot-servlet/.gitignore | 4 ++ spring-boot-servlet/README.md | 2 + spring-boot-servlet/pom.xml | 55 +++++++++++++++++++ .../src/main/java/META-INF/MANIFEST.MF | 2 + .../java/com/baeldung/ApplicationMain.java | 19 +++++++ .../configuration/WebAppInitializer.java | 32 +++++++++++ .../configuration/WebMvcConfigure.java | 40 ++++++++++++++ .../java/com/baeldung/props/Constants.java | 20 +++++++ .../com/baeldung/props/PropertyLoader.java | 27 +++++++++ .../baeldung/props/PropertySourcesLoader.java | 23 ++++++++ .../servlets/GenericCustomServlet.java | 18 ++++++ .../servlets/javaee/AnnotationServlet.java | 20 +++++++ .../servlets/javaee/EEWebXmlServlet.java | 20 +++++++ .../SpringRegistrationBeanServlet.java | 19 +++++++ .../embedded/EmbeddedTomcatExample.java | 16 ++++++ .../src/main/resources/application.properties | 10 ++++ .../src/main/resources/custom.properties | 4 ++ .../src/main/webapp/WEB-INF/context.xml | 12 ++++ .../src/main/webapp/WEB-INF/dispatcher.xml | 16 ++++++ .../src/main/webapp/WEB-INF/web.xml | 40 ++++++++++++++ .../src/main/webapp/annotationservlet.jsp | 1 + spring-boot-servlet/src/main/webapp/index.jsp | 1 + 23 files changed, 402 insertions(+) create mode 100644 spring-boot-servlet/.gitignore create mode 100644 spring-boot-servlet/README.md create mode 100644 spring-boot-servlet/pom.xml create mode 100644 spring-boot-servlet/src/main/java/META-INF/MANIFEST.MF create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/ApplicationMain.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/configuration/WebAppInitializer.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/configuration/WebMvcConfigure.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/props/Constants.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/props/PropertyLoader.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/props/PropertySourcesLoader.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/servlets/GenericCustomServlet.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/AnnotationServlet.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/EEWebXmlServlet.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/SpringRegistrationBeanServlet.java create mode 100644 spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/embedded/EmbeddedTomcatExample.java create mode 100644 spring-boot-servlet/src/main/resources/application.properties create mode 100644 spring-boot-servlet/src/main/resources/custom.properties create mode 100644 spring-boot-servlet/src/main/webapp/WEB-INF/context.xml create mode 100644 spring-boot-servlet/src/main/webapp/WEB-INF/dispatcher.xml create mode 100644 spring-boot-servlet/src/main/webapp/WEB-INF/web.xml create mode 100644 spring-boot-servlet/src/main/webapp/annotationservlet.jsp create mode 100644 spring-boot-servlet/src/main/webapp/index.jsp diff --git a/pom.xml b/pom.xml index aa58b1d2e9..924bd96ade 100644 --- a/pom.xml +++ b/pom.xml @@ -109,6 +109,7 @@ spring-autowire spring-batch spring-boot + spring-boot-servlet spring-cloud-data-flow spring-cloud spring-core diff --git a/spring-boot-servlet/.gitignore b/spring-boot-servlet/.gitignore new file mode 100644 index 0000000000..60be5b80aa --- /dev/null +++ b/spring-boot-servlet/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project diff --git a/spring-boot-servlet/README.md b/spring-boot-servlet/README.md new file mode 100644 index 0000000000..262a11fc36 --- /dev/null +++ b/spring-boot-servlet/README.md @@ -0,0 +1,2 @@ +###Relevant Articles: +- [How to Register a Servlet in a Java Web Application](http://www.baeldung.com/how-to-register-a-servlet-in-a-java-web-application/) \ No newline at end of file diff --git a/spring-boot-servlet/pom.xml b/spring-boot-servlet/pom.xml new file mode 100644 index 0000000000..3818e3468f --- /dev/null +++ b/spring-boot-servlet/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + com.baeldung + spring-boot-servlet + 0.0.1-SNAPSHOT + war + spring-boot-servlet + + + org.springframework.boot + spring-boot-dependencies + 1.5.1.RELEASE + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat.version} + + + org.apache.tomcat.embed + tomcat-embed-jasper + ${tomcat.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + 1.8 + 8.5.11 + + + diff --git a/spring-boot-servlet/src/main/java/META-INF/MANIFEST.MF b/spring-boot-servlet/src/main/java/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..69ebae1751 --- /dev/null +++ b/spring-boot-servlet/src/main/java/META-INF/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Main-Class: com.baeldung.ApplicationMain diff --git a/spring-boot-servlet/src/main/java/com/baeldung/ApplicationMain.java b/spring-boot-servlet/src/main/java/com/baeldung/ApplicationMain.java new file mode 100644 index 0000000000..66f2e85999 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/ApplicationMain.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +@SpringBootApplication +public class ApplicationMain extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(ApplicationMain.class); + } +} \ No newline at end of file diff --git a/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebAppInitializer.java b/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebAppInitializer.java new file mode 100644 index 0000000000..b7e22500f4 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebAppInitializer.java @@ -0,0 +1,32 @@ +package com.baeldung.configuration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.context.support.XmlWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +public class WebAppInitializer implements WebApplicationInitializer { + + public void onStartup(ServletContext container) throws ServletException { + + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(WebMvcConfigure.class); + ctx.setServletContext(container); + + ServletRegistration.Dynamic servletOne = container.addServlet("SpringProgrammaticDispatcherServlet", new DispatcherServlet(ctx)); + servletOne.setLoadOnStartup(1); + servletOne.addMapping("/"); + + XmlWebApplicationContext xctx = new XmlWebApplicationContext(); + xctx.setConfigLocation("/WEB-INF/context.xml"); + xctx.setServletContext(container); + + ServletRegistration.Dynamic servletTwo = container.addServlet("SpringProgrammaticXMLDispatcherServlet", new DispatcherServlet(xctx)); + servletTwo.setLoadOnStartup(1); + servletTwo.addMapping("/"); + } + +} \ No newline at end of file diff --git a/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebMvcConfigure.java b/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebMvcConfigure.java new file mode 100644 index 0000000000..de9067de6e --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/configuration/WebMvcConfigure.java @@ -0,0 +1,40 @@ +package com.baeldung.configuration; + +import org.springframework.boot.web.support.ErrorPageFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.resource.PathResourceResolver; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +@Configuration +public class WebMvcConfigure extends WebMvcConfigurerAdapter { + + @Bean + public ViewResolver getViewResolver() { + InternalResourceViewResolver resolver = new InternalResourceViewResolver(); + resolver.setPrefix("/WEB-INF/"); + resolver.setSuffix(".jsp"); + return resolver; + } + + @Override + public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { + configurer.enable(); + } + + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); + } + + @Bean + public ErrorPageFilter errorPageFilter() { + return new ErrorPageFilter(); + } +} + diff --git a/spring-boot-servlet/src/main/java/com/baeldung/props/Constants.java b/spring-boot-servlet/src/main/java/com/baeldung/props/Constants.java new file mode 100644 index 0000000000..421401eec7 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/props/Constants.java @@ -0,0 +1,20 @@ +package com.baeldung.props; + +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Properties; + +public final class Constants { + + @Autowired + PropertySourcesLoader psl; + + public static final String breakLine = System.getProperty("line.separator"); + private static final PropertyLoader pl = new PropertyLoader(); + private static final Properties mainProps = pl.getProperties("custom.properties"); + public static final String DISPATCHER_SERVLET_NAME = mainProps.getProperty("dispatcher.servlet.name"); + public static final String DISPATCHER_SERVLET_MAPPING = mainProps.getProperty("dispatcher.servlet.mapping"); + private final String EXAMPLE_SERVLET_NAME = psl.getProperty("example.servlet.name"); + private final String EXAMPLE_SERVLET_MAPPING = psl.getProperty("example.servlet.mapping"); + +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/props/PropertyLoader.java b/spring-boot-servlet/src/main/java/com/baeldung/props/PropertyLoader.java new file mode 100644 index 0000000000..5d890d96fa --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/props/PropertyLoader.java @@ -0,0 +1,27 @@ +package com.baeldung.props; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class PropertyLoader { + private static final Logger log = LoggerFactory.getLogger(PropertyLoader.class); + + public Properties getProperties(String file) { + Properties prop = new Properties(); + InputStream input = null; + try { + input = getClass().getResourceAsStream(file); + prop.load(input); + if (input != null) { + input.close(); + } + } catch (IOException ex) { + log.error("IOException: " + ex); + } + return prop; + } +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/props/PropertySourcesLoader.java b/spring-boot-servlet/src/main/java/com/baeldung/props/PropertySourcesLoader.java new file mode 100644 index 0000000000..8c7b3a4af5 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/props/PropertySourcesLoader.java @@ -0,0 +1,23 @@ +package com.baeldung.props; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.ConfigurableEnvironment; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.*" }) +@PropertySource("classpath:custom.properties") public class PropertySourcesLoader { + + private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); + + @Autowired + ConfigurableEnvironment env; + + public String getProperty(String key) { + return env.getProperty(key); + } +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/GenericCustomServlet.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/GenericCustomServlet.java new file mode 100644 index 0000000000..c6543c9eef --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/GenericCustomServlet.java @@ -0,0 +1,18 @@ +package com.baeldung.servlets; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +public class GenericCustomServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Hello World

"); + } +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/AnnotationServlet.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/AnnotationServlet.java new file mode 100644 index 0000000000..d971e68cfa --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/AnnotationServlet.java @@ -0,0 +1,20 @@ +package com.baeldung.servlets.javaee; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet(name = "AnnotationServlet", + description = "Example Servlet Using Annotations", + urlPatterns = { "/annotationservlet" }) +public class AnnotationServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response); + } +} diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/EEWebXmlServlet.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/EEWebXmlServlet.java new file mode 100644 index 0000000000..4209e815cd --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/javaee/EEWebXmlServlet.java @@ -0,0 +1,20 @@ +package com.baeldung.servlets.javaee; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +public class EEWebXmlServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("

Hello World

"); + } +} \ No newline at end of file diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/SpringRegistrationBeanServlet.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/SpringRegistrationBeanServlet.java new file mode 100644 index 0000000000..4a34465894 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/SpringRegistrationBeanServlet.java @@ -0,0 +1,19 @@ +package com.baeldung.servlets.springboot; + +import com.baeldung.servlets.GenericCustomServlet; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringRegistrationBeanServlet { + + @Bean + public ServletRegistrationBean genericCustomServlet() { + ServletRegistrationBean bean = new ServletRegistrationBean(new GenericCustomServlet(), "/springregistrationbeanservlet/*"); + bean.setLoadOnStartup(1); + return bean; + } +} + + diff --git a/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/embedded/EmbeddedTomcatExample.java b/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/embedded/EmbeddedTomcatExample.java new file mode 100644 index 0000000000..b2458f33c7 --- /dev/null +++ b/spring-boot-servlet/src/main/java/com/baeldung/servlets/springboot/embedded/EmbeddedTomcatExample.java @@ -0,0 +1,16 @@ +package com.baeldung.servlets.springboot.embedded; + +import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; +import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class EmbeddedTomcatExample { + + @Bean + public EmbeddedServletContainerFactory servletContainer() { + TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); + return tomcat; + } +} diff --git a/spring-boot-servlet/src/main/resources/application.properties b/spring-boot-servlet/src/main/resources/application.properties new file mode 100644 index 0000000000..4e9e2b4cf1 --- /dev/null +++ b/spring-boot-servlet/src/main/resources/application.properties @@ -0,0 +1,10 @@ +#Server Configuration +#server.port=8080 +#server.context-path=/javabootdata +#Resource Handling +#spring.resources.static-locations=classpath:/WEB-INF/resources +#spring.mvc.view.prefix=/WEB-INF/ +#spring.mvc.view.suffix=.jsp +#spring.resources.cache-period=3600 +servlet.name=dispatcherExample +servlet.mapping=/dispatcherExampleURL \ No newline at end of file diff --git a/spring-boot-servlet/src/main/resources/custom.properties b/spring-boot-servlet/src/main/resources/custom.properties new file mode 100644 index 0000000000..34f31bcd50 --- /dev/null +++ b/spring-boot-servlet/src/main/resources/custom.properties @@ -0,0 +1,4 @@ +dispatcher.servlet.name=dispatcherExample +dispatcher.servlet.mapping=/dispatcherExampleURL +example.servlet.name=dispatcherExample +example.servlet.mapping=/dispatcherExampleURL \ No newline at end of file diff --git a/spring-boot-servlet/src/main/webapp/WEB-INF/context.xml b/spring-boot-servlet/src/main/webapp/WEB-INF/context.xml new file mode 100644 index 0000000000..263bed4430 --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/WEB-INF/context.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/spring-boot-servlet/src/main/webapp/WEB-INF/dispatcher.xml b/spring-boot-servlet/src/main/webapp/WEB-INF/dispatcher.xml new file mode 100644 index 0000000000..ade8e66777 --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/WEB-INF/dispatcher.xml @@ -0,0 +1,16 @@ + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-servlet/src/main/webapp/WEB-INF/web.xml b/spring-boot-servlet/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..60a4b079de --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,40 @@ + + + JSP + + index.html + index.htm + index.jsp + + + + + EEWebXmlServlet + com.baeldung.servlets.javaee.EEWebXmlServlet + + + + EEWebXmlServlet + /eewebxmlservlet + + + + + SpringBootWebXmlServlet + org.springframework.web.servlet.DispatcherServlet + + contextConfigLocation + /WEB-INF/dispatcher.xml + + 1 + + + + SpringBootWebXmlServlet + / + + + + diff --git a/spring-boot-servlet/src/main/webapp/annotationservlet.jsp b/spring-boot-servlet/src/main/webapp/annotationservlet.jsp new file mode 100644 index 0000000000..f21748df50 --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/annotationservlet.jsp @@ -0,0 +1 @@ +

Annotation Servlet!

\ No newline at end of file diff --git a/spring-boot-servlet/src/main/webapp/index.jsp b/spring-boot-servlet/src/main/webapp/index.jsp new file mode 100644 index 0000000000..e534282777 --- /dev/null +++ b/spring-boot-servlet/src/main/webapp/index.jsp @@ -0,0 +1 @@ +

Hello!

\ No newline at end of file