Merge remote-tracking branch 'origin/master'

Conflicts:
	jsf/pom.xml
This commit is contained in:
Slavisa Baeldung 2016-06-17 15:46:46 +02:00
commit aaed0434cb
195 changed files with 6782 additions and 575 deletions

4
.gitignore vendored
View File

@ -7,8 +7,11 @@
# Eclipse
.settings/
*.project
*.classpath
.prefs
*.prefs
.metadata/
# Intellij
.idea/
@ -23,3 +26,4 @@ log/
target/
spring-openid/src/main/resources/application.properties
.recommenders/

View File

@ -41,6 +41,12 @@
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>

View File

@ -0,0 +1,16 @@
package com.baeldung.datetime;
import java.time.Duration;
import java.time.LocalTime;
import java.time.Period;
public class UseDuration {
public LocalTime modifyDates(LocalTime localTime,Duration duration){
return localTime.plus(duration);
}
public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
return Duration.between(localTime1, localTime2);
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.datetime;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
public class UseLocalDate {
public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
return LocalDate.of(year, month, dayOfMonth);
}
public LocalDate getLocalDateUsingParseMethod(String representation){
return LocalDate.parse(representation);
}
public LocalDate getLocalDateFromClock(){
LocalDate localDate = LocalDate.now();
return localDate;
}
public LocalDate getNextDay(LocalDate localDate){
return localDate.plusDays(1);
}
public LocalDate getPreviousDay(LocalDate localDate){
return localDate.minus(1, ChronoUnit.DAYS);
}
public DayOfWeek getDayOfWeek(LocalDate localDate){
DayOfWeek day = localDate.getDayOfWeek();
return day;
}
public LocalDate getFirstDayOfMonth(){
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
return firstDayOfMonth;
}
public LocalDateTime getStartOfDay(LocalDate localDate){
LocalDateTime startofDay = localDate.atStartOfDay();
return startofDay;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
public class UseLocalDateTime {
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
return LocalDateTime.parse(representation);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.datetime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
public class UseLocalTime {
public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
LocalTime localTime = LocalTime.of(hour, min, seconds);
return localTime;
}
public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
LocalTime localTime = LocalTime.parse(timeRepresentation);
return localTime;
}
public LocalTime getLocalTimeFromClock(){
LocalTime localTime = LocalTime.now();
return localTime;
}
public LocalTime addAnHour(LocalTime localTime){
LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
return newTime;
}
public int getHourFromLocalTime(LocalTime localTime){
return localTime.getHour();
}
public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
return localTime.withMinute(minute);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.datetime;
import java.time.LocalDate;
import java.time.Period;
public class UsePeriod {
public LocalDate modifyDates(LocalDate localDate,Period period){
return localDate.plus(period);
}
public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
return Period.between(localDate1, localDate2);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
public class UseToInstant {
public LocalDateTime convertDateToLocalDate(Date date){
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
return localDateTime;
}
public LocalDateTime convertDateToLocalDate(Calendar calendar){
LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
return localDateTime;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class UseZonedDateTime {
public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
return zonedDateTime;
}
}

View File

@ -0,0 +1,91 @@
package com.baeldung.enums;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;
public class Pizza {
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses =
EnumSet.of(PizzaStatusEnum.DELIVERED);
private PizzaStatusEnum status;
public enum PizzaStatusEnum {
ORDERED(5) {
@Override
public boolean isOrdered() {
return true;
}
},
READY(2) {
@Override
public boolean isReady() {
return true;
}
},
DELIVERED(0) {
@Override
public boolean isDelivered() {
return true;
}
};
private int timeToDelivery;
public boolean isOrdered() {
return false;
}
public boolean isReady() {
return false;
}
public boolean isDelivered() {
return false;
}
public int getTimeToDelivery() {
return timeToDelivery;
}
PizzaStatusEnum(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}
public PizzaStatusEnum getStatus() {
return status;
}
public void setStatus(PizzaStatusEnum status) {
this.status = status;
}
public boolean isDeliverable() {
return this.status.isReady();
}
public void printTimeToDeliver() {
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
}
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
}
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
return pzList.stream().collect(
Collectors.groupingBy(Pizza::getStatus,
() -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
this.setStatus(PizzaStatusEnum.DELIVERED);
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.enums;
public enum PizzaDeliveryStrategy {
EXPRESS {
@Override
public void deliver(Pizza pz) {
System.out.println("Pizza will be delivered in express mode");
}
},
NORMAL {
@Override
public void deliver(Pizza pz) {
System.out.println("Pizza will be delivered in normal mode");
}
};
public abstract void deliver(Pizza pz);
}

View File

@ -0,0 +1,22 @@
package com.baeldung.enums;
public enum PizzaDeliverySystemConfiguration {
INSTANCE;
PizzaDeliverySystemConfiguration() {
// Do the configuration initialization which
// involves overriding defaults like delivery strategy
}
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
public static PizzaDeliverySystemConfiguration getInstance() {
return INSTANCE;
}
public PizzaDeliveryStrategy getDeliveryStrategy() {
return deliveryStrategy;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.streamApi;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Created by Alex Vengr
*/
public class Product {
private int price;
private String name;
private boolean utilize;
public Product(int price, String name) {
this(price);
this.name = name;
}
public Product(int price) {
this.price = price;
}
public Product() {
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Stream<String> streamOf(List<String> list) {
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.datetime;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import org.junit.Assert;
import org.junit.Test;
public class UseLocalDateTest {
UseLocalDate useLocalDate = new UseLocalDate();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalDate(){
Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString());
}
@Test
public void givenString_whenUsingParse_thenLocalDate(){
Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
}
@Test
public void whenUsingClock_thenLocalDate(){
Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock());
}
@Test
public void givenDate_whenUsingPlus_thenNextDay(){
Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now()));
}
@Test
public void givenDate_whenUsingMinus_thenPreviousDay(){
Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now()));
}
@Test
public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){
Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
}
@Test
public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){
Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth());
}
@Test
public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.datetime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import org.junit.Assert;
import org.junit.Test;
public class UseLocalDateTimeTest {
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
@Test
public void givenString_whenUsingParse_thenLocalDateTime(){
Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
Assert.assertEquals(LocalTime.of(6,30),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.datetime;
import java.time.LocalTime;
import org.junit.Assert;
import org.junit.Test;
public class UseLocalTimeTest {
UseLocalTime useLocalTime = new UseLocalTime();
@Test
public void givenValues_whenUsingFactoryOf_thenLocalTime(){
Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString());
}
@Test
public void givenString_whenUsingParse_thenLocalTime(){
Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
}
@Test
public void givenTime_whenAddHour_thenLocalTime(){
Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString());
}
@Test
public void getHourFromLocalTime(){
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1)));
}
@Test
public void getLocalTimeWithMinuteSetToValue(){
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.datetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Assert;
import org.junit.Test;
public class UsePeriodTest {
UsePeriod usingPeriod=new UsePeriod();
@Test
public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){
Period period = Period.ofDays(1);
LocalDate localDate = LocalDate.parse("2007-05-10");
Assert.assertEquals(localDate.plusDays(1),usingPeriod.modifyDates(localDate, period));
}
@Test
public void givenDates_thenGetPeriod(){
LocalDate localDate1 = LocalDate.parse("2007-05-10");
LocalDate localDate2 = LocalDate.parse("2007-05-15");
Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2));
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Assert;
import org.junit.Test;
public class UseZonedDateTimeTest {
UseZonedDateTime zonedDateTime=new UseZonedDateTime();
@Test
public void givenZoneId_thenZonedDateTime(){
ZoneId zoneId=ZoneId.of("Europe/Paris");
ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime));
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.enums;
import org.junit.Test;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import static junit.framework.TestCase.assertTrue;
public class PizzaTest {
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {
Pizza testPz = new Pizza();
testPz.setStatus(Pizza.PizzaStatusEnum.READY);
assertTrue(testPz.isDeliverable());
}
@Test
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
List<Pizza> pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
Pizza pz2 = new Pizza();
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz3 = new Pizza();
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz4 = new Pizza();
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
assertTrue(undeliveredPzs.size() == 3);
}
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
List<Pizza> pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
Pizza pz2 = new Pizza();
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz3 = new Pizza();
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz4 = new Pizza();
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
}
@Test
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza();
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
}
}

View File

@ -0,0 +1,263 @@
package com.baeldung.java8;
import com.baeldung.streamApi.Product;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.*;
import static org.junit.Assert.*;
public class Java8StreamApiTest {
private long counter;
private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class);
private List<Product> productList;
@Before
public void init() {
productList = Arrays.asList(
new Product(23, "potatoes"), new Product(14, "orange"),
new Product(13, "lemon"), new Product(23, "bread"),
new Product(13, "sugar"));
}
@Test
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
long size = list.stream().skip(1)
.map(element -> element.substring(0, 3)).count();
assertEquals(list.size() - 1, size);
}
@Test
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
counter = 0;
long sizeFirst = list.stream()
.skip(2).map(element -> {
wasCalled();
return element.substring(0, 3);
}).count();
assertEquals(1, counter);
counter = 0;
long sizeSecond = list.stream().map(element -> {
wasCalled();
return element.substring(0, 3);
}).skip(2).count();
assertEquals(3, counter);
}
@Test
public void createEmptyStream_whenEmpty_thenCorrect() {
Stream<String> streamEmpty = Stream.empty();
assertEquals(0, streamEmpty.count());
List<String> names = Collections.emptyList();
Stream<String> streamOf = Product.streamOf(names);
assertTrue(streamOf.count() == 0);
}
@Test
public void createStream_whenCreated_thenCorrect() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> streamOfCollection = collection.stream();
assertEquals(3, streamOfCollection.count());
Stream<String> streamOfArray = Stream.of("a", "b", "c");
assertEquals(3, streamOfArray.count());
String[] arr = new String[]{"a", "b", "c"};
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
assertEquals(2, streamOfArrayPart.count());
IntStream intStream = IntStream.range(1, 3);
LongStream longStream = LongStream.rangeClosed(1, 3);
Random random = new Random();
DoubleStream doubleStream = random.doubles(3);
assertEquals(2, intStream.count());
assertEquals(3, longStream.count());
assertEquals(3, doubleStream.count());
IntStream streamOfChars = "abc".chars();
IntStream str = "".chars();
assertEquals(3, streamOfChars.count());
Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
assertEquals("a", streamOfString.findFirst().get());
Path path = getPath();
Stream<String> streamOfStrings = null;
try {
streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
} catch (IOException e) {
log.error("Error creating streams from paths {}", path, e.getMessage(), e);
}
assertEquals("a", streamOfStrings.findFirst().get());
Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
assertEquals(3, streamBuilder.count());
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
assertEquals(10, streamGenerated.count());
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
assertTrue(40 <= streamIterated.findAny().get());
}
@Test
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
Optional<String> stream = list.stream()
.filter(element -> {
log.info("filter() was called");
return element.contains("2");
}).map(element -> {
log.info("map() was called");
return element.toUpperCase();
}).findFirst();
}
@Test
public void reduce_whenExpected_thenCorrect() {
OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
assertEquals(6, reduced.getAsInt());
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
assertEquals(16, reducedTwoParams);
int reducedThreeParams = Stream.of(1, 2, 3)
.reduce(10, (a, b) -> a + b, (a, b) -> {
log.info("combiner was called");
return a + b;
});
assertEquals(16, reducedThreeParams);
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream()
.reduce(10, (a, b) -> a + b, (a, b) -> {
log.info("combiner was called");
return a + b;
});
assertEquals(36, reducedThreeParamsParallel);
}
@Test
public void collecting_whenAsExpected_thenCorrect() {
List<String> collectorCollection = productList.stream()
.map(Product::getName).collect(Collectors.toList());
assertTrue(collectorCollection instanceof List);
assertEquals(5, collectorCollection.size());
String listToString = productList.stream().map(Product::getName)
.collect(Collectors.joining(", ", "[", "]"));
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
assertTrue(17.2 == averagePrice);
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
assertEquals(86, summingPrice);
IntSummaryStatistics statistics = productList.stream()
.collect(Collectors.summarizingInt(Product::getPrice));
assertEquals(23, statistics.getMax());
Map<Integer, List<Product>> collectorMapOfLists = productList.stream()
.collect(Collectors.groupingBy(Product::getPrice));
assertEquals(3, collectorMapOfLists.keySet().size());
Map<Boolean, List<Product>> mapPartioned = productList.stream()
.collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
assertEquals(2, mapPartioned.keySet().size());
}
@Test(expected = UnsupportedOperationException.class)
public void collect_whenThrows_thenCorrect() {
Set<Product> unmodifiableSet = productList.stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(),
Collections::unmodifiableSet));
unmodifiableSet.add(new Product(4, "tea"));
}
@Test
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
Collector<Product, ?, LinkedList<Product>> toLinkedList =
Collector.of(LinkedList::new, LinkedList::add,
(first, second) -> {
first.addAll(second);
return first;
});
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
assertTrue(linkedListOfPersons.containsAll(productList));
}
@Test
public void parallelStream_whenWorks_thenCorrect() {
Stream<Product> streamOfCollection = productList.parallelStream();
boolean isParallel = streamOfCollection.isParallel();
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12)
.anyMatch(price -> price > 200);
assertTrue(isParallel && haveBigPrice);
}
@Test
public void parallel_whenIsParallel_thenCorrect() {
IntStream intStreamParallel =
IntStream.range(1, 150).parallel().map(element -> element * 34);
boolean isParallel = intStreamParallel.isParallel();
assertTrue(isParallel);
}
@Test
public void parallel_whenIsSequential_thenCorrect() {
IntStream intStreamParallel =
IntStream.range(1, 150).parallel().map(element -> element * 34);
IntStream intStreamSequential = intStreamParallel.sequential();
boolean isParallel = intStreamParallel.isParallel();
assertFalse(isParallel);
}
private Path getPath() {
Path path = null;
try {
path = Files.createTempFile(null, ".txt");
} catch (IOException e) {
log.error(e.getMessage());
}
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write("a\nb\nc");
} catch (IOException e) {
log.error(e.getMessage());
}
return path;
}
private void wasCalled() {
counter++;
}
}

View File

@ -9,7 +9,11 @@
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>4.01</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
@ -122,8 +126,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

View File

@ -0,0 +1,110 @@
package com.baeldung.enums;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections15.Predicate;
import java.io.IOException;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;
public class Pizza {
private static EnumSet<PizzaStatus> undeliveredPizzaStatuses =
EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
private PizzaStatus status;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum PizzaStatus {
ORDERED(5) {
@Override
public boolean isOrdered() {
return true;
}
},
READY(2) {
@Override
public boolean isReady() {
return true;
}
},
DELIVERED(0) {
@Override
public boolean isDelivered() {
return true;
}
};
private int timeToDelivery;
public boolean isOrdered() {
return false;
}
public boolean isReady() {
return false;
}
public boolean isDelivered() {
return false;
}
@JsonProperty("timeToDelivery")
public int getTimeToDelivery() {
return timeToDelivery;
}
PizzaStatus(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}
public PizzaStatus getStatus() {
return status;
}
public void setStatus(PizzaStatus status) {
this.status = status;
}
public boolean isDeliverable() {
return this.status.isReady();
}
public void printTimeToDeliver() {
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
}
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
return input.stream().filter(
(s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
.collect(Collectors.toList());
}
public static EnumMap<PizzaStatus, List<Pizza>>
groupPizzaByStatus(List<Pizza> pzList) {
return pzList.stream().collect(
Collectors.groupingBy(Pizza::getStatus,
() -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
this.setStatus(PizzaStatus.DELIVERED);
}
}
public static String getJsonString(Pizza pz) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz);
}
private static Predicate<Pizza> thatAreNotDelivered() {
return entry -> undeliveredPizzaStatuses.contains(entry.getStatus());
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.enums;
public enum PizzaDeliveryStrategy {
EXPRESS {
@Override
public void deliver(Pizza pz) {
System.out.println("Pizza will be delivered in express mode");
}
},
NORMAL {
@Override
public void deliver(Pizza pz) {
System.out.println("Pizza will be delivered in normal mode");
}
};
public abstract void deliver(Pizza pz);
}

View File

@ -0,0 +1,21 @@
package com.baeldung.enums;
public enum PizzaDeliverySystemConfiguration {
INSTANCE;
PizzaDeliverySystemConfiguration() {
// Do the configuration initialization which
// involves overriding defaults like delivery strategy
}
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
public static PizzaDeliverySystemConfiguration getInstance() {
return INSTANCE;
}
public PizzaDeliveryStrategy getDeliveryStrategy() {
return deliveryStrategy;
}
}

View File

@ -0,0 +1,80 @@
package org.baeldung.java.enums;
import com.baeldung.enums.Pizza;
import org.junit.Test;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import static junit.framework.TestCase.assertTrue;
public class PizzaTest {
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {
Pizza testPz = new Pizza();
testPz.setStatus(Pizza.PizzaStatus.READY);
assertTrue(testPz.isDeliverable());
}
@Test
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
List<Pizza> pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
Pizza pz2 = new Pizza();
pz2.setStatus(Pizza.PizzaStatus.ORDERED);
Pizza pz3 = new Pizza();
pz3.setStatus(Pizza.PizzaStatus.ORDERED);
Pizza pz4 = new Pizza();
pz4.setStatus(Pizza.PizzaStatus.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
assertTrue(undeliveredPzs.size() == 3);
}
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
List<Pizza> pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
Pizza pz2 = new Pizza();
pz2.setStatus(Pizza.PizzaStatus.ORDERED);
Pizza pz3 = new Pizza();
pz3.setStatus(Pizza.PizzaStatus.ORDERED);
Pizza pz4 = new Pizza();
pz4.setStatus(Pizza.PizzaStatus.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
EnumMap<Pizza.PizzaStatus, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
assertTrue(map.get(Pizza.PizzaStatus.DELIVERED).size() == 1);
assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2);
assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1);
}
@Test
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza();
pz.setStatus(Pizza.PizzaStatus.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED);
}
}

12
dependency-injection/.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
RemoteSystemsTempFiles/
.classpath
.project
.settings/
bin/
.metadata/
docs/*.autosave
docs/*.autosave
.recommenders/
build/
.gradle/
.DS_Store

View File

@ -0,0 +1,43 @@
apply plugin: 'java'
apply plugin: 'eclipse'
allprojects {
apply plugin: 'java'
sourceCompatibility = 1.6
targetCompatibility = 1.6
}
repositories {
mavenCentral()
}
sourceSets {
main {
resources.srcDirs = ["src/main/java","src/main/resources"]
}
test {
resources.srcDirs = ["src/main/java", "src/main/resources", "src/test/resources"]
}
}
configurations {
compile
}
test {
testLogging {
events 'started', 'passed'
}
}
dependencies {
testCompile('junit:junit:4.11')
testCompile('org.mockito:mockito-all:1.10.19')
testCompile group: 'org.springframework', name: 'spring-test', version: '4.2.6.RELEASE'
testCompile group: 'org.springframework', name: 'spring-core', version: '4.2.6.RELEASE'
testCompile group: 'org.springframework', name: 'spring-beans', version: '4.2.6.RELEASE'
testCompile group: 'org.springframework', name: 'spring-context', version: '4.2.6.RELEASE'
testCompile group: 'javax.inject', name: 'javax.inject', version: '1'
testRuntime('junit:junit:4.11')
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -0,0 +1 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>7Vjvb+I4EP1rkO4+7KkhhW0/8qt3J3V1Velq7z5VbmKIb50M55hS9q/fGXtMEgLXrprthwqEEH6ZOJ5573nAvXiSP/1uxCr7BKnUvf5Z+tSLp71+/6If4ycBWw8MBpceWBqVeiiqgLn6Jhk8Y3StUlk2Ai2AtmrVBBMoCpnYBiaMgU0zbAG6+dSVWIYnVsA8EbqNflGpzUJawwr/Q6plFp4cDTm/B5F8XRpYF/y8Xj9euJe/nIswFydaZiKFTQ2KZ1hWA4Az07f8aSI1lTaUzd93deTqbt1GFry2Z24I67DbkLtMsRQ8BGMzWEIh9KxCxy4/STOc4SizucavEX7Fh5rt34y7wT80+G3ghumImKFZV7K4y1Th0SuFK/K3/Cut3bIaxNoCQtUKrgFW/By/Zlro0bQZKmFtEo7CsROSMEvJUR93JUclS8glLhlDjNTCqsfm7II1tdzF8a2YlqC7QsAKVGHL2sw3BGAAuyO6HPgZ2Rz9yC0jcIRf/IxhVFtaBTkeD3PKeT4KveYMrpTU6QgLulFGplOZQ4v1cqNyLQqit0boAgobtEBjodUSaZsmWGdpEHiUxir0zYgvWOJonGRKp9diC2uqc2nRFGE0zsCobzitCM/Ay8Yy6WiwesSc7mRtGFlizE2gmO700LUoCaCYBLQWq1I97BacI9mqGIO1kHNQyJR0NwENmAYWINg0iIsSk4GwI/JqC4dvCO5mgmNmZFNtJfGAQ7LaNnJ5cVxpNXX8L/m88dbI/0AbIAlgKtF3qSwSXNYIwZF5UNYIs61d2JcF1sCRVkmitAa+ylC4ApxkFrVaMhSkouWCZjgslHIlElUsr13M9LxCbrkqBG0yZeUccVrTBvsNbQs430K73SRTKa7dbUtWWOG5J6LZh5jHYIxvLPiEtqIB5jXBMVIYxvimcGMnUGB+guwaTyUKayNJXC/ThGO5rYngcu4dz4kgxL1GBOctEbSI1Wrf657Y0O6c+3+Y1Ry5cC2CabxzW/YHN32D6rhNNUH7FGrxIPUNlMoqoPmNj92j9g3YG7zQwh04mJtDgzxMYd/D958+z+/ux7P70ee7v778eTub3k/AGPw1pNnfj4BTngz9syQxZPrfwtA8RU0TL9m8Tz29w54+PG829egje73GfxQ00ejqjL2Gf/8Dcb+ru93Re31uDZrs5PZXuN157Efa90G2u3A7C+vUvjtj70D7PsheB+2bDwJa7duC9+gvv54c+yacH+jPP82xEa+uxvqt/G+N/7bdOcAzDLued7SOVCo6DKG+uNeyX0I1e5h47aALRhfNLrj7q1ur8sEid9AEo/bBRjjleSfVHfJJ0O43xiWPa9UNley8uu2Tg3dW3eiCBRSqG/Nfre6ri8PqDNcf4VXn5PHsOw==</diagram></mxfile>

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>7Vhdb9s4EPw1fuwhtqK0eYw/ctdDeijqHO7uyWAkWmJLcX0UFcf99d2llpZkKUiKOHkobBiGOVx+zcxybY2iWfHwuxWb/BOkUo8mZ+nDKJqPJpMPkwg/CdjVQBxf1kBmVVpD4wZYqu+SwTNGK5XKshPoALRTmy6YgDEycR1MWAvbbtgadHfVjcjCig2wTITuo/+o1OXhWBcN/odUWR5WHl/w+e5E8i2zUBlebzSJ1v5VdxcizMUHLXORwrYFRQuk1QLgzPSteJhJTdQG2upx14/07vdtpeG9PTEg7MPtwtllilRwE6zLIQMj9KJBp/58kmY4w1buCo1fx/gVF7W7fxn3jf+o8Vvsm+kVKUOzbqS5zZWp0WuFO6qHfJXO7dgNonKAULODG4ANr1PvmTb66LEZKqGyCUdh2xtJ2Exy1Ps95ehkCYXELWOIlVo4dd+dXbCnsn1cwyt+YWqHaeal74WueNJrJXX60XxF985lAT0Vyq0qtDBEd4vgNRgXtKG20CpDGucJnltaBO6ldQp9fMUdjjibJrnS6Y3YQUXnLh2aNLSmOVj1HacVYQ3sto5FQMO3I5Y0krWyssSYz4FyGllDN6IkgGIS0FpsSnW333CB5CszBeeg4KBwUvLBDDTgMZCAkDZBbDqY5OvlMbn7QoYB7HK+jUJz26R2FDOWt9P6gsGXSM83YUv6d9TrlR/PJaZCKk2CO7tC+MreKWeF3bU6Dp2BNHjdGleUzsI3Gbgz4F2zbtHJUHCLlmuaYdgr5UYkymQ3PmZ+3iBfmBiCtrlycok47WmLJYAyFedba5/guUpx7/6mcMKJWn7SegPKOE9mPMU30juj2yHGc82wjSqGNr4p3LoZGDyfwHE4TKK3tpL89Txb+Lzr24J9EK7zp3wQ4l5ig/OeDXrCanWY7rWwoQL5C+CnVS1QC39rs4y3/hZ956fvSB31pSboUEIt7qT+DKVyCmh+W8ceSPsG6sXM4FPqfXi5ePGAeHiEszVd4k2qrj79vbxdTRerj3/9uZjdLuarZZUksizXldac4feAk55S+rVMEW7st0hpnqLliudc36fCfsTCHr/vVvaIk70l/76It+W/PEJh978de4XdX491qi+dxRw7JfsLkt2n2M/U70G1j5HsbKxT/T6aegP1e1C9I9Rv/nPeq98OOEdP+foWig8U51fL1zHvrqX5F/l/pbCUPUNhX/Ae5ZGooscTVBQP6vVzpOYMJl2PUALPw88bJvmS/3C2SB7k+AgVcNx/rBEeu/wi5EYHvy8u+hUnEHl0cvsPDn4xcuMD58avRi42m0eqvq/12Dpa/AA=</diagram></mxfile>

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -0,0 +1 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>7VhZbxs3EP41AtqHFDqydvOoy20KJwgiF2meDHp3pGXC5ahcyrLy6zPkDrWnYQVe5yGQIAjit8Njvm8OiYPJPHv4y4ht+g4TUIPxMHkYTBaD8fjP8YQ+HXAogCh6UwAbI5MCGpXASn4DBoeM7mQCec3QIiort3UwRq0htjVMGIP7utkaVX3XrdiEHUtgFQvVRj/JxKbBrYsS/xvkJg07jy7YvzsRf90Y3GnebzCerP2reJyJsBY7mqciwX0FmiyJVoNIK7tv2cMclKM20FbMu3rk6fHcBjSf7YkJ4Rz2EHyHhKjgIRqb4ga1UMsSnXn/wK0wpFFqM0VfR/SVNjWH/xj3g89u8Efkh8nUKeNW3YK+SaUu0CtJJyqmfAFrDxwNYmeRoPIE14hb3qc4szvoo24zlOPOxGxFYx9IwmyArS6PlFMkA2ZARyYTA0pYeV9fXXBMbY52Ja/0hantppm3vhdqx4teSVDJ7PBeZPBWf6EYXkCGLS3yvcyU0I70Cs1r1DYo5MZCyQ2RuYjJezAE3IOxkqJ5yg+sY24Wp1Il1+KAO+d9bilUw2iWopHfaFkR9qDHxrIUFPZVi5WbyYoZyMnmQyDezSyga5E7wNnEqJTY5vLueOCMJJB6htZixkbBUxcNc1RIbhABIXmC5M4x4CLzmOhtOUNVKiZwSQqRvy/ze3LJOqWV3H7Dds+Rn6thRf5XNNSkfbIASoYEdEzHmhI4NXfSGmEOlQfNqCAKvGZlROTW4FcIvGn0EbOuUMlQiBQFa7dCd5zkWxFLvbn2NovXJfKRWXHQPpUWVoS7M+2pCbhcpfXWyqd4KhM6u68VVlhRSO903qLU1lMZzehN5M5dfYjIrzmNScEwprczN3aOmvwTNI+mAcXVHlxsnRYSXtF2SHAQhIL+VBAEu+cEwetWELSEVbKZ6oWwoQf55P9hVTPSwtdtlvHG19FXfvma1JO21A5qSqjEHagPmEsr0a1vCtuGtD9BvYgZfEo9TvzniBd1iEcuNHP49t2/q5vb2fL27ft/lvOb5eJ2jsZQdVec3itriN1zRr9YTFycWNb7yGheohIUn8FONdoUzCl1/Nzde+zuUWjUob+P2rX9+LO71uC5Oz8nEvzvyFaD94XynPc95b2X80c6eafafeQ995NzJ+9NvY5O3qleD52c/6i3OrnFIkd/+/2csT9F845O/WIZO+LTVVT/CP/vJHWzExT2Pe9RHh1V7rLC9cVGyz5Fas5hp2sPXXDU7IIRp0yF5UB8jeQe/uWO2rcc4RbmF2E3umywe9FRt16K3fYlwi/G7njYYHfY0dP7YZeG5R2rf1a5x54svwM=</diagram></mxfile>

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

View File

@ -0,0 +1 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>7Vptb+I4EP41le4+bEUIUPZjeenenrqn3tLT3X6qTGIS7zox5zil7K/fcTLTvHbhFOAkBEKAx87EM88zL7G4cqfRywfN1uEn5XN51e/5L1fu7KrfH/dd+LSCbS4Y9VAQaOHnIqcQLMR3jsIeSlPh86Sy0CgljVhXhZ6KY+6ZioxprTbVZSslq3dds4DuWAgWHpNN6d/CNyGZNSrkv3ERhHRnZ/Q+n1ky71ugVRrj/a767ip75dMRI11oaBIyX21KIncObtVKgWb7K3qZcmldS27Lr7t7Y/Z135rHuLcdF9A+zJZs5z64AodKm1AFKmZyXkgnmX3caujBKDSRhJ8O/ISb6u0/KM8GX+zgepgN/VuLjNW65vFjKOJceidgR/klX7kxW2QDS40CUbGDe6XWeJ+mlWh4olLtoR0wznjDdMBx1U0ushaWLkPPfOAq4rBlWKC5ZEY8V8nAkFPB67rCr/ADXdvuZtzLM5MpKr0TXPp/pkyKleD6Y/wVaDzjkWrAkWxEJFls/V7y9ErFhkCyY9ATgD9nHniEaxA8c20EEPoWJ4x13sQLhfTv2Val1iOJAbbSaBIqLb6DWkb3gGltEA1gfnnFwl6JoGmewJoHAsNemYvuWWIFdo2npGTrRCxfNxwBLCKeKGNUhIvIUkuIqZIKzAAHUPz8BHVrK8fU8waiNIt0x7REw00R4+4NysJKfKOwCwcwA5Y48M5mSL5iqQToISZ8Hnuws1sQ3+qlMJrpbWmiP5IWJ188w8/A/gQFIxZZYONlkn2xiPs1XdUVP1EMBpR0N4gILs5oUpAwMVp94wRVrDKSrkrooYjIKfnKaminZrJmnoiD+2zNbFBIPiMOVrQJheELkNs9baD02AwB+lYySyyh8MGiLEMZZljONkuttRKxybAbTuANaE5tVhqCXVMYA2loDG+7XJupisE+BtfBZRyovOGWzi0spODezUKkHZWRXbQbDLqzDlWUWNcAVop6dsmBpcqX5Zv/jGoEWGTVAmF8zLL3u0x9BWq3CbUV1SGUbMnlg0qEEcrq1/naGrQnQI+Q2oXeuDt4DhLlDKvzsFmdHYTi9OUZN1MJEjCjB6VZltLp06e/Fo9Pk/nTxz9+n08f57OnRep5PElWqZTbX37NU/ezArWX5Lln+HUt4WPs6XZFo4vltwtNMBpLNGmtppcG7ngN3IgenKiDQ1hL8DujFvjfH6CBQ6bVGrisLuWRvzAaQu4S+/vGPsVTl8apFW1a1wVtLN+Xxulg6A3Rg7vQO0DjhKcxjYJuVB6jVKsvEXtkzAnfU0Ssg23cobvl6xuoMqWO2bnuuWMSPHAtYKe2ZGNf/dpIL6WyNfaYXbRDh6OlNhq5f/oumjZT7o9iZUKuL23Siduk4bjaJrmDZhz2e20nXSTsRITmceelU+r2lLQ/A95ulVoBP0jibR5tXnqljvi1NEut+B3ilKntjPDSLf0fUdvSLh0vapvPs5/5v6mAorYHxFnpe9OR1le2ubHlsVa598Eaw9gCe4BiOKgXw2Zotbakh6iEzafIM/XxsObj8Qmd3Hzao1b5TLzr0vEVpYnmoSc58tDOJR3n69xhzbkt6eFozm0+MZ0bc2u516FgPYV3m48h50ZdSqlE3eHRvAvD4l9J2Vzpn1/u/Ac=</diagram></mxfile>

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -0,0 +1 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>7Vhtb+I4EP41SHcftgICtP1YoN1bqXtalZ7u7lPlJiZx1/HkHANlf/3OOGOSEPpyonfaOxUhFD8ejz3zzItDL5rljx+tKLLPkEjdG/aTx1407w2HZ8MIfwnYVsB4fF4BqVVJBQ1qYKG+SQb7jK5UIsuWoAPQThVtMAZjZOxamLAWNm2xJej2roVIw441sIiF7qK/q8RlwaxJjf8iVZqFnQcTtu9exF9TCyvD+/WG0dJ/qulcBF1saJmJBDYNKLpEt1oA1ExP+eNManJtcFu17uqJ2d25rTR8tucX4BQtWAu9YtN7w4nGpdMCH1J6uFJSJzeyhJWN5SfzgP5WYOYyhyCK6nfSbJbbBleWG5VrYXA0zVyuERzg4xKMW7AQjYVWqcHnGM8tLQJraZ1CQi54wkGBaJwpnVyLLazIutKht8NomoFV31CtCHvgtHUcW6PzlsSCViLcR9TKEmW+BJfRygq6FiUBJBOD1qIo1f3uwLmwqTJTcA5yFgqWXimtZ6ABzUAHBP6Da5rcMF1kq+TU8RBz9VFCLp3dokiY5bDhtBpxmm3qGI1GLJI14/OUBQXnRbrTXMcGPnB4HA4VVtEIlQ+U4XIpVtqhzQheIPAg1uJEwYlH9oMBzfRU1YFQOgtfZXCXAR8oy4YHGQoBouWSNBwOj7IQsTLptZeZj2rkhn1B0CZTTi4QpzNtsHwhBqhvqX0iZipJJKqcWnDCiYpxorcAZZz333iKX3TzrH8y7o3RrhmOkbgwxi+JWzcDg/YJXIfLJIbTRlJIHYiEkIcvR0KgngvOS9RHXLKOYX50oEjsEavVfoZXxIbq6XP+b7OaIxe0Q6Dxllief/DqW1RHXaoJ2qdQi3upv0CpqIIhZivZPWr/BfbOxq9j7+x48ninFnloQr/QaFko6xfGkKvQK3eff1vc3l19+nV+N69T+6efq+ReA6p9T+p/KizOX1nPx4wdExennbh4tnL/GG0cL2A/SBvvkHqgsz/Zxk/77T4+CNfBBvGDyaF6wCF1DPHcON6reTNtX6DTJ8uTaRteC15ib8SN9KhbGJ+uwZZM8N2Fh2hoBikYoS9rFD2HLySSNJDfGrSigXb7B+N+8CcNsOLRMLmgVynSWkhzmykqoIhSYvCSB+nclnNTrBxQ1d2d4Bo8wbRPdWY66PMZg3b5ftS6cWL+p/J5IqzU2L3Wbe1Hubn7YnQj/1opLCmv6H++8DzZZSgiyVlUnPbq5msaIacNdb03KEXjvVeKwaQbzIdiOVSso5zcfaXoRvd/2rtR6NTh3te9tQdHvrlzu7f2/5lzJ6fszRC6I1bx9t7FYf2fjJ9r/O8VXX4H</diagram></mxfile>

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>3Vhbb+I6EP41SN0HECGQbh8boNuutkerltXZ84QMcRL3OHFqHAr99R0749y4qCpdqV0eQvx5PJ755mJDxx0nm2+SZPGtCCjvDPrBpuNOOoPB14ELTw1sC2A0uiiASLKggJwKuGfPFME+ojkL6KohqITgimVNcCnSlC5VAyNSiqemWCh4c9eMRHbHCrhfEr6L/ssCFVu3vAq/piyK7c6Oh/4tyPL/SIo8xf06Azc0n2I6IVYXOrqKSSCeapA7BVqlEKBZvyWbMeWaWktbse7qwGxpt6Qp2nZ8ATq0UlvrOg2ACRwKqWIRiZTwaYX6xj2qFfRhFKuEw6sDr7Cn3P5G3Az+04PeyAyDSx0YrTWj6SxmaYFeMTCoWPJAldpiMpBcCYAqC34IkeE+hc3a0INeI7QSuVyiFKakIjKiKDUqGYdEpiKhYDKISMqJYuumdoIpFZVyFa3wgsweCAtGe014jlrv6GPOJOR4m39FN2BdnVaQYs9kYQQ0TZlgqTLWjPzOaAII4SwCOidL8J9KANZUKgbpfIkTCQsCEztOFpT7ZZKOBRcgD/vaNLXsag0Uy7lZbGhJlcN13k0+7TKKivo9DAK2he6wGL6acNT8UzNQqe2CeE2r01IgwnAFEW/HqzTvVSFEw2sR7Aw8riOVNeLnPea6dv0E0kyn+CXM9rMNPA210AE03lU6mfXcsDanQ9/FWOo5DGepE94i/DY7LyxwS6FKgjtapPtN+gBhYiKd0ERYWfCvFC/Xa90NBKTAnSYWg1QfMrDpH3B8yKw3EcJpCFIlI23dXX2Y0JDkXEHDAM1a8oGsSY+JnkHe2QMLaIwkECw/Xaz0l5VZZSTd6yhnKe3GeDpoM52ezpXWVjVn5re/7mdzfzq/+ef7dDybTuZjISWEkEPOl14V+zXtPNGGsy/F5FpAlh/faR+tO8CJ5hwh+6j/BQYlPqk4PavnxlvdbHXmdlM1NVz23iKBfQFSITfnXGhONj8UqcJDzYEOZsZXJGEQXXdyTfmaaq3Nln+wB++ccQd7rWPbM3ZFF4dP1X3G7SNmQ2PWnSN4yoFnDtaP2i0PtI2d9vhhm+En7N+vNflTl5xna8xeRIa7Ned4e2ru4h1K7nyn5Owd+MS7JVzEMXv0ghb3+wMErXXJ0mhmbuxwyXsXdodavsbuBTaZGrm25dW5tdgp3OKPu7+XW8/emW3men+MXBhWP2+Li3j1F4I7fQE=</diagram></mxfile>

View File

@ -0,0 +1,81 @@
<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>dependency-injection</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>@Resource vs @Inject vs @Autowired</name>
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely @Resource, @Inject, and @Autowired</description>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Demo.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>java.net</id>
<url>https://maven.java.net/content/repositories/releases/</url>
</repository>
</repositories>
</project>

View File

@ -0,0 +1,27 @@
package com.baeldung.autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.dependency.ArbitraryDependency;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Autowired-Type.xml"})
public class FieldAutowiredDemo {
@Autowired
private ArbitraryDependency fieldDependency;
@Test
public void fieldDependency_MUST_BE_AUTOWIRED_Correctly() {
assertNotNull(fieldDependency);
assertEquals("Arbitrary Dependency", fieldDependency.toString());
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.dependency.ArbitraryDependency;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Autowired-Name.xml"})
public class FieldAutowiredNameDemo {
@Autowired
private ArbitraryDependency autowiredFieldDependency;
@Test
public void autowiredFieldDependency_MUST_BE_AUTOWIRED_Correctly() {
assertNotNull(autowiredFieldDependency);
assertEquals("Arbitrary Dependency", autowiredFieldDependency.toString());
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.dependency.ArbitraryDependency;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Autowired-Qualifier.xml"})
public class FieldQualifierAutowiredDemo {
@Autowired
@Qualifier("autowiredFieldDependency")
private ArbitraryDependency fieldDependency1;
@Autowired
@Qualifier("anotherAutowiredFieldDependency")
private ArbitraryDependency fieldDependency2;
@Test
public void fieldDependency1_MUST_BE_AUTOWIRED_Correctly() {
assertNotNull(fieldDependency1);
assertEquals("Arbitrary Dependency", fieldDependency1.toString());
}
@Test
public void fieldDependency2_MUST_BE_AUTOWIRED_Correctly() {
assertNotNull(fieldDependency2);
assertEquals("Another Arbitrary Dependency", fieldDependency2.toString());
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.dependency;
public class AnotherArbitraryDependency extends ArbitraryDependency {
private final String label = "Another Arbitrary Dependency";
public String toString() {
return label;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.dependency;
public class ArbitraryDependency {
private final String label = "Arbitrary Dependency";
public String toString() {
return label;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.dependency;
public class YetAnotherArbitraryDependency extends ArbitraryDependency {
private final String label = "Yet Another Arbitrary Dependency";
public String toString() {
return label;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import javax.inject.Named;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.dependency.ArbitraryDependency;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Inject-Name.xml"})
public class FieldByNameInjectDemo {
@Inject
@Named("yetAnotherFieldInjectDependency")
private ArbitraryDependency yetAnotherFieldInjectDependency;
@Test
public void yetAnotherFieldInjectDependency_MUST_BE_INJECTED_Correctly() {
assertNotNull(yetAnotherFieldInjectDependency);
assertEquals("Yet Another Arbitrary Dependency", yetAnotherFieldInjectDependency.toString());
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.dependency.ArbitraryDependency;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Inject-Type.xml"})
public class FieldInjectDemo {
@Inject
private ArbitraryDependency inject1Dependency;
@Test
public void fieldDependency_MUST_BE_INJECTED_Successfully() {
assertNotNull(inject1Dependency);
assertEquals("Arbitrary Dependency", inject1Dependency.toString());
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.dependency.ArbitraryDependency;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Inject-Qualifier.xml"})
public class FieldQualifierInjectDemo {
@Inject
@Qualifier("defaultFile")
private ArbitraryDependency defaultDependency;
@Inject
@Qualifier("namedFile")
private ArbitraryDependency namedDependency;
@Test
public void defaultDependency_MUST_BE_INJECTED_Successfully() {
assertNotNull(defaultDependency);
assertEquals("Arbitrary Dependency", defaultDependency.toString());
}
@Test
public void namedDependency_MUST_BE_INJECTED_Correctly() {
assertNotNull(defaultDependency);
assertEquals("Another Arbitrary Dependency", namedDependency.toString());
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.resource;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Resource-NameType.xml"})
public class FieldResourceInjectionDemo {
@Resource(name="namedFile")
private File defaultFile;
@Test
public void plainResourceAnnotation_MUST_FIND_DefaultFile() {
assertNotNull(defaultFile);
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Resource-Qualifier.xml"})
public class MethodByQualifierResourceDemo {
private File arbDependency;
private File anotherArbDependency;
@Test
public void dependencies_MUST_BE_INJECTED_Correctly() {
assertNotNull(arbDependency);
assertEquals("namedFile.txt", arbDependency.getName());
assertNotNull(anotherArbDependency);
assertEquals("defaultFile.txt", anotherArbDependency.getName());
}
@Resource
@Qualifier("namedFile")
public void setArbDependency(File arbDependency) {
this.arbDependency = arbDependency;
}
@Resource
@Qualifier("defaultFile")
public void setAnotherArbDependency(File anotherArbDependency) {
this.anotherArbDependency = anotherArbDependency;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.resource;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Resource-NameType.xml"})
public class MethodByTypeResourceDemo {
private File defaultFile;
@Resource
protected void setDefaultFile(File defaultFile) {
this.defaultFile = defaultFile;
}
@Test
public void defaultFile_MUST_BE_INJECTED_Correctly() {
assertNotNull(defaultFile);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.resource;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Resource-NameType.xml"})
public class MethodResourceInjectionDemo {
private File defaultFile;
@Resource(name="namedFile")
protected void setDefaultFile(File defaultFile) {
this.defaultFile = defaultFile;
}
@Test
public void defaultFile_MUST_BE_INJECTED_Correctly() {
assertNotNull(defaultFile);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.resource;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Resource-NameType.xml"})
public class NamedResourceTest {
@Resource(name="namedFile")
private File testFile;
@Test
public void namedResource_MUST_FIND_SPECIFIED_File() {
assertNotNull(testFile);
assertTrue(testFile.getName().equals("namedFile.txt"));
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.resource;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Resource-Qualifier.xml"})
public class QualifierResourceInjectionDemo {
@Resource
private File defaultFile;
@Resource
@Qualifier("namedFile")
private File namedFile;
@Test
public void defaultFile_MUST_BE_Valid() {
assertNotNull(defaultFile);
}
@Test
public void namedFile_MUST_BE_Valid() {
assertNotNull(namedFile);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.resource;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"/applicationContextTest-@Resource-NameType.xml"})
public class SetterResourceInjectionDemo {
private File defaultFile;
@Resource
protected void setDefaultFile(File defaultFile) {
this.defaultFile = defaultFile;
}
@Test
public void setter_MUST_INJECT_Resource() {
assertNotNull(defaultFile);
}
}

View File

@ -0,0 +1,12 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="anotherAutowiredFieldDependency" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -0,0 +1,12 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="anotherAutowiredFieldDependency" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -0,0 +1,10 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
</beans>

View File

@ -0,0 +1,11 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="yetAnotherFieldInjectDependency" class="com.baeldung.dependency.YetAnotherArbitraryDependency"/>
</beans>

View File

@ -0,0 +1,12 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="defaultFile" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="namedFile" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -0,0 +1,10 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="injectDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
</beans>

View File

@ -0,0 +1,12 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="namedFile" class="java.io.File">
<constructor-arg value="namedFile.txt"/>
</bean>
</beans>

View File

@ -0,0 +1,16 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="defaultFile" class="java.io.File">
<constructor-arg value="defaultFile.txt"/>
</bean>
<bean id="namedFile" class="java.io.File">
<constructor-arg value="namedFile.txt"/>
</bean>
</beans>

110
gatling/pom.xml Normal file
View File

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>gatling</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<scala.version>2.11.7</scala.version>
<encoding>UTF-8</encoding>
<gatling.version>2.2.0</gatling.version>
<scala-maven-plugin.version>3.2.2</scala-maven-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-app</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-recorder</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-app</artifactId>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-recorder</artifactId>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
</dependency>
</dependencies>
<build>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<args>
<arg>-Ybackend:GenBCode</arg>
<arg>-Ydelambdafy:method</arg>
<arg>-target:jvm-1.8</arg>
<arg>-deprecation</arg>
<arg>-feature</arg>
<arg>-unchecked</arg>
<arg>-language:implicitConversions</arg>
<arg>-language:postfixOps</arg>
</args>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.gatling</groupId>
<artifactId>gatling-maven-plugin</artifactId>
<version>${gatling.version}</version>
<executions>
<execution>
<phase>test</phase>
<goals><goal>execute</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,127 @@
#########################
# Gatling Configuration #
#########################
# This file contains all the settings configurable for Gatling with their default values
gatling {
core {
#outputDirectoryBaseName = "" # The prefix for each simulation result folder (then suffixed by the report generation timestamp)
#runDescription = "" # The description for this simulation run, displayed in each report
#encoding = "utf-8" # Encoding to use throughout Gatling for file and string manipulation
#simulationClass = "" # The FQCN of the simulation to run (when used in conjunction with noReports, the simulation for which assertions will be validated)
#mute = false # When set to true, don't ask for simulation name nor run description (currently only used by Gatling SBT plugin)
#elFileBodiesCacheMaxCapacity = 200 # Cache size for request body EL templates, set to 0 to disable
#rawFileBodiesCacheMaxCapacity = 200 # Cache size for request body Raw templates, set to 0 to disable
#rawFileBodiesInMemoryMaxSize = 1000 # Below this limit, raw file bodies will be cached in memory
extract {
regex {
#cacheMaxCapacity = 200 # Cache size for the compiled regexes, set to 0 to disable caching
}
xpath {
#cacheMaxCapacity = 200 # Cache size for the compiled XPath queries, set to 0 to disable caching
}
jsonPath {
#cacheMaxCapacity = 200 # Cache size for the compiled jsonPath queries, set to 0 to disable caching
#preferJackson = false # When set to true, prefer Jackson over Boon for JSON-related operations
}
css {
#cacheMaxCapacity = 200 # Cache size for the compiled CSS selectors queries, set to 0 to disable caching
}
}
directory {
#data = user-files/data # Folder where user's data (e.g. files used by Feeders) is located
#bodies = user-files/bodies # Folder where bodies are located
#simulations = user-files/simulations # Folder where the bundle's simulations are located
#reportsOnly = "" # If set, name of report folder to look for in order to generate its report
#binaries = "" # If set, name of the folder where compiles classes are located: Defaults to GATLING_HOME/target.
#results = results # Name of the folder where all reports folder are located
}
}
charting {
#noReports = false # When set to true, don't generate HTML reports
#maxPlotPerSeries = 1000 # Number of points per graph in Gatling reports
#useGroupDurationMetric = false # Switch group timings from cumulated response time to group duration.
indicators {
#lowerBound = 800 # Lower bound for the requests' response time to track in the reports and the console summary
#higherBound = 1200 # Higher bound for the requests' response time to track in the reports and the console summary
#percentile1 = 50 # Value for the 1st percentile to track in the reports, the console summary and Graphite
#percentile2 = 75 # Value for the 2nd percentile to track in the reports, the console summary and Graphite
#percentile3 = 95 # Value for the 3rd percentile to track in the reports, the console summary and Graphite
#percentile4 = 99 # Value for the 4th percentile to track in the reports, the console summary and Graphite
}
}
http {
#fetchedCssCacheMaxCapacity = 200 # Cache size for CSS parsed content, set to 0 to disable
#fetchedHtmlCacheMaxCapacity = 200 # Cache size for HTML parsed content, set to 0 to disable
#perUserCacheMaxCapacity = 200 # Per virtual user cache size, set to 0 to disable
#warmUpUrl = "http://gatling.io" # The URL to use to warm-up the HTTP stack (blank means disabled)
#enableGA = true # Very light Google Analytics, please support
ssl {
keyStore {
#type = "" # Type of SSLContext's KeyManagers store
#file = "" # Location of SSLContext's KeyManagers store
#password = "" # Password for SSLContext's KeyManagers store
#algorithm = "" # Algorithm used SSLContext's KeyManagers store
}
trustStore {
#type = "" # Type of SSLContext's TrustManagers store
#file = "" # Location of SSLContext's TrustManagers store
#password = "" # Password for SSLContext's TrustManagers store
#algorithm = "" # Algorithm used by SSLContext's TrustManagers store
}
}
ahc {
#keepAlive = true # Allow pooling HTTP connections (keep-alive header automatically added)
#connectTimeout = 60000 # Timeout when establishing a connection
#pooledConnectionIdleTimeout = 60000 # Timeout when a connection stays unused in the pool
#readTimeout = 60000 # Timeout when a used connection stays idle
#maxRetry = 2 # Number of times that a request should be tried again
#requestTimeout = 60000 # Timeout of the requests
#acceptAnyCertificate = true # When set to true, doesn't validate SSL certificates
#httpClientCodecMaxInitialLineLength = 4096 # Maximum length of the initial line of the response (e.g. "HTTP/1.0 200 OK")
#httpClientCodecMaxHeaderSize = 8192 # Maximum size, in bytes, of each request's headers
#httpClientCodecMaxChunkSize = 8192 # Maximum length of the content or each chunk
#webSocketMaxFrameSize = 10240000 # Maximum frame payload size
#sslEnabledProtocols = [TLSv1.2, TLSv1.1, TLSv1] # Array of enabled protocols for HTTPS, if empty use the JDK defaults
#sslEnabledCipherSuites = [] # Array of enabled cipher suites for HTTPS, if empty use the JDK defaults
#sslSessionCacheSize = 0 # SSLSession cache size, set to 0 to use JDK's default
#sslSessionTimeout = 0 # SSLSession timeout in seconds, set to 0 to use JDK's default (24h)
#useOpenSsl = false # if OpenSSL should be used instead of JSSE (requires tcnative jar)
#useNativeTransport = false # if native transport should be used instead of Java NIO (requires netty-transport-native-epoll, currently Linux only)
#usePooledMemory = true # if Gatling should use pooled memory
#tcpNoDelay = true
#soReuseAddress = false
#soLinger = -1
#soSndBuf = -1
#soRcvBuf = -1
}
dns {
#queryTimeout = 5000 # Timeout of each DNS query in millis
#maxQueriesPerResolve = 3 # Maximum allowed number of DNS queries for a given name resolution
}
}
data {
#writers = [console, file] # The list of DataWriters to which Gatling write simulation data (currently supported : console, file, graphite, jdbc)
console {
#light = false # When set to true, displays a light version without detailed request stats
}
file {
#bufferSize = 8192 # FileDataWriter's internal data buffer size, in bytes
}
leak {
#noActivityTimeout = 30 # Period, in seconds, for which Gatling may have no activity before considering a leak may be happening
}
graphite {
#light = false # only send the all* stats
#host = "localhost" # The host where the Carbon server is located
#port = 2003 # The port to which the Carbon server listens to (2003 is default for plaintext, 2004 is default for pickle)
#protocol = "tcp" # The protocol used to send data to Carbon (currently supported : "tcp", "udp")
#rootPathPrefix = "gatling" # The common prefix of all metrics sent to Graphite
#bufferSize = 8192 # GraphiteDataWriter's internal data buffer size, in bytes
#writeInterval = 1 # GraphiteDataWriter's write interval, in seconds
}
}
}

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern>
<immediateFlush>false</immediateFlush>
</encoder>
</appender>
<!-- Uncomment for logging ALL HTTP request and responses -->
<!-- <logger name="io.gatling.http.ahc" level="TRACE" /> -->
<!-- <logger name="io.gatling.http.response" level="TRACE" /> -->
<!-- Uncomment for logging ONLY FAILED HTTP request and responses -->
<!-- <logger name="io.gatling.http.ahc" level="DEBUG" /> -->
<!-- <logger name="io.gatling.http.response" level="DEBUG" /> -->
<root level="WARN">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

View File

@ -0,0 +1,53 @@
recorder {
core {
#mode = "Proxy"
#encoding = "utf-8" # The encoding used for reading/writing request bodies and the generated simulation
#outputFolder = "" # The folder where generated simulation will we written
#package = "" # The package's name of the generated simulation
#className = "RecordedSimulation" # The name of the generated Simulation class
#thresholdForPauseCreation = 100 # The minimum time, in milliseconds, that must pass between requests to trigger a pause creation
#saveConfig = false # When set to true, the configuration from the Recorder GUI overwrites this configuration
#headless = false # When set to true, run the Recorder in headless mode instead of the GUI
#harFilePath = "" # The path of the HAR file to convert
}
filters {
#filterStrategy = "Disabled" # The selected filter resources filter strategy (currently supported : "Disabled", "BlackList", "WhiteList")
#whitelist = [] # The list of ressources patterns that are part of the Recorder's whitelist
#blacklist = [] # The list of ressources patterns that are part of the Recorder's blacklist
}
http {
#automaticReferer = true # When set to false, write the referer + enable 'disableAutoReferer' in the generated simulation
#followRedirect = true # When set to false, write redirect requests + enable 'disableFollowRedirect' in the generated simulation
#removeCacheHeaders = true # When set to true, removes from the generated requests headers leading to request caching
#inferHtmlResources = true # When set to true, add inferred resources + set 'inferHtmlResources' with the configured blacklist/whitelist in the generated simulation
#checkResponseBodies = false # When set to true, save response bodies as files and add raw checks in the generated simulation
}
proxy {
#port = 8000 # Local port used by Gatling's Proxy for HTTP/HTTPS
https {
#mode = "SelfSignedCertificate" # The selected "HTTPS mode" (currently supported : "SelfSignedCertificate", "ProvidedKeyStore", "GatlingCertificateAuthority", "CustomCertificateAuthority")
keyStore {
#path = "" # The path of the custom key store
#password = "" # The password for this key store
#type = "JKS" # The type of the key store (currently supported: "JKS")
}
certificateAuthority {
#certificatePath = "" # The path of the custom certificate
#privateKeyPath = "" # The certificate's private key path
}
}
outgoing {
#host = "" # The outgoing proxy's hostname
#username = "" # The username to use to connect to the outgoing proxy
#password = "" # The password corresponding to the user to use to connect to the outgoing proxy
#port = 0 # The HTTP port to use to connect to the outgoing proxy
#sslPort = 0 # If set, The HTTPS port to use to connect to the outgoing proxy
}
}
netty {
#maxInitialLineLength = 10000 # Maximum length of the initial line of the response (e.g. "HTTP/1.0 200 OK")
#maxHeaderSize = 20000 # Maximum size, in bytes, of each request's headers
#maxChunkSize = 8192 # Maximum length of the content or each chunk
#maxContentLength = 100000000 # Maximum length of the aggregated content of each response
}
}

View File

@ -0,0 +1,13 @@
import io.gatling.app.Gatling
import io.gatling.core.config.GatlingPropertiesBuilder
object Engine extends App {
val props = new GatlingPropertiesBuilder
props.dataDirectory(IDEPathHelper.dataDirectory.toString)
props.resultsDirectory(IDEPathHelper.resultsDirectory.toString)
props.bodiesDirectory(IDEPathHelper.bodiesDirectory.toString)
props.binariesDirectory(IDEPathHelper.mavenBinariesDirectory.toString)
Gatling.fromMap(props.build)
}

View File

@ -0,0 +1,22 @@
import java.nio.file.Path
import io.gatling.commons.util.PathHelper._
object IDEPathHelper {
val gatlingConfUrl: Path = getClass.getClassLoader.getResource("gatling.conf").toURI
val projectRootDir = gatlingConfUrl.ancestor(3)
val mavenSourcesDirectory = projectRootDir / "src" / "test" / "scala"
val mavenResourcesDirectory = projectRootDir / "src" / "test" / "resources"
val mavenTargetDirectory = projectRootDir / "target"
val mavenBinariesDirectory = mavenTargetDirectory / "test-classes"
val dataDirectory = mavenResourcesDirectory / "data"
val bodiesDirectory = mavenResourcesDirectory / "bodies"
val recorderOutputDirectory = mavenSourcesDirectory
val resultsDirectory = mavenTargetDirectory / "gatling"
val recorderConfigFile = mavenResourcesDirectory / "recorder.conf"
}

View File

@ -0,0 +1,12 @@
import io.gatling.recorder.GatlingRecorder
import io.gatling.recorder.config.RecorderPropertiesBuilder
object Recorder extends App {
val props = new RecorderPropertiesBuilder
props.simulationOutputFolder(IDEPathHelper.recorderOutputDirectory.toString)
props.simulationPackage("org.baeldung")
props.bodiesFolder(IDEPathHelper.bodiesDirectory.toString)
GatlingRecorder.fromMap(props.build, Some(IDEPathHelper.recorderConfigFile))
}

View File

@ -0,0 +1,46 @@
package org.baeldung
import scala.concurrent.duration._
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import io.gatling.jdbc.Predef._
class RecordedSimulation extends Simulation {
val httpProtocol = http
.baseURL("http://computer-database.gatling.io")
.inferHtmlResources(BlackList(""".*\.css""", """.*\.js""", """.*\.ico"""), WhiteList())
.acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.acceptEncodingHeader("gzip, deflate")
.acceptLanguageHeader("it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3")
.userAgentHeader("Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0")
val scn = scenario("RecordedSimulation")
.exec(http("request_0")
.get("/"))
.pause(5)
.exec(http("request_1")
.get("/computers?f=amstrad"))
.pause(4)
.exec(http("request_2")
.get("/computers/412"))
.pause(2)
.exec(http("request_3")
.get("/"))
.pause(2)
.exec(http("request_4")
.get("/computers?p=1"))
.pause(1)
.exec(http("request_5")
.get("/computers?p=2"))
.pause(2)
.exec(http("request_6")
.get("/computers?p=3"))
setUp(scn.inject(atOnceUsers(1))).protocols(httpProtocol)
}

View File

@ -1,55 +0,0 @@
#Sat Jan 21 23:04:06 EET 2012
eclipse.preferences.version=1
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
sp_cleanup.add_default_serial_version_id=true
sp_cleanup.add_generated_serial_version_id=false
sp_cleanup.add_missing_annotations=true
sp_cleanup.add_missing_deprecated_annotations=true
sp_cleanup.add_missing_methods=false
sp_cleanup.add_missing_nls_tags=false
sp_cleanup.add_missing_override_annotations=true
sp_cleanup.add_missing_override_annotations_interface_methods=true
sp_cleanup.add_serial_version_id=false
sp_cleanup.always_use_blocks=true
sp_cleanup.always_use_parentheses_in_expressions=true
sp_cleanup.always_use_this_for_non_static_field_access=false
sp_cleanup.always_use_this_for_non_static_method_access=false
sp_cleanup.convert_to_enhanced_for_loop=true
sp_cleanup.correct_indentation=true
sp_cleanup.format_source_code=true
sp_cleanup.format_source_code_changes_only=true
sp_cleanup.make_local_variable_final=true
sp_cleanup.make_parameters_final=true
sp_cleanup.make_private_fields_final=false
sp_cleanup.make_type_abstract_if_missing_method=false
sp_cleanup.make_variable_declarations_final=true
sp_cleanup.never_use_blocks=false
sp_cleanup.never_use_parentheses_in_expressions=false
sp_cleanup.on_save_use_additional_actions=true
sp_cleanup.organize_imports=true
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
sp_cleanup.remove_private_constructors=true
sp_cleanup.remove_trailing_whitespaces=true
sp_cleanup.remove_trailing_whitespaces_all=true
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
sp_cleanup.remove_unnecessary_casts=true
sp_cleanup.remove_unnecessary_nls_tags=false
sp_cleanup.remove_unused_imports=true
sp_cleanup.remove_unused_local_variables=false
sp_cleanup.remove_unused_private_fields=true
sp_cleanup.remove_unused_private_members=false
sp_cleanup.remove_unused_private_methods=true
sp_cleanup.remove_unused_private_types=true
sp_cleanup.sort_members=false
sp_cleanup.sort_members_all=false
sp_cleanup.use_blocks=false
sp_cleanup.use_blocks_only_for_return_and_throw=false
sp_cleanup.use_parentheses_in_expressions=false
sp_cleanup.use_this_for_non_static_field_access=true
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
sp_cleanup.use_this_for_non_static_method_access=true
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true

View File

@ -0,0 +1,146 @@
package org.baeldung.httpclient;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class SandboxTest {
@Test
public final void whenInterestingDigestAuthScenario_then200OK() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http");
// set up the credentials to run agains the server
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd"));
// This endpoint need fake cookie to work properly
final CookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value");
cookie.setDomain("httpbin.org");
cookie.setPath("/");
cookieStore.addCookie(cookie);
// We need a first run to get a 401 to seed the digest auth
// Make a client using those creds
final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credsProvider).build();
// And make a call to the URL we are after
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
// Create a context to use
final HttpClientContext context = HttpClientContext.create();
// Get a response from the sever (expect a 401!)
final HttpResponse authResponse = client.execute(targetHost, httpget, context);
// Pull out the auth header that came back from the server
final Header challenge = authResponse.getHeaders("WWW-Authenticate")[0];
// Lets use a digest scheme to solve it
final DigestScheme digest = new DigestScheme();
digest.processChallenge(challenge);
// Make a header with the solution based upon user/password and what the digest got out of the initial 401 reponse
final Header solution = digest.authenticate(new UsernamePasswordCredentials("user", "passwd"), httpget, context);
// Need an auth cache to use the new digest we made
final AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, digest);
// Add the authCache and thus solved digest to the context
context.setAuthCache(authCache);
// Pimp up our http get with the solved header made by the digest
httpget.addHeader(solution);
// use it!
System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost);
for (int i = 0; i < 3; i++) {
final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context);
try {
System.out.println("----------------------------------------");
System.out.println(responseGood.getStatusLine());
System.out.println(EntityUtils.toString(responseGood.getEntity()));
} finally {
responseGood.close();
}
}
client.close();
}
// This test needs module spring-security-rest-digest-auth to be running
@Test
public final void whenWeKnowDigestParameters_thenNo401Status() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass"));
final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1");
final HttpClientContext context = HttpClientContext.create();
// == make it preemptive
final AuthCache authCache = new BasicAuthCache();
final DigestScheme digestAuth = new DigestScheme();
digestAuth.overrideParamter("realm", "Custom Realm Name");
digestAuth.overrideParamter("nonce", "nonce value goes here");
authCache.put(targetHost, digestAuth);
context.setAuthCache(authCache);
// == end
System.out.println("Executing The Request knowing the digest parameters ==== ");
final HttpResponse authResponse = client.execute(targetHost, httpget, context);
System.out.println(authResponse.toString());
client.close();
}
// This test needs module spring-security-rest-digest-auth to be running
@Test
public final void whenDoNotKnowParameters_thenOnlyOne401() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
final HttpClientContext context = HttpClientContext.create();
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass"));
final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1");
System.out.println("Executing The Request NOT knowing the digest parameters ==== ");
final HttpResponse tempResponse = client.execute(targetHost, httpget, context);
System.out.println(tempResponse.toString());
for (int i = 0; i < 3; i++) {
System.out.println("No more Challenges or 401");
final CloseableHttpResponse authResponse = client.execute(targetHost, httpget, context);
System.out.println(authResponse.toString());
authResponse.close();
}
client.close();
}
}

311
jee7schedule/pom.xml Normal file
View File

@ -0,0 +1,311 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>jee7schedule</artifactId>
<version>1.0-SNAPSHOT</version>
<description>JavaEE 7 Arquillian Archetype Sample</description>
<packaging>war</packaging>
<properties>
<java.min.version>1.7</java.min.version>
<maven.min.version>3.0.0</maven.min.version>
<version.junit>4.11</version.junit>
<version.javaee_api>7.0</version.javaee_api>
<version.arquillian_core>1.1.4.Final</version.arquillian_core>
<version.wildfly>8.0.0.Final</version.wildfly>
</properties>
<prerequisites>
<maven>${maven.min.version}</maven>
</prerequisites>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>${version.arquillian_core}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${version.javaee_api}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${version.junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>1.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-impl-maven</artifactId>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-impl-maven-archive</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.min.version}</source>
<target>${java.min.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>wildfly-managed-arquillian</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<serverProfile>standalone-full.xml</serverProfile>
<serverRoot>${project.build.directory}/wildfly-${version.wildfly}</serverRoot>
</properties>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-websockets-jsr</artifactId>
<version>1.0.0.Beta25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-json-p-provider</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<version>${version.wildfly}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<configuration>
<skip>${maven.test.skip}</skip>
</configuration>
<executions>
<execution>
<id>unpack</id>
<phase>process-test-classes</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-dist</artifactId>
<version>${version.wildfly}</version>
<type>zip</type>
<overWrite>false</overWrite>
<outputDirectory>${project.build.directory}</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<environmentVariables>
<JBOSS_HOME>${project.build.directory}/wildfly-${version.wildfly}</JBOSS_HOME>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>wildfly-remote-arquillian</id>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-websockets-jsr</artifactId>
<version>1.0.0.Beta25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-json-p-provider</artifactId>
<version>3.0.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-remote</artifactId>
<version>${version.wildfly}</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>glassfish-embedded-arquillian</id>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-client</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>1.0.0.CR4</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>glassfish-remote-arquillian</id>
<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-client</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-remote-3.1</artifactId>
<version>1.0.0.CR4</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,27 @@
package com.baeldung.timer;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import java.util.Date;
@Startup
@Singleton
public class AutomaticTimerBean {
@Inject
Event<TimerEvent> event;
/**
* This method will be called every 10 second and will fire an @TimerEvent
*/
@Schedule(hour = "*", minute = "*", second = "*/10", info = "Every 10 second timer")
public void printDate() {
event.fire(new TimerEvent("TimerEvent sent at :" + new Date()));
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.timer;
import javax.ejb.*;
/**
* Created by ccristianchiovari on 5/2/16.
*/
@Singleton
public class FixedDelayTimerBean {
@EJB
private WorkerBean workerBean;
@Lock(LockType.READ)
@Schedule(second = "*/5", minute = "*", hour = "*", persistent = false)
public void atSchedule() throws InterruptedException {
workerBean.doTimerWork();
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.timer;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.enterprise.event.Event;
import javax.inject.Inject;
/**
* author: Cristian Chiovari
*/
@Startup
@Singleton
public class ProgrammaticAtFixedRateTimerBean {
@Inject
Event<TimerEvent> event;
@Resource
TimerService timerService;
@PostConstruct
public void initialize() {
timerService.createTimer(0,1000, "Every second timer");
}
@Timeout
public void programmaticTimout(Timer timer) {
event.fire(new TimerEvent(timer.getInfo().toString()));
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.timer;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.enterprise.event.Event;
import javax.inject.Inject;
/**
* author: Jacek Jackowiak
*/
@Startup
@Singleton
public class ProgrammaticTimerBean {
@Inject
Event<TimerEvent> event;
@Resource
TimerService timerService;
@PostConstruct
public void initialize() {
ScheduleExpression scheduleExpression = new ScheduleExpression()
.hour("*")
.minute("*")
.second("*/5");
TimerConfig timerConfig = new TimerConfig();
timerConfig.setInfo("Every 5 second timer");
timerService.createCalendarTimer(scheduleExpression, timerConfig);
}
@Timeout
public void programmaticTimout(Timer timer) {
event.fire(new TimerEvent(timer.getInfo().toString()));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.timer;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.enterprise.event.Event;
import javax.inject.Inject;
/**
* author: Cristian Chiovari
*/
@Startup
@Singleton
public class ProgrammaticWithInitialFixedDelayTimerBean {
@Inject
Event<TimerEvent> event;
@Resource
TimerService timerService;
@PostConstruct
public void initialize() {
timerService.createTimer(10000l,5000l, "Delay 10 seconds then every 5 second timer");
}
@Timeout
public void programmaticTimout(Timer timer) {
event.fire(new TimerEvent(timer.getInfo().toString()));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.timer;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timer;
import javax.enterprise.event.Event;
import javax.inject.Inject;
@Startup
@Singleton
public class ScheduleTimerBean {
@Inject
Event<TimerEvent> event;
@Schedule(hour = "*", minute = "*", second = "*/5", info = "Every 5 second timer")
public void automaticallyScheduled(Timer timer) {
fireEvent(timer);
}
private void fireEvent(Timer timer) {
event.fire(new TimerEvent(timer.getInfo().toString()));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.timer;
public class TimerEvent {
private String eventInfo;
private long time = System.currentTimeMillis();
public TimerEvent(String s) {
this.eventInfo = s;
}
public long getTime() {
return time;
}
public String getEventInfo() {
return eventInfo;
}
@Override
public String toString() {
return "TimerEvent {" +
"eventInfo='" + eventInfo + '\'' +
", time=" + time +
'}';
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.timer;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.event.Observes;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* This class will listen to all TimerEvent and will collect them
*/
@Startup
@Singleton
public class TimerEventListener {
final List<TimerEvent> events = new CopyOnWriteArrayList<>();
public void listen(@Observes TimerEvent event) {
System.out.println("event = " + event);
events.add(event);
}
public List<TimerEvent> getEvents() {
return events;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.timer;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by cristianchiovari on 5/2/16.
*/
@Singleton
public class WorkerBean {
private AtomicBoolean busy = new AtomicBoolean(false);
@Lock(LockType.READ)
public void doTimerWork() throws InterruptedException {
System.out.println("Timer method called but not started yet !");
if (!busy.compareAndSet(false, true)) {
return;
}
try {
System.out.println("Timer work started");
Thread.sleep(12000);
System.out.println("Timer work done");
} finally {
busy.set(false);
}
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.timer;
import com.jayway.awaitility.Awaitility;
import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
public class AutomaticTimerBeanTest {
//the @AutomaticTimerBean has a method called every 10 seconds
//testing the difference ==> 100000
final static long TIMEOUT = 10000l;
//the tolerance accepted , so if between two consecutive calls there has to be at least 9 or max 11 seconds.
//because the timer service is not intended for real-time applications so it will not be exactly 10 seconds
final static long TOLERANCE = 1000l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
//only @AutomaticTimerBean is deployed not the other timers
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, AutomaticTimerBean.class);
}
@Test
public void should_receive_two_pings() {
Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
//the test will wait here until two events are triggered
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
long delay = secondEvent.getTime() - firstEvent.getTime();
System.out.println("Actual timeout = " + delay);
//ensure that the delay between the events is more or less 10 seconds (no real time precision)
assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.timer;
import com.jayway.awaitility.Awaitility;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
public class ProgrammaticAtFixedRateTimerBeanTest {
final static long TIMEOUT = 1000;
final static long TOLERANCE = 500l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticAtFixedRateTimerBean.class);
}
@Test
public void should_receive_ten_pings() {
Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(10));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
long delay = secondEvent.getTime() - firstEvent.getTime();
System.out.println("Actual timeout = " + delay);
assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.timer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
public class ProgrammaticTimerBeanTest {
final static long TIMEOUT = 5000l;
final static long TOLERANCE = 1000l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticTimerBean.class);
}
@Test
public void should_receive_two_pings() {
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
long delay = secondEvent.getTime() - firstEvent.getTime();
System.out.println("Actual timeout = " + delay);
assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.timer;
import com.jayway.awaitility.Awaitility;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@RunWith(Arquillian.class)
public class ProgrammaticWithFixedDelayTimerBeanTest {
final static long TIMEOUT = 15000l;
final static long TOLERANCE = 1000l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticWithInitialFixedDelayTimerBean.class);
}
@Test
public void should_receive_two_pings() {
Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
// 10 seconds pause so we get the startTime and it will trigger first event
long startTime = System.currentTimeMillis();
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
long delay = secondEvent.getTime() - startTime;
System.out.println("Actual timeout = " + delay);
//apx 15 seconds = 10 delay + 2 timers (first after a pause of 10 seconds and the next others every 5 seconds)
assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.timer;
import com.jayway.awaitility.Awaitility;
import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
public class ScheduleTimerBeanTest {
final static long TIMEOUT = 5000l;
final static long TOLERANCE = 1000l;
@Inject
TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
return ShrinkWrap.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ScheduleTimerBean.class);
}
@Test
public void should_receive_three_pings() {
Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(3));
TimerEvent firstEvent = timerEventListener.getEvents().get(0);
TimerEvent secondEvent = timerEventListener.getEvents().get(1);
TimerEvent thirdEvent = timerEventListener.getEvents().get(2);
long delay = secondEvent.getTime() - firstEvent.getTime();
assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
delay = thirdEvent.getTime() - secondEvent.getTime();
assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.timer;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
class WithinWindowMatcher extends BaseMatcher<Long> {
private final long timeout;
private final long tolerance;
public WithinWindowMatcher(long timeout, long tolerance) {
this.timeout = timeout;
this.tolerance = tolerance;
}
@Override
public boolean matches(Object item) {
final Long actual = (Long) item;
return Math.abs(actual - timeout) < tolerance;
}
@Override
public void describeTo(Description description) {
//To change body of implemented methods use File | Settings | File Templates.
}
public static Matcher<Long> withinWindow(final long timeout, final long tolerance) {
return new WithinWindowMatcher(timeout, tolerance);
}
}

View File

@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

1
jooq-spring/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/src/main/java/com/baeldung/jooq/introduction/db

View File

@ -14,6 +14,19 @@
<junit.version>4.12</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- jOOQ -->
<dependency>
@ -40,6 +53,11 @@
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jooq</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<!-- Logging -->
<dependency>
@ -67,7 +85,7 @@
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,3 @@
spring.datasource.url=jdbc:h2:~/jooq
spring.datasource.username=sa
spring.datasource.password=

View File

@ -8,12 +8,12 @@ import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
import org.springframework.jdbc.support.SQLExceptionTranslator;
public class ExceptionTranslator extends DefaultExecuteListener {
private static final long serialVersionUID = 649359748808106775L;
@Override
public void exception(ExecuteContext context) {
SQLDialect dialect = context.configuration().dialect();
SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(dialect.name());
context.exception(translator.translate("Access database using jOOQ", context.sql(), context.sqlException()));
}
}

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