merge with base repo

This commit is contained in:
Ahmed Tawila 2017-12-01 14:46:05 +02:00
commit ea2c91871e
237 changed files with 4004 additions and 338 deletions

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Eugen Paraschiv
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,9 +1,14 @@
The "REST with Spring" Classes
==============================
After 5 months of work, here's the Master Class of REST With Spring: <br/>
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
And here's the Master Class of Learn Spring Security: <br/>
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
Spring Tutorials
================

View File

@ -0,0 +1,224 @@
package com.baeldung.poi.powerpoint;
import org.apache.poi.sl.usermodel.AutoNumberingScheme;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.TableCell;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Helper class for the PowerPoint presentation creation
*/
public class PowerPointHelper {
/**
* Read an existing presentation
*
* @param fileLocation
* File location of the presentation
* @return instance of {@link XMLSlideShow}
* @throws IOException
*/
public XMLSlideShow readingExistingSlideShow(String fileLocation) throws IOException {
return new XMLSlideShow(new FileInputStream(fileLocation));
}
/**
* Create a sample presentation
*
* @param fileLocation
* File location of the presentation
* @throws IOException
*/
public void createPresentation(String fileLocation) throws IOException {
// Create presentation
XMLSlideShow ppt = new XMLSlideShow();
XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);
// Retriving the slide layout
XSLFSlideLayout layout = defaultMaster.getLayout(SlideLayout.TITLE_ONLY);
// Creating the 1st slide
XSLFSlide slide1 = ppt.createSlide(layout);
XSLFTextShape title = slide1.getPlaceholder(0);
// Clearing text to remove the predefined one in the template
title.clearText();
XSLFTextParagraph p = title.addNewTextParagraph();
XSLFTextRun r1 = p.addNewTextRun();
r1.setText("Baeldung");
r1.setFontColor(new Color(78, 147, 89));
r1.setFontSize(48.);
// Add Image
ClassLoader classLoader = getClass().getClassLoader();
byte[] pictureData = IOUtils.toByteArray(new FileInputStream(classLoader.getResource("logo-leaf.png").getFile()));
XSLFPictureData pd = ppt.addPicture(pictureData, PictureData.PictureType.PNG);
XSLFPictureShape picture = slide1.createPicture(pd);
picture.setAnchor(new Rectangle(320, 230, 100, 92));
// Creating 2nd slide
layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide2 = ppt.createSlide(layout);
// setting the tile
title = slide2.getPlaceholder(0);
title.clearText();
XSLFTextRun r = title.addNewTextParagraph().addNewTextRun();
r.setText("Baeldung");
// Adding the link
XSLFHyperlink link = r.createHyperlink();
link.setAddress("http://www.baeldung.com");
// setting the content
XSLFTextShape content = slide2.getPlaceholder(1);
content.clearText(); // unset any existing text
content.addNewTextParagraph().addNewTextRun().setText("First paragraph");
content.addNewTextParagraph().addNewTextRun().setText("Second paragraph");
content.addNewTextParagraph().addNewTextRun().setText("Third paragraph");
// Creating 3rd slide - List
layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide3 = ppt.createSlide(layout);
title = slide3.getPlaceholder(0);
title.clearText();
r = title.addNewTextParagraph().addNewTextRun();
r.setText("Lists");
content = slide3.getPlaceholder(1);
content.clearText();
XSLFTextParagraph p1 = content.addNewTextParagraph();
p1.setIndentLevel(0);
p1.setBullet(true);
r1 = p1.addNewTextRun();
r1.setText("Bullet");
// the next three paragraphs form an auto-numbered list
XSLFTextParagraph p2 = content.addNewTextParagraph();
p2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
p2.setIndentLevel(1);
XSLFTextRun r2 = p2.addNewTextRun();
r2.setText("Numbered List Item - 1");
// Creating 4th slide
XSLFSlide slide4 = ppt.createSlide();
createTable(slide4);
// Save presentation
FileOutputStream out = new FileOutputStream(fileLocation);
ppt.write(out);
out.close();
// Closing presentation
ppt.close();
}
/**
* Delete a slide from the presentation
*
* @param ppt
* The presentation
* @param slideNumber
* The number of the slide to be deleted (0-based)
*/
public void deleteSlide(XMLSlideShow ppt, int slideNumber) {
ppt.removeSlide(slideNumber);
}
/**
* Re-order the slides inside a presentation
*
* @param ppt
* The presentation
* @param slideNumber
* The number of the slide to move
* @param newSlideNumber
* The new position of the slide (0-base)
*/
public void reorderSlide(XMLSlideShow ppt, int slideNumber, int newSlideNumber) {
List<XSLFSlide> slides = ppt.getSlides();
XSLFSlide secondSlide = slides.get(slideNumber);
ppt.setSlideOrder(secondSlide, newSlideNumber);
}
/**
* Retrieve the placeholder inside a slide
*
* @param slide
* The slide
* @return List of placeholder inside a slide
*/
public List<XSLFShape> retrieveTemplatePlaceholders(XSLFSlide slide) {
List<XSLFShape> placeholders = new ArrayList<>();
for (XSLFShape shape : slide.getShapes()) {
if (shape instanceof XSLFAutoShape) {
placeholders.add(shape);
}
}
return placeholders;
}
/**
* Create a table
*
* @param slide
* Slide
*/
private void createTable(XSLFSlide slide) {
XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
int numColumns = 3;
int numRows = 5;
// header
XSLFTableRow headerRow = tbl.addRow();
headerRow.setHeight(50);
for (int i = 0; i < numColumns; i++) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextParagraph.TextAlign.CENTER);
XSLFTextRun r = p.addNewTextRun();
r.setText("Header " + (i + 1));
r.setBold(true);
r.setFontColor(Color.white);
th.setFillColor(new Color(79, 129, 189));
th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0);
th.setBorderColor(TableCell.BorderEdge.bottom, Color.white);
// all columns are equally sized
tbl.setColumnWidth(i, 150);
}
// data
for (int rownum = 0; rownum < numRows; rownum++) {
XSLFTableRow tr = tbl.addRow();
tr.setHeight(50);
for (int i = 0; i < numColumns; i++) {
XSLFTableCell cell = tr.addCell();
XSLFTextParagraph p = cell.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Cell " + (i * rownum + 1));
if (rownum % 2 == 0) {
cell.setFillColor(new Color(208, 216, 232));
} else {
cell.setFillColor(new Color(233, 247, 244));
}
}
}
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.poi.powerpoint;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.List;
public class PowerPointIntegrationTest {
private PowerPointHelper pph;
private String fileLocation;
private static final String FILE_NAME = "presentation.pptx";
@Before
public void setUp() throws Exception {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
pph = new PowerPointHelper();
pph.createPresentation(fileLocation);
}
@Test
public void whenReadingAPresentation_thenOK() throws Exception {
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
Assert.assertNotNull(xmlSlideShow);
Assert.assertEquals(4, xmlSlideShow.getSlides().size());
}
@Test
public void whenRetrievingThePlaceholdersForEachSlide_thenOK() throws Exception {
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
List<XSLFShape> onlyTitleSlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(0));
List<XSLFShape> titleAndBodySlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(1));
List<XSLFShape> emptySlidePlaceholdes = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(3));
Assert.assertEquals(1, onlyTitleSlidePlaceholders.size());
Assert.assertEquals(2, titleAndBodySlidePlaceholders.size());
Assert.assertEquals(0, emptySlidePlaceholdes.size());
}
@Test
public void whenSortingSlides_thenOK() throws Exception {
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
XSLFSlide slide4 = xmlSlideShow.getSlides().get(3);
pph.reorderSlide(xmlSlideShow, 3, 1);
Assert.assertEquals(slide4, xmlSlideShow.getSlides().get(1));
}
@Test
public void givenPresentation_whenDeletingASlide_thenOK() throws Exception {
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
pph.deleteSlide(xmlSlideShow, 3);
Assert.assertEquals(3, xmlSlideShow.getSlides().size());
}
@After
public void tearDown() throws Exception {
File testFile = new File(fileLocation);
if (testFile.exists()) {
testFile.delete();
}
pph = null;
}
}

View File

@ -28,8 +28,14 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<version>4.12</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>

View File

@ -1,35 +0,0 @@
/**
*
*/
package com.baeldung.datetime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows different ways of converting java.util.Date into java.time.LocalDate.
*
* @author abialas
*
*/
public class DateToLocalDateConverter {
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
}
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
}

View File

@ -1,35 +0,0 @@
/**
*
*/
package com.baeldung.datetime;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows different ways of converting java.util.Date into java.time.LocalDateTime.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverter {
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
}

View File

@ -1,72 +0,0 @@
/**
*
*/
package com.baeldung.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
*
* JUnits for {@link DateToLocalDateConverter} class.
*
* @author abialas
*
*/
public class DateToLocalDateConverterTest {
@Test
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
}

View File

@ -1,78 +0,0 @@
/**
*
*/
package com.baeldung.datetime;
import static org.junit.Assert.assertEquals;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
*
* JUnits for {@link DateToLocalDateTimeConverter} class.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverterTest {
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
}

View File

@ -3,18 +3,35 @@
*/
package com.baeldung.java9.datetime;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows a way to convert java.util.Date into java.time.LocalDate with new Java 1.9.
* Class which shows a way to convert java.util.Date into java.time.LocalDate.
*
* @author abialas
*
*/
public class DateToLocalDateConverter {
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
}
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
public static LocalDate convertToLocalDate(Date dateToConvert) {
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
}

View File

@ -3,18 +3,35 @@
*/
package com.baeldung.java9.datetime;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime with new Java 1.9.
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime.
*
* @author abialas
*
*/
public class DateToLocalDateTimeConverter {
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime())
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
}
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
}

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.datetime;
package com.baeldung.java9.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.datetime;
package com.baeldung.java9.datetime;
import java.time.LocalDate;
import java.time.ZoneId;

View File

@ -22,6 +22,54 @@ import com.baeldung.java9.datetime.DateToLocalDateConverter;
*/
public class DateToLocalDateConverterTest {
@Test
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10);
Date dateToConvert = calendar.getTime();
// when
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
// then
assertEquals(2010, localDate.get(ChronoField.YEAR));
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
}
@Test
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
// given

View File

@ -29,6 +29,60 @@ public class DateToLocalDateTimeConverterTest {
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
// then
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
}
@Test
public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() {
// given
Calendar calendar = Calendar.getInstance();
calendar.set(2010, 10, 10, 8, 20);
Date dateToConvert = calendar.getTime();
// when
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.datetime;
package com.baeldung.java9.datetime;
import static org.junit.Assert.assertEquals;

View File

@ -1,7 +1,7 @@
/**
*
*/
package com.baeldung.datetime;
package com.baeldung.java9.datetime;
import static org.junit.Assert.assertEquals;

View File

@ -0,0 +1,33 @@
package com.baeldung.concurrent.waitandnotify;
public class Data {
private String packet;
// True if receiver should wait
// False if sender should wait
private boolean transfer = true;
public synchronized String receive() {
while (transfer) {
try {
wait();
} catch (InterruptedException e) {}
}
transfer = true;
notifyAll();
return packet;
}
public synchronized void send(String packet) {
while (!transfer) {
try {
wait();
} catch (InterruptedException e) {}
}
transfer = false;
this.packet = packet;
notifyAll();
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.concurrent.waitandnotify;
public class NetworkDriver {
public static void main(String[] args) {
Data data = new Data();
Thread sender = new Thread(new Sender(data));
Thread receiver = new Thread(new Receiver(data));
sender.start();
receiver.start();
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.concurrent.waitandnotify;
import java.util.concurrent.ThreadLocalRandom;
public class Receiver implements Runnable {
private Data load;
public Receiver(Data load) {
this.load = load;
}
public void run() {
for(String receivedMessage = load.receive();
!"End".equals(receivedMessage) ;
receivedMessage = load.receive()) {
System.out.println(receivedMessage);
//Thread.sleep() to mimic heavy server-side processing
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
} catch (InterruptedException e) {}
}
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.concurrent.waitandnotify;
import java.util.concurrent.ThreadLocalRandom;
public class Sender implements Runnable {
private Data data;
public Sender(Data data) {
this.data = data;
}
public void run() {
String packets[] = {
"First packet",
"Second packet",
"Third packet",
"Fourth packet",
"End"
};
for (String packet : packets) {
data.send(packet);
//Thread.sleep() to mimic heavy server-side processing
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
} catch (InterruptedException e) {}
}
}
}

View File

@ -1,7 +1,11 @@
package com.baeldung.concurrent.stopping;
import com.jayway.awaitility.Awaitility;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -22,11 +26,10 @@ public class StopThreadTest {
// Stop it and make sure the flags have been reversed
controlSubThread.stop();
Thread.sleep(interval);
assertTrue(controlSubThread.isStopped());
await()
.until(() -> assertTrue(controlSubThread.isStopped()));
}
@Test
public void whenInterruptedThreadIsStopped() throws InterruptedException {
@ -44,7 +47,8 @@ public class StopThreadTest {
controlSubThread.interrupt();
// Wait less than the time we would normally sleep, and make sure we exited.
Thread.sleep(interval/10);
assertTrue(controlSubThread.isStopped());
Awaitility.await()
.atMost(interval/ 10, TimeUnit.MILLISECONDS)
.until(controlSubThread::isStopped);
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.concurrent.waitandnotify;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NetworkIntegrationTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private String expected;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@Before
public void setUpExpectedOutput() {
StringWriter expectedStringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(expectedStringWriter);
printWriter.println("First packet");
printWriter.println("Second packet");
printWriter.println("Third packet");
printWriter.println("Fourth packet");
printWriter.close();
expected = expectedStringWriter.toString();
}
@After
public void cleanUpStreams() {
System.setOut(null);
System.setErr(null);
}
@Test
public void givenSenderAndReceiver_whenSendingPackets_thenNetworkSynchronized() {
Data data = new Data();
Thread sender = new Thread(new Sender(data));
Thread receiver = new Thread(new Receiver(data));
sender.start();
receiver.start();
//wait for sender and receiver to finish before we test against expected
try {
sender.join();
receiver.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(expected, outContent.toString());
}
}

26
core-java-sun/.gitignore vendored Normal file
View File

@ -0,0 +1,26 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

6
core-java-sun/README.md Normal file
View File

@ -0,0 +1,6 @@
=========
## Core Java Cookbooks and Examples
### Relevant Articles:
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)

489
core-java-sun/pom.xml Normal file
View File

@ -0,0 +1,489 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-sun</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-sun</name>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.1.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8.0</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- util -->
<guava.version>23.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-io.version>2.5</commons-io.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<lombok.version>1.16.12</lombok.version>
<fscontext.version>4.6-b01</fscontext.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>2.8.9</mockito.version>
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)

View File

@ -0,0 +1,6 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -119,4 +119,5 @@
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)

View File

@ -181,11 +181,6 @@
<version>2.1.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
@ -216,13 +211,6 @@
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8.0</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,51 @@
package com.baeldung.comparable;
public class Player implements Comparable<Player> {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
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;
}
@Override
public String toString() {
return this.name;
}
@Override
public int compareTo(Player otherPlayer) {
return (this.getRanking() - otherPlayer.getRanking());
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam);
System.out.println("After Sorting : " + footballTeam);
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.comparator;
public class Player {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
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;
}
@Override
public String toString() {
return this.name;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.comparator;
import java.util.Comparator;
public class PlayerAgeComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getAge() - secondPlayer.getAge());
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerAgeSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
//Instance of PlayerAgeComparator
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
Collections.sort(footballTeam, playerComparator);
System.out.println("After Sorting by age : " + footballTeam);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.comparator;
import java.util.Comparator;
public class PlayerRankingComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getRanking() - secondPlayer.getRanking());
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerRankingSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 40);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
//Instance of PlayerRankingComparator
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
Collections.sort(footballTeam, playerComparator);
System.out.println("After Sorting by ranking : " + footballTeam);
}
}

View File

@ -11,7 +11,7 @@ public class PolygonFactory {
if(numberOfSides == 5) {
return new Pentagon();
}
if(numberOfSides == 4) {
if(numberOfSides == 7) {
return new Heptagon();
}
else if(numberOfSides == 8) {
@ -19,4 +19,4 @@ public class PolygonFactory {
}
return null;
}
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.loops;
public class LoopsInJava {
public int[] simple_for_loop() {
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = i;
System.out.println("Simple for loop: i - " + i);
}
return arr;
}
public int[] enhanced_for_each_loop() {
int[] intArr = { 0, 1, 2, 3, 4 };
int[] arr = new int[5];
for (int num : intArr) {
arr[num] = num;
System.out.println("Enhanced for-each loop: i - " + num);
}
return arr;
}
public int[] while_loop() {
int i = 0;
int[] arr = new int[5];
while (i < 5) {
arr[i] = i;
System.out.println("While loop: i - " + i++);
}
return arr;
}
public int[] do_while_loop() {
int i = 0;
int[] arr = new int[5];
do {
arr[i] = i;
System.out.println("Do-While loop: i - " + i++);
} while (i < 5);
return arr;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.polymorphism;
import java.awt.image.BufferedImage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileManager {
final static Logger logger = LoggerFactory.getLogger(FileManager.class);
public static void main(String[] args) {
GenericFile file1 = new TextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
logger.info("File Info: \n" + file1.getFileInfo() + "\n");
ImageFile imageFile = new ImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
.getBytes(), "v1.0.0");
logger.info("File Info: \n" + imageFile.getFileInfo());
}
public static ImageFile createImageFile(String name, int height, int width, byte[] content, String version) {
ImageFile imageFile = new ImageFile(name, height, width, content, version);
logger.info("File 2 Info: \n" + imageFile.getFileInfo());
return imageFile;
}
public static GenericFile createTextFile(String name, String content, String version) {
GenericFile file1 = new TextFile(name, content, version);
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
return file1;
}
public static TextFile createTextFile2(String name, String content, String version) {
TextFile file1 = new TextFile(name, content, version);
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
return file1;
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.polymorphism;
import java.util.Date;
public class GenericFile {
private String name;
private String extension;
private Date dateCreated;
private String version;
private byte[] content;
public GenericFile() {
this.setDateCreated(new Date());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public String getFileInfo() {
return "File Name: " + this.getName() + "\n" + "Extension: " + this.getExtension() + "\n" + "Date Created: " + this.getDateCreated() + "\n" + "Version: " + this.getVersion() + "\n";
}
public Object read() {
return content;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.polymorphism;
public class ImageFile extends GenericFile {
private int height;
private int width;
public ImageFile(String name, int height, int width, byte[] content, String version) {
this.setHeight(height);
this.setWidth(width);
this.setContent(content);
this.setName(name);
this.setVersion(version);
this.setExtension(".jpg");
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public String getFileInfo() {
return super.getFileInfo() + "Height: " + this.getHeight() + "\n" + "Width: " + this.getWidth();
}
public String read() {
return this.getContent()
.toString();
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.polymorphism;
public class TextFile extends GenericFile {
private int wordCount;
public TextFile(String name, String content, String version) {
String[] words = content.split(" ");
this.setWordCount(words.length > 0 ? words.length : 1);
this.setContent(content.getBytes());
this.setName(name);
this.setVersion(version);
this.setExtension(".txt");
}
public int getWordCount() {
return wordCount;
}
public void setWordCount(int wordCount) {
this.wordCount = wordCount;
}
public String getFileInfo() {
return super.getFileInfo() + "Word Count: " + wordCount;
}
public String read() {
return this.getContent()
.toString();
}
public String read(int limit) {
return this.getContent()
.toString()
.substring(0, limit);
}
public String read(int start, int stop) {
return this.getContent()
.toString()
.substring(start, stop);
}
}

View File

@ -1,3 +1,3 @@
UK
US
Germany
Germany

View File

@ -0,0 +1,50 @@
package com.baeldung.arraydeque;
import java.util.ArrayDeque;
import java.util.Deque;
import static org.junit.Assert.*;
import org.junit.Test;
public class ArrayDequeTest {
@Test
public void whenOffer_addsAtLast() {
final Deque<String> deque = new ArrayDeque<>();
deque.offer("first");
deque.offer("second");
assertEquals("second", deque.getLast());
}
@Test
public void whenPoll_removesFirst() {
final Deque<String> deque = new ArrayDeque<>();
deque.offer("first");
deque.offer("second");
assertEquals("first", deque.poll());
}
@Test
public void whenPush_addsAtFirst() {
final Deque<String> deque = new ArrayDeque<>();
deque.push("first");
deque.push("second");
assertEquals("second", deque.getFirst());
}
@Test
public void whenPop_removesLast() {
final Deque<String> deque = new ArrayDeque<>();
deque.push("first");
deque.push("second");
assertEquals("second", deque.pop());
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.comparable;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class ComparableUnitTest {
@Test
public void whenUsingComparable_thenSortedList() {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
Collections.sort(footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class ComparatorUnitTest {
List<Player> footballTeam;
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
}
@Test
public void whenUsingRankingComparator_thenSortedList() {
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
Collections.sort(footballTeam, playerComparator);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
@Test
public void whenUsingAgeComparator_thenSortedList() {
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
Collections.sort(footballTeam, playerComparator);
assertEquals(footballTeam.get(0)
.getName(), "John");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class Java8ComparatorUnitTest {
List<Player> footballTeam;
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
}
@Test
public void whenComparing_UsingLambda_thenSorted() {
System.out.println("************** Java 8 Comaparator **************");
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
@Test
public void whenComparing_UsingComparatorComparing_thenSorted() {
System.out.println("********* Comaparator.comparing method *********");
System.out.println("********* byRanking *********");
Comparator<Player> byRanking = Comparator.comparing(Player::getRanking);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
System.out.println("********* byAge *********");
Comparator<Player> byAge = Comparator.comparing(Player::getAge);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byAge);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Roger");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}

View File

@ -2,14 +2,24 @@ package com.baeldung.file;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import com.google.common.base.Charsets;
import com.google.common.io.CharSink;
import com.google.common.io.FileWriteMode;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.util.StreamUtils;
@ -18,6 +28,26 @@ public class FilesTest {
public static final String fileName = "src/main/resources/countries.properties";
@Before
@After
public void setup() throws Exception {
PrintWriter writer = new PrintWriter(fileName);
writer.print("UK\r\n" + "US\r\n" + "Germany\r\n");
writer.close();
}
@Test
public void whenAppendToFileUsingGuava_thenCorrect() throws IOException {
File file = new File(fileName);
CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
chs.write("Spain\r\n");
assertThat(StreamUtils.getStringFromInputStream(
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
@ -27,10 +57,38 @@ public class FilesTest {
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@After
public void revertFile() throws IOException {
PrintWriter writer = new PrintWriter(fileName);
writer.print("UK\r\n" + "US\r\n" + "Germany\r\n");
writer.close();
@Test
public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException {
File file = new File(fileName);
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
assertThat(StreamUtils.getStringFromInputStream(
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
}
@Test
public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception {
FileOutputStream fos = new FileOutputStream(fileName, true);
fos.write("Spain\r\n".getBytes());
fos.close();
assertThat(StreamUtils.getStringFromInputStream(
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException {
FileWriter fw = new FileWriter(fileName, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Spain");
bw.newLine();
bw.close();
assertThat(
StreamUtils.getStringFromInputStream(
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.loops;
import org.junit.Assert;
import org.junit.Test;
public class WhenUsingLoops {
private LoopsInJava loops = new LoopsInJava();
@Test
public void shouldRunForLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.simple_for_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunEnhancedForeachLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.enhanced_for_each_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunWhileLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunDoWhileLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.do_while_loop();
Assert.assertArrayEquals(expected, actual);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.nestedclass;
import org.junit.Test;
abstract class SimpleAbstractClass {
abstract void run();
}
public class AnonymousInner {
@Test
public void run() {
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
void run() {
System.out.println("Running Anonymous Class...");
}
};
simpleAbstractClass.run();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Enclosing {
private static int x = 1;
public static class StaticNested {
private void run() {
System.out.println("x = " + x);
}
}
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
nested.run();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewEnclosing {
private void run() {
class Local {
void run() {
System.out.println("Welcome to Baeldung!");
}
}
Local local = new Local();
local.run();
}
@Test
public void test() {
NewEnclosing newEnclosing = new NewEnclosing();
newEnclosing.run();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewOuter {
int a = 1;
static int b = 2;
public class InnerClass {
int a = 3;
static final int b = 4;
public void run() {
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("NewOuterTest.this.a = " + NewOuter.this.a);
System.out.println("NewOuterTest.b = " + NewOuter.b);
System.out.println("NewOuterTest.this.b = " + NewOuter.this.b);
}
}
@Test
public void test() {
NewOuter outer = new NewOuter();
NewOuter.InnerClass inner = outer.new InnerClass();
inner.run();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Outer {
public class Inner {
public void run() {
System.out.println("Calling test...");
}
}
@Test
public void test() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.run();
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.polymorphism;
import static org.junit.Assert.*;
import java.awt.image.BufferedImage;
import org.junit.Ignore;
import org.junit.Test;
public class PolymorphismUnitTest {
@Test
public void givenImageFile_whenFileCreated_shouldSucceed() {
ImageFile imageFile = FileManager.createImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
.getBytes(), "v1.0.0");
assertEquals(200, imageFile.getHeight());
}
// Downcasting then Upcasting
@Test
public void givenTextFile_whenTextFileCreatedAndAssignedToGenericFileAndCastBackToTextFileOnGetWordCount_shouldSucceed() {
GenericFile textFile = FileManager.createTextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
TextFile textFile2 = (TextFile) textFile;
assertEquals(6, textFile2.getWordCount());
}
// Downcasting
@Test(expected = ClassCastException.class)
public void givenGenericFile_whenCastToTextFileAndInvokeGetWordCount_shouldFail() {
GenericFile genericFile = new GenericFile();
TextFile textFile = (TextFile) genericFile;
System.out.println(textFile.getWordCount());
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.varargs;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class FormatterTest {
private final static String FORMAT = "%s %s %s";
@Test
public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() {
String actualResult = format();
assertThat(actualResult, is("empty "));
}
@Test
public void givenOneArgument_thenResultHasTwoTrailingSpace() {
String actualResult = format("baeldung");
assertThat(actualResult, is("baeldung "));
}
@Test
public void givenTwoArguments_thenOneTrailingSpaceExists() {
String actualResult = format("baeldung", "rocks");
assertThat(actualResult, is("baeldung rocks "));
}
@Test
public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() {
String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring");
assertThat(actualResult, is("baeldung rocks java"));
}
public String format() {
return format("empty", "");
}
public String format(String value) {
return format(value, "");
}
public String format(String val1, String val2) {
return String.format(FORMAT, val1, val2, "");
}
public String formatWithVarArgs(String... values) {
if (values.length == 0) {
return "no arguments given";
}
return String.format(FORMAT, values);
}
}

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -17,12 +17,15 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
<hibernate.version>5.2.12.Final</hibernate.version>
<mysql.version>6.0.6</mysql.version>
<mariaDB4j.version>2.2.3</mariaDB4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
@ -40,6 +43,21 @@
<artifactId>h2</artifactId>
<version>1.4.194</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>ch.vorburger.mariaDB4j</groupId>
<artifactId>mariaDB4j</artifactId>
<version>${mariaDB4j.version}</version>
</dependency>
</dependencies>
<build>
<finalName>hibernate5</finalName>

View File

@ -5,6 +5,7 @@ import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.OrderEntry;
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
import com.baeldung.hibernate.pojo.OrderEntryPK;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.TemporalValues;
@ -23,6 +24,7 @@ import com.baeldung.hibernate.pojo.inheritance.Person;
import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
@ -36,8 +38,14 @@ import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
return getSessionFactory(null);
}
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
@ -70,6 +78,7 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Vehicle.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(PointEntity.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
@ -86,12 +95,11 @@ public class HibernateUtil {
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Point;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class PointEntity {
@Id
@GeneratedValue
private Long id;
private Point point;
public PointEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
@Override
public String toString() {
return "PointEntity{" + "id=" + id + ", point=" + point + '}';
}
}

View File

@ -0,0 +1,97 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.PointEntity;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.Query;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class HibernateSpatialTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void shouldConvertWktToGeometry() throws ParseException {
Geometry geometry = wktToGeometry("POINT (2 5)");
assertEquals("Point", geometry.getGeometryType());
assertTrue(geometry instanceof Point);
}
@Test
public void shouldInsertAndSelectPoints() throws ParseException {
PointEntity entity = new PointEntity();
entity.setPoint((Point) wktToGeometry("POINT (1 1)"));
session.persist(entity);
PointEntity fromDb = session.find(PointEntity.class, entity.getId());
assertEquals("POINT (1 1)", fromDb.getPoint().toString());
}
@Test
public void shouldSelectDisjointPoints() throws ParseException {
insertPoint("POINT (1 2)");
insertPoint("POINT (3 4)");
insertPoint("POINT (5 6)");
Point point = (Point) wktToGeometry("POINT (3 4)");
Query query = session.createQuery("select p from PointEntity p "
+ "where disjoint(p.point, :point) = true", PointEntity.class);
query.setParameter("point", point);
assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(0)).getPoint().toString());
assertEquals("POINT (5 6)", ((PointEntity) query.getResultList().get(1)).getPoint().toString());
}
@Test
public void shouldSelectAllPointsWithinPolygon() throws ParseException {
insertPoint("POINT (1 1)");
insertPoint("POINT (1 2)");
insertPoint("POINT (3 4)");
insertPoint("POINT (5 6)");
Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true",
PointEntity.class);
query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))"));
assertEquals(3, query.getResultList().size());
assertEquals("POINT (1 1)", ((PointEntity) query.getResultList().get(0)).getPoint().toString());
assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(1)).getPoint().toString());
assertEquals("POINT (3 4)", ((PointEntity) query.getResultList().get(2)).getPoint().toString());
}
private void insertPoint(String point) throws ParseException {
PointEntity entity = new PointEntity();
entity.setPoint((Point) wktToGeometry(point));
session.persist(entity);
}
private Geometry wktToGeometry(String wellKnownText) throws ParseException {
WKTReader fromText = new WKTReader();
Geometry geom = null;
geom = fromText.read(wellKnownText);
return geom;
}
}

View File

@ -0,0 +1,10 @@
hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate-spatial
hibernate.connection.username=root
hibernate.connection.password=pass
hibernate.connection.pool_size=5
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.max_fetch_depth=5
hibernate.hbm2ddl.auto=create-drop

BIN
libraries/helloWorld.docx Normal file

Binary file not shown.

View File

@ -12,7 +12,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -2,6 +2,5 @@
- [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro)
- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback)
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback)
- [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders)

View File

@ -11,7 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -9,7 +9,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
<relativePath>../../</relativePath>
</parent>
<dependencies>

View File

@ -31,7 +31,5 @@
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -7,18 +7,22 @@ import java.util.List;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
public class InMemoryLuceneIndex {
@ -45,6 +49,7 @@ public class InMemoryLuceneIndex {
document.add(new TextField("title", title, Field.Store.YES));
document.add(new TextField("body", body, Field.Store.YES));
document.add(new SortedDocValuesField("title", new BytesRef(title)));
writter.addDocument(document);
writter.close();
@ -73,6 +78,51 @@ public class InMemoryLuceneIndex {
}
public void deleteDocument(Term term) {
try {
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
IndexWriter writter = new IndexWriter(memoryIndex, indexWriterConfig);
writter.deleteDocuments(term);
writter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public List<Document> searchIndex(Query query) {
try {
IndexReader indexReader = DirectoryReader.open(memoryIndex);
IndexSearcher searcher = new IndexSearcher(indexReader);
TopDocs topDocs = searcher.search(query, 10);
List<Document> documents = new ArrayList<>();
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
documents.add(searcher.doc(scoreDoc.doc));
}
return documents;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public List<Document> searchIndex(Query query, Sort sort) {
try {
IndexReader indexReader = DirectoryReader.open(memoryIndex);
IndexSearcher searcher = new IndexSearcher(indexReader);
TopDocs topDocs = searcher.search(query, 10, sort);
List<Document> documents = new ArrayList<>();
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
documents.add(searcher.doc(scoreDoc.doc));
}
return documents;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -4,7 +4,19 @@ import java.util.List;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.BytesRef;
import org.junit.Assert;
import org.junit.Test;
@ -20,4 +32,121 @@ public class LuceneInMemorySearchTest {
Assert.assertEquals("Hello world", documents.get(0).get("title"));
}
}
@Test
public void givenTermQueryWhenFetchedDocumentThenCorrect() {
InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
inMemoryLuceneIndex.indexDocument("activity", "running in track");
inMemoryLuceneIndex.indexDocument("activity", "Cars are running on road");
Term term = new Term("body", "running");
Query query = new TermQuery(term);
List<Document> documents = inMemoryLuceneIndex.searchIndex(query);
Assert.assertEquals(2, documents.size());
}
@Test
public void givenPrefixQueryWhenFetchedDocumentThenCorrect() {
InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
inMemoryLuceneIndex.indexDocument("article", "Lucene introduction");
inMemoryLuceneIndex.indexDocument("article", "Introduction to Lucene");
Term term = new Term("body", "intro");
Query query = new PrefixQuery(term);
List<Document> documents = inMemoryLuceneIndex.searchIndex(query);
Assert.assertEquals(2, documents.size());
}
@Test
public void givenBooleanQueryWhenFetchedDocumentThenCorrect() {
InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
inMemoryLuceneIndex.indexDocument("Destination", "Las Vegas singapore car");
inMemoryLuceneIndex.indexDocument("Commutes in singapore", "Bus Car Bikes");
Term term1 = new Term("body", "singapore");
Term term2 = new Term("body", "car");
TermQuery query1 = new TermQuery(term1);
TermQuery query2 = new TermQuery(term2);
BooleanQuery booleanQuery = new BooleanQuery.Builder().add(query1, BooleanClause.Occur.MUST)
.add(query2, BooleanClause.Occur.MUST).build();
List<Document> documents = inMemoryLuceneIndex.searchIndex(booleanQuery);
Assert.assertEquals(1, documents.size());
}
@Test
public void givenPhraseQueryWhenFetchedDocumentThenCorrect() {
InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
inMemoryLuceneIndex.indexDocument("quotes", "A rose by any other name would smell as sweet.");
Query query = new PhraseQuery(1, "body", new BytesRef("smell"), new BytesRef("sweet"));
List<Document> documents = inMemoryLuceneIndex.searchIndex(query);
Assert.assertEquals(1, documents.size());
}
@Test
public void givenFuzzyQueryWhenFetchedDocumentThenCorrect() {
InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
inMemoryLuceneIndex.indexDocument("article", "Halloween Festival");
inMemoryLuceneIndex.indexDocument("decoration", "Decorations for Halloween");
Term term = new Term("body", "hallowen");
Query query = new FuzzyQuery(term);
List<Document> documents = inMemoryLuceneIndex.searchIndex(query);
Assert.assertEquals(2, documents.size());
}
@Test
public void givenWildCardQueryWhenFetchedDocumentThenCorrect() {
InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
inMemoryLuceneIndex.indexDocument("article", "Lucene introduction");
inMemoryLuceneIndex.indexDocument("article", "Introducing Lucene with Spring");
Term term = new Term("body", "intro*");
Query query = new WildcardQuery(term);
List<Document> documents = inMemoryLuceneIndex.searchIndex(query);
Assert.assertEquals(2, documents.size());
}
@Test
public void givenSortFieldWhenSortedThenCorrect() {
InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
inMemoryLuceneIndex.indexDocument("Ganges", "River in India");
inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia");
inMemoryLuceneIndex.indexDocument("Amazon", "Rain forest river");
inMemoryLuceneIndex.indexDocument("Rhine", "Belongs to Europe");
inMemoryLuceneIndex.indexDocument("Nile", "Longest River");
Term term = new Term("body", "river");
Query query = new WildcardQuery(term);
SortField sortField = new SortField("title", SortField.Type.STRING_VAL, false);
Sort sortByTitle = new Sort(sortField);
List<Document> documents = inMemoryLuceneIndex.searchIndex(query, sortByTitle);
Assert.assertEquals(4, documents.size());
Assert.assertEquals("Amazon", documents.get(0).getField("title").stringValue());
}
@Test
public void whenDocumentDeletedThenCorrect() {
InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer());
inMemoryLuceneIndex.indexDocument("Ganges", "River in India");
inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia");
Term term = new Term("title", "ganges");
inMemoryLuceneIndex.deleteDocument(term);
Query query = new TermQuery(term);
List<Document> documents = inMemoryLuceneIndex.searchIndex(query);
Assert.assertEquals(0, documents.size());
}
}

1
muleesb/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
# Add any directories, files, or patterns you don't want to be tracked by version control

View File

@ -0,0 +1 @@
DEFAULT_PARTITION

View File

View File

View File

View File

5
muleesb/mule-project.xml Normal file
View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<mule-project xmlns="http://www.mulesoft.com/tooling/project" runtimeId="org.mule.tooling.server.3.9.0.ee" schemaVersion="5.3.0.0">
<name>muleesb</name>
<description></description>
</mule-project>

214
muleesb/pom.xml Normal file
View File

@ -0,0 +1,214 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>muleesb</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>mule</packaging>
<name>Mule muleesb Application</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<mule.version>3.8.1</mule.version>
<mule.tools.version>1.2</mule.tools.version>
<munit.version>1.3.6</munit.version>
<mule.munit.support.version>3.9.0</mule.munit.support.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.mule.tools.maven</groupId>
<artifactId>mule-app-maven-plugin</artifactId>
<version>${mule.tools.version}</version>
<extensions>true</extensions>
<configuration>
<copyToAppsDirectory>true</copyToAppsDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.mule.tools</groupId>
<artifactId>muleesb-maven-plugin</artifactId>
<version>1.0</version>
<configuration>
<muleVersion>3.7.0</muleVersion>
<applications>/home/abir/AnypointStudio/workspace/variablescopetest</applications>
</configuration>
<executions>
<execution>
<id>deploy</id>
<goals>
<goal>start</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<id>add-resource</id>
<phase>generate-resources</phase>
<goals>
<goal>add-resource</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/main/app/</directory>
</resource>
<resource>
<directory>mappings/</directory>
</resource>
<resource>
<directory>src/main/api/</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.mulesoft.munit.tools</groupId>
<artifactId>munit-maven-plugin</artifactId>
<version>${munit.version}</version>
<executions>
<execution>
<id>test</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
<configuration>
<coverage>
<runCoverage>true</runCoverage>
<formats>
<format>html</format>
</formats>
</coverage>
</configuration>
</plugin>
</plugins>
<testResources>
<testResource>
<directory>src/test/munit</directory>
</testResource>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
</build>
<!-- Mule Dependencies -->
<dependencies>
<!-- Xml configuration -->
<dependency>
<groupId>org.mule.modules</groupId>
<artifactId>mule-module-spring-config</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<!-- Mule Transports -->
<dependency>
<groupId>org.mule.transports</groupId>
<artifactId>mule-transport-file</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mule.transports</groupId>
<artifactId>mule-transport-http</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mule.transports</groupId>
<artifactId>mule-transport-jdbc</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mule.transports</groupId>
<artifactId>mule-transport-jms</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mule.transports</groupId>
<artifactId>mule-transport-vm</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<!-- Mule Modules -->
<dependency>
<groupId>org.mule.modules</groupId>
<artifactId>mule-module-scripting</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mule.modules</groupId>
<artifactId>mule-module-xml</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<!-- for testing -->
<dependency>
<groupId>org.mule.tests</groupId>
<artifactId>mule-tests-functional</artifactId>
<version>${mule.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mule.modules</groupId>
<artifactId>mule-module-apikit</artifactId>
<version>${mule.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.mulesoft.munit</groupId>
<artifactId>mule-munit-support</artifactId>
<version>${mule.munit.support.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.mulesoft.munit</groupId>
<artifactId>munit-runner</artifactId>
<version>${munit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>Central</id>
<name>Central</name>
<url>http://repo1.maven.org/maven2/</url>
<layout>default</layout>
</repository>
<repository>
<id>mulesoft-releases</id>
<name>MuleSoft Releases Repository</name>
<url>http://repository.mulesoft.org/releases/</url>
<layout>default</layout>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>mulesoft-release</id>
<name>mulesoft release repository</name>
<layout>default</layout>
<url>http://repository.mulesoft.org/releases/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

View File

View File

@ -0,0 +1,6 @@
#** GENERATED CONTENT ** Mule Application Deployment Descriptor
#Mon Nov 06 15:54:37 BDT 2017
redeployment.enabled=true
encoding=UTF-8
domain=default
config.resources=variablescopetest.xml

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd">
<http:listener-config name="HTTP_Listener_Configuration" host="localhost" port="8081" doc:name="HTTP Listener Configuration"/>
<flow name="Flow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP" allowedMethods="POST"/>
<logger message="Original paylaod: #[payload]" level="INFO" doc:name="Logger"/>
<custom-transformer class="com.baeldung.transformer.InitializationTransformer" doc:name="Java"/>
<logger message="Payload After Initialization: #[payload]" level="INFO" doc:name="Logger"/>
<set-variable variableName="f1" value="#['Flow Variable 1']" doc:name="F1"/>
<set-session-variable variableName="s1" value="#['Session variable 1']" doc:name="S1"/>
<vm:outbound-endpoint exchange-pattern="request-response" path="test" doc:name="VM"/>
</flow>
<flow name="Flow1">
<vm:inbound-endpoint exchange-pattern="request-response" path="test" doc:name="VM"/>
<custom-transformer encoding="ISO-8859-2" class="com.baeldung.transformer.InvokingMessageComponent" doc:name="Java"/>
<logger message="Payload after Java Component : #[payload]" level="INFO" doc:name="Logger"/>
<set-variable variableName="f2" value="#['Flow Variable 2']" doc:name="F2"/>
<set-session-variable variableName="s2" value="#['Session Variable 2']" doc:name="S2"/>
<flow-ref name="Flow2" doc:name="Flow2"/>
<logger message="Payload: Returned form flow 2: #[payload] . Variables: Flow var and Session vars : S1-#[sessionVars.s1], S2-#[sessionVars.s2] ,F1-#[flowVars.f1], F2-#[flowVars.f2],F3-#[flowVars.f3]" level="INFO" doc:name="Logger"/>
</flow>
<flow name="Flow2">
<component class="com.baeldung.transformer.FromFlow2Component" doc:name="Java"/>
<logger message="In Flow 2: Flow Variables :: #[flowVars.f1],#[flowVars.f2] and Session Variabless: #[sessionVars.s1] ,#[sessionVars.s2]" level="INFO" doc:name="Logger"/>
<set-variable variableName="f3" value="#['Flow Variable 3 ']" doc:name="F3"/>
</flow>
</mule>

View File

@ -0,0 +1,18 @@
package com.baeldung.transformer;
import org.mule.api.MuleEventContext;
import org.mule.api.MuleMessage;
import org.mule.api.lifecycle.Callable;
public class FromFlow2Component implements Callable {
@Override
public Object onCall(MuleEventContext eventContext) throws Exception {
MuleMessage message = eventContext.getMessage();
message.setPayload("Converted in flow 2");
return message;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.transformer;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.api.transport.PropertyScope;
import org.mule.transformer.AbstractMessageTransformer;
public class InitializationTransformer extends AbstractMessageTransformer {
@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// TODO Auto-generated method stub
String payload = null;
try {
payload = message.getPayloadAsString();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("Logged Payload: "+payload);
message.setPayload("Payload from Initialization");
message.setProperty("outboundKey", "outboundpropertyvalue",PropertyScope.OUTBOUND);
return message;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.transformer;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
public class InvokingMessageComponent extends AbstractMessageTransformer {
@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// TODO Auto-generated method stub
String InboundProp = (String) message.getInboundProperty("outboundKey");
System.out.println("InboundProp:" + InboundProp);
return InboundProp;
}
}

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Appenders>
<RollingFile name="file" fileName="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}variablescopetest.log"
filePattern="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}variablescopetest-%i.log">
<PatternLayout pattern="%d [%t] %-5p %c - %m%n" />
<SizeBasedTriggeringPolicy size="10 MB" />
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Loggers>
<!-- CXF is used heavily by Mule for web services -->
<AsyncLogger name="org.apache.cxf" level="WARN"/>
<!-- Apache Commons tend to make a lot of noise which can clutter the log-->
<AsyncLogger name="org.apache" level="WARN"/>
<!-- Reduce startup noise -->
<AsyncLogger name="org.springframework.beans.factory" level="WARN"/>
<!-- Mule classes -->
<AsyncLogger name="org.mule" level="INFO"/>
<AsyncLogger name="com.mulesoft" level="INFO"/>
<!-- Reduce DM verbosity -->
<AsyncLogger name="org.jetel" level="WARN"/>
<AsyncLogger name="Tracking" level="WARN"/>
<AsyncRoot level="INFO">
<AppenderRef ref="file" />
</AsyncRoot>
</Loggers>
</Configuration>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:mock="http://www.mulesoft.org/schema/mule/mock" xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:munit="http://www.mulesoft.org/schema/mule/munit" xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:core="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:test="http://www.mulesoft.org/schema/mule/test"
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/mock http://www.mulesoft.org/schema/mule/mock/current/mule-mock.xsd
http://www.mulesoft.org/schema/mule/munit http://www.mulesoft.org/schema/mule/munit/current/mule-munit.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/test http://www.mulesoft.org/schema/mule/test/current/mule-test.xsd">
<munit:config name="munit" doc:name="MUnit configuration" />
<spring:beans>
<spring:import resource="classpath:variablescopetest.xml" />
</spring:beans>
<munit:test name="variablescopetest-test-suite-FlowTest"
description="Test">
<mock:when messageProcessor="vm:outbound-endpoint" doc:name="VM">
<mock:with-attributes>
<mock:with-attribute name="path" whereValue="test"/>
</mock:with-attributes>
<mock:then-return payload="#['Converted in flow 2']"/>
</mock:when>
<flow-ref name="Flow" doc:name="Flow-ref to Flow" />
<munit:assert-on-equals message="Flow variable doesn't have the actual value"
expectedValue="#['Flow Variable 1']" actualValue="#[flowVars.f1]"
doc:name="Assert Equals" />
</munit:test>
<munit:test name="variablescopetest-test-suite-Flow1Test"
description="Test">
<flow-ref name="Flow1" doc:name="Flow-ref to Flow1" />
</munit:test>
<munit:test name="variablescopetest-test-suite-Flow2Test" description="Test">
<flow-ref name="Flow2" doc:name="Flow-ref to Flow2"/>
</munit:test>
</mule>

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