Merge pull request #4 from eugenp/master

Pulled from eugenp:master to sync my fork
This commit is contained in:
Dhrubajyoti Bhattacharjee 2017-04-02 16:04:21 +05:30 committed by GitHub
commit ccd76faa60
724 changed files with 29838 additions and 3802 deletions

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
*/bin/*
*.class
# Package Files #

View File

@ -1,6 +1,9 @@
language: java
install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
install: travis_wait 60 mvn -q test
before_script:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc
jdk:
- oraclejdk8
@ -15,9 +18,4 @@ cache:
- .autoconf
- $HOME/.m2
sudo: required
env:
global:
JAVA_OPTS="-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC"
MAVEN_OPTS="-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC"

View File

@ -10,9 +10,15 @@
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -0,0 +1,13 @@
package com.baeldung.algorithms.primechecker;
import java.math.BigInteger;
public class BigIntegerPrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
BigInteger bigInt = BigInteger.valueOf(number);
return bigInt.isProbablePrime(100);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.algorithms.primechecker;
import java.util.stream.IntStream;
public class BruteForcePrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
return IntStream.range(2, number).noneMatch(n -> (number % n == 0));
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.algorithms.primechecker;
import java.util.stream.IntStream;
public class OptimisedPrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
return IntStream.range(2, (int)Math.sqrt(number) + 1)
.noneMatch(n -> (number % n == 0));
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.algorithms.primechecker;
public interface PrimeChecker {
public boolean isPrime( int number );
}

View File

@ -0,0 +1,12 @@
package com.baeldung.algorithms.primechecker;
import org.apache.commons.math3.primes.Primes;
public class PrimesPrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
return Primes.isPrime(number);
}
}

View File

@ -21,12 +21,12 @@ public final class RtState implements State {
}
public State transit(final CharSequence c) {
for(final Transition t : this.transitions) {
if(t.isPossible(c)) {
return t.state();
}
}
throw new IllegalArgumentException("Input not accepted: " + c);
return transitions
.stream()
.filter(t -> t.isPossible(c))
.map(Transition::state)
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Input not accepted: " + c));
}
public boolean isFinal() {

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.BigIntegerPrimeChecker;
import com.baeldung.algorithms.primechecker.PrimeChecker;
public class BigIntegerPrimeCheckerTest {
PrimeChecker primeChecker = new BigIntegerPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.algorithms.primechecker;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.BruteForcePrimeChecker;
import static org.junit.Assert.*;
public class BruteForcePrimeCheckerTest {
BruteForcePrimeChecker primeChecker = new BruteForcePrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.OptimisedPrimeChecker;
import com.baeldung.algorithms.primechecker.PrimeChecker;
public class OptimisedPrimeCheckerTest {
PrimeChecker primeChecker = new OptimisedPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.PrimeChecker;
import com.baeldung.algorithms.primechecker.PrimesPrimeChecker;
public class PrimesPrimeCheckerTest {
PrimeChecker primeChecker = new PrimesPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue() {
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse() {
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -1 +1,3 @@
*.docx
temp.xls
temp.xlsx

Binary file not shown.

0
book Normal file
View File

View File

View File

@ -84,4 +84,5 @@
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)

View File

@ -198,7 +198,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
@ -250,6 +249,7 @@
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>

View File

@ -0,0 +1,61 @@
package com.baeldung.arraycopy.model;
public class Address implements Cloneable {
private String country;
private String state;
private String city;
private String street;
private String zipcode;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
@Override
protected Object clone() throws CloneNotSupportedException {
super.clone();
Address address = new Address();
address.setCity(this.city);
address.setCountry(this.country);
address.setState(this.state);
address.setStreet(this.street);
address.setZipcode(this.zipcode);
return address;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.arraycopy.model;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = -2454619097207585825L;
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.pow;
import java.text.DecimalFormat;
public class PowerExample {
public static void main(String[] args) {
int intResult = (int) Math.pow(2, 3);
System.out.println("Math.pow(2, 3) = " + intResult);
double dblResult = Math.pow(4.2, 3);
System.out.println("Math.pow(4.2, 3) = " + Math.pow(4.2, 3));
DecimalFormat df = new DecimalFormat(".00");
System.out.println("Math.pow(4.2, 3) rounded = " + df.format(dblResult));
}
}

View File

@ -0,0 +1,168 @@
package com.baeldung.arraycopy;
import com.baeldung.arraycopy.model.Address;
import com.baeldung.arraycopy.model.Employee;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
public class ArrayCopyUtilTest {
private static Employee[] employees;
private static final int MAX = 2;
@BeforeClass
public static void setup(){
createEmployeesArray();
}
private static void createEmployeesArray() {
employees = new Employee[MAX];
Employee employee;
for(int i = 0; i < MAX; i++) {
employee = new Employee();
employee.setName("Emp"+i);
employee.setId(i);
employees[i] = employee;
}
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55};
int[] copiedArray = new int[3];
System.arraycopy(array, 0, copiedArray, 0, 3);
Assert.assertArrayEquals(copiedArray, array);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = new int[3];
System.arraycopy(array, 2, copiedArray, 0, 3);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[2]);
Assert.assertTrue(copiedArray[1] == array[3]);
Assert.assertTrue(copiedArray[2] == array[4]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaArraysCopyOfRange_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[1]);
Assert.assertTrue(copiedArray[1] == array[2]);
Assert.assertTrue(copiedArray[2] == array[3]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArraysCopyOf_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int newLength = array.length;
int[] copiedArray = Arrays.copyOf(array, newLength);
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArrayOfNonPrimitiveType_whenCopiedViaArraysCopyOf_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.copyOf(employees, employees.length);
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArrayClone_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int[] copiedArray = array.clone();
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Employee[] copiedArray = employees.clone();
Assert.assertArrayEquals(copiedArray, employees);;
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfCloneableNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Address[] addresses = createAddressArray();
Address[] copiedArray = addresses.clone();
addresses[0].setCity(addresses[0].getCity()+"_Changed");
Assert.assertArrayEquals(copiedArray, addresses);
}
@Test
public void givenArraysOfSerializableNonPrimitiveType_whenCopiedViaSerializationUtils_thenDoDeepCopy(){
Employee[] copiedArray = SerializationUtils.clone(employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertFalse(
copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaStream_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.stream(employees).toArray(Employee[]::new);
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfPrimitiveType_whenCopiedViaStream_thenSuccessful(){
String[] strArray = {"orange", "red", "green'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);
Assert.assertArrayEquals(copiedArray, strArray);
}
private Address[] createAddressArray(){
Address[] addresses = new Address[1];
addresses[0] = createAddress();
return addresses;
}
private Address createAddress() {
Address address = new Address();
address.setCountry("USA");
address.setState("CA");
address.setCity("San Francisco");
address.setStreet("Street 1");
address.setZipcode("59999");
return address;
}
}

View File

@ -12,7 +12,7 @@ import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
public class CountdownLatchExampleTest {
public class CountdownLatchExampleIntegrationTest {
@Test
public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException {
// Given

View File

@ -1,5 +1,6 @@
package com.baeldung.enums;
import com.baeldung.enums.Pizza.PizzaStatusEnum;
import org.junit.Test;
import java.util.ArrayList;
@ -69,11 +70,31 @@ public class PizzaUnitTest {
}
@Test
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
public void whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza();
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
}
@Test
public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
String pizzaEnumValue = "READY";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
}
@Test(expected = IllegalArgumentException.class)
public void whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "rEAdY";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
@Test(expected = IllegalArgumentException.class)
public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "invalid";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
}

View File

@ -60,7 +60,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparing_thenCheckingSort() {
public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
@ -68,7 +68,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparingWithComparator_thenCheckingSort() {
public void whenComparingWithComparator_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
return s2.compareTo(s1);
});
@ -76,9 +76,18 @@ public class Java8ComparatorTest {
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void whenReversed_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
Arrays.sort(employees, employeeNameComparatorReversed);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void givenEmployeeArray_whenUsingComparingInt_thenCheckingSort() {
public void whenComparingInt_thenSortedByAge() {
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
Arrays.sort(employees, employeeAgeComparator);
// System.out.println(Arrays.toString(employees));
@ -86,7 +95,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparingLong_thenCheckingSort() {
public void whenComparingLong_thenSortedByMobile() {
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
Arrays.sort(employees, employeeMobileComparator);
// System.out.println(Arrays.toString(employees));
@ -94,7 +103,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparingDouble_thenCheckingSort() {
public void whenComparingDouble_thenSortedBySalary() {
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
Arrays.sort(employees, employeeSalaryComparator);
// System.out.println(Arrays.toString(employees));
@ -102,7 +111,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingNaturalOrder_thenCheckingSort() {
public void whenNaturalOrder_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
@ -110,7 +119,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingReverseOrder_thenCheckingSort() {
public void whenReverseOrder_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
@ -118,7 +127,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingNullFirst_thenCheckingSort() {
public void whenNullsFirst_thenSortedByNameWithNullsFirst() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
@ -127,7 +136,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingNullLast_thenCheckingSort() {
public void whenNullsLast_thenSortedByNameWithNullsLast() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
@ -136,7 +145,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingThenComparing_thenCheckingSort() {
public void whenThenComparing_thenSortedByAgeName() {
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
@ -145,7 +154,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingThenComparingInt_thenCheckingSort() {
public void whenThenComparing_thenSortedByNameAge() {
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
@ -153,40 +162,6 @@ public class Java8ComparatorTest {
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
}
@Before
public void printData() {
// System.out.println("employees");
// System.out.println(Arrays.toString(employees));
//
// System.out.println("employeesArrayWithNulls");
// System.out.println(Arrays.toString(employeesArrayWithNulls));
//
// System.out.println("sortedEmployeesByName");
// System.out.println(Arrays.toString(sortedEmployeesByName));
//
// System.out.println("sortedEmployeesByNameDesc");
// System.out.println(Arrays.toString(sortedEmployeesByNameDesc));
//
// System.out.println("sortedEmployeesByAge");
// System.out.println(Arrays.toString(sortedEmployeesByAge));
//
// System.out.println("sortedEmployeesByMobile");
// System.out.println(Arrays.toString(sortedEmployeesByMobile));
//
// System.out.println("sortedEmployeesBySalary");
// System.out.println(Arrays.toString(sortedEmployeesBySalary));
//
// System.out.println("sortedEmployeesArray_WithNullsFirst");
// System.out.println(Arrays.toString(sortedEmployeesArray_WithNullsFirst));
//
// System.out.println("sortedEmployeesArray_WithNullsLast");
// System.out.println(Arrays.toString(sortedEmployeesArray_WithNullsLast));
//
// System.out.println("sortedEmployeesByNameAge");
// System.out.println(Arrays.toString(sortedEmployeesByNameAge));
//
// System.out.println("someMoreEmployees");
// System.out.println(Arrays.toString(someMoreEmployees));
//
}
}

View File

@ -1,52 +1,39 @@
package com.baeldung.list.flattennestedlist;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Test;
public class FlattenNestedListTest {
List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
@Test
public void givenListOfListOfString_flattenNestedList1() {
// given
List<String> ls1 = Arrays.asList("one:one", "one:two", "one:three");
List<String> ls2 = Arrays.asList("two:one", "two:two", "two:three");
List<String> ls3 = Arrays.asList("three:one", "three:two", "three:three");
public void givenString_flattenNestedList1() {
List<String> ls = flattenListOfListsImperatively(lol);
List<List<String>> list = Arrays.asList(ls1, ls2, ls3);
// when
List<String> ls = flattenListOfListsImperatively(list);
// then
assertNotNull(ls);
assertTrue(ls.size() == 9);
//TODO content assertion
assertTrue(ls.size() == 8);
// assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
@Test
public void givenListOfListOfString_flattenNestedList2() {
// given
List<String> ls1 = Arrays.asList("one:one", "one:two", "one:three");
List<String> ls2 = Arrays.asList("two:one", "two:two", "two:three");
List<String> ls3 = Arrays.asList("three:one", "three:two", "three:three");
public void givenString_flattenNestedList2() {
List<String> ls = flattenListOfListsStream(lol);
List<List<String>> list = Arrays.asList(ls1, ls2, ls3);
// when
List<String> ls = flattenListOfListsStream(list);
// then
assertNotNull(ls);
assertTrue(ls.size() == 9);
//TODO content assertion
assertTrue(ls.size() == 8);
// assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
public <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
@ -56,9 +43,6 @@ public class FlattenNestedListTest {
}
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
}
}

View File

@ -7,7 +7,7 @@ import java.io.*;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public class JavaProcessUnitTest {
public class JavaProcessUnitIntegrationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
private static class StreamGobbler implements Runnable {

View File

@ -1,38 +1,38 @@
package org.baeldung.java.streams;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStreamTest {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
long firstNum = 1;
long lastNum = 1_000_000;
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}
@Test
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
List<Long> aList = new ArrayList<>();
Stream<Long> parallelStream = aList.parallelStream();
assertTrue(parallelStream.isParallel());
}
}
package org.baeldung.java.streams;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStreamIntegrationTest {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
long firstNum = 1;
long lastNum = 1_000_000;
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}
@Test
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
List<Long> aList = new ArrayList<>();
Stream<Long> parallelStream = aList.parallelStream();
assertTrue(parallelStream.isParallel());
}
}

View File

@ -145,6 +145,7 @@
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>

1
guava21/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

41
guava21/pom.xml Normal file
View File

@ -0,0 +1,41 @@
<?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.guava</groupId>
<artifactId>tutorial</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,27 @@
package com.baeldung.guava.tutorial;
import com.google.common.util.concurrent.AtomicLongMap;
public class AtomicLongMapTutorials {
private AtomicLongMap<String> atomicLongMap;
public AtomicLongMapTutorials() {
atomicLongMap = AtomicLongMap.create();
}
public void addKeys() {
atomicLongMap.addAndGet("apple", 250);
atomicLongMap.addAndGet("bat", 350);
atomicLongMap.addAndGet("cat", 450);
atomicLongMap.addAndGet("dog", 550);
}
public static void main(String[] args) {
AtomicLongMapTutorials atomicLongMapTutorials = new AtomicLongMapTutorials();
atomicLongMapTutorials.addKeys();
System.out.println(atomicLongMapTutorials.atomicLongMap.get("2"));
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Comparators;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ComparatorsExamples {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 4, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(integers, new AscedingOrderComparator());
System.out.println(isInAscendingOrder);
}
private static class AscedingOrderComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Streams;
import java.util.stream.Stream;
public class ConcatStreams {
public static Stream concatStreams(Stream stream1, Stream stream2, Stream stream3) {
return Streams.concat(stream1, stream2, stream3);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
public class InternerBuilderExample {
public static void main(String[] args) {
Interner<Integer> interners = Interners.<Integer> newBuilder()
.concurrencyLevel(2)
.strong().<Integer> build();
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.guava.tutorial;
import com.google.common.util.concurrent.Monitor;
import java.util.ArrayList;
import java.util.List;
public class MonitorExample {
private List<String> students = new ArrayList<String>();
private static final int MAX_SIZE = 100;
private Monitor monitor = new Monitor();
public void addToCourse(String item) throws InterruptedException {
Monitor.Guard studentsBelowCapacity = monitor.newGuard(this::isStudentsCapacityUptoLimit);
monitor.enterWhen(studentsBelowCapacity);
try {
students.add(item);
} finally {
monitor.leave();
}
}
public Boolean isStudentsCapacityUptoLimit() {
return students.size() > MAX_SIZE;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.MoreCollectors;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class MoreCollectorsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.toOptional());
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Streams;
import java.util.*;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class StreamsUtility {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
//Using Collection
Stream<Integer> streamFromCollection = Streams.stream(numbers);
//Using Iterator
Stream<Integer> streamFromIterator = Streams.stream(numbers.iterator());
//Using Iterable
Stream<Integer> streamFromIterable = Streams.stream((Iterable<Integer>) numbers);
//Using Optional
Stream<Integer> streamFromOptional = Streams.stream(Optional.of(1));
//Using OptionalLong to LongStream
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
//Using OptionalInt to IntStream
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
//Using OptionalDouble to DoubleStream
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
Stream<Integer> concatenatedStreams = Streams.concat(streamFromCollection, streamFromIterable, streamFromIterator);
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//This will return 10
Optional<Integer> lastItem = Streams.findLast(integers.stream());
Streams.zip(Stream.of("candy", "chocolate", "bar"), Stream.of("$1", "$2", "$3"), (arg1, arg2) -> arg1 + ":" + arg2);
}
}

View File

@ -0,0 +1,54 @@
import com.google.common.util.concurrent.AtomicLongMap;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AtomicLongMapTests {
private static final String SPRING_COURSE_KEY = "Spring";
private static final String HIBERNATE_COURSE_KEY = "hibernate";
private static final String GUAVA_COURSE_KEY = "Guava";
AtomicLongMap<String> courses = AtomicLongMap.create();
public void setUp() {
courses.put(SPRING_COURSE_KEY, 1056);
courses.put(HIBERNATE_COURSE_KEY, 259);
courses.put(GUAVA_COURSE_KEY, 78);
}
@Test
public void accumulateAndGet_withLongBinaryOperator_thenSuccessful() {
long noOfStudents = 56;
long oldValue = courses.get(SPRING_COURSE_KEY);
long totalNotesRequired = courses.accumulateAndGet("Guava", noOfStudents, (x, y) -> (x * y));
assertEquals(totalNotesRequired, oldValue * noOfStudents);
}
@Test
public void getAndAccumulate_withLongBinaryOperator_thenSuccessful() {
long noOfStudents = 56;
long beforeUpdate = courses.get(SPRING_COURSE_KEY);
long onUpdate = courses.accumulateAndGet("Guava", noOfStudents, (x, y) -> (x * y));
long afterUpdate = courses.get(SPRING_COURSE_KEY);
assertEquals(onUpdate, afterUpdate);
assertEquals(afterUpdate, beforeUpdate * noOfStudents);
}
@Test
public void updateAndGet_withLongUnaryOperator_thenSuccessful() {
long beforeUpdate = courses.get(SPRING_COURSE_KEY);
long onUpdate = courses.updateAndGet("Guava", (x) -> (x / 2));
long afterUpdate = courses.get(SPRING_COURSE_KEY);
assertEquals(onUpdate, afterUpdate);
assertEquals(afterUpdate, beforeUpdate / 2);
}
}

View File

@ -0,0 +1,77 @@
import com.google.common.collect.Comparators;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
public class ComparatorsUnitTests {
@Test
public void isInOrderTest() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 4, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(numbers, new AscendingOrderComparator<Number>());
Assert.assertTrue(isInAscendingOrder);
}
@Test
public void isInStrictOrderTest() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 3, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(numbers, new AscendingOrderComparator<Number>());
Assert.assertFalse(isInAscendingOrder);
}
private class AscendingOrderComparator<I extends Number> implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
@Override
public Comparator<Integer> reversed() {
return null;
}
@Override
public Comparator<Integer> thenComparing(Comparator<? super Integer> other) {
return null;
}
@Override
public <U> Comparator<Integer> thenComparing(Function<? super Integer, ? extends U> keyExtractor, Comparator<? super U> keyComparator) {
return null;
}
@Override
public <U extends Comparable<? super U>> Comparator<Integer> thenComparing(Function<? super Integer, ? extends U> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingInt(ToIntFunction<? super Integer> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingLong(ToLongFunction<? super Integer> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingDouble(ToDoubleFunction<? super Integer> keyExtractor) {
return null;
}
}
}

View File

@ -0,0 +1,158 @@
import com.google.common.collect.Streams;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class GauavaStreamsTests {
List<Integer> numbers;
@Before
public void setUp() {
numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
}
@Test
public void createStreamsWithCollection() {
//Deprecated API to create stream from collection
Stream streamFromCollection = Streams.stream(numbers);
//Assert.assertNotNull(streamFromCollection);
StreamUtility.assertStreamEquals(streamFromCollection, numbers.stream());
}
@Test
public void createStreamsWithIterable() {
Iterable<Integer> numbersIterable = (Iterable<Integer>) numbers;
Stream streamFromIterable = Streams.stream(numbersIterable);
Assert.assertNotNull(streamFromIterable);
StreamUtility.assertStreamEquals(streamFromIterable, numbers.stream());
}
@Test
public void createStreamsWithIterator() {
Iterator<Integer> numbersIterator = numbers.iterator();
Stream streamFromIterator = Streams.stream(numbersIterator);
Assert.assertNotNull(streamFromIterator);
StreamUtility.assertStreamEquals(streamFromIterator, numbers.stream());
}
@Test
public void createStreamsWithOptional() {
Stream streamFromOptional = Streams.stream(Optional.of(1));
Assert.assertNotNull(streamFromOptional);
Assert.assertEquals(streamFromOptional.count(), 1);
}
@Test
public void createStreamsWithOptionalLong() {
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
Assert.assertNotNull(streamFromOptionalLong);
Assert.assertEquals(streamFromOptionalLong.count(), 1);
}
@Test
public void createStreamsWithOptionalInt() {
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
//Assert.assertNotNull(streamFromOptionalInt);
Assert.assertEquals(streamFromOptionalInt.count(), 1);
}
@Test
public void createStreamsWithOptionalDouble() {
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
//Assert.assertNotNull(streamFromOptionalDouble);
Assert.assertEquals(streamFromOptionalDouble.count(), 1);
}
@Test
public void concatStreamsOfSameType() {
Stream oddNumbers = Arrays
.asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
.stream();
Stream evenNumbers = Arrays
.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
.stream();
Stream combinedStreams = Streams.concat(oddNumbers, evenNumbers);
//Assert.assertNotNull(combinedStreams);
StreamUtility.assertStreamEquals(combinedStreams, Stream.concat(oddNumbers, evenNumbers));
}
@Test
public void concatStreamsOfTypeLongStream() {
LongStream firstTwenty = LongStream.range(1, 20);
LongStream nextTwenty = LongStream.range(21, 40);
LongStream combinedStreams = Streams.concat(firstTwenty, nextTwenty);
Assert.assertNotNull(combinedStreams);
StreamUtility.assertStreamEquals(combinedStreams, LongStream.concat(firstTwenty, nextTwenty));
}
@Test
public void concatStreamsOfTypeIntStream() {
IntStream firstTwenty = IntStream.range(1, 20);
IntStream nextTwenty = IntStream.range(21, 40);
IntStream combinedStreams = Streams.concat(firstTwenty, nextTwenty);
Assert.assertNotNull(combinedStreams);
StreamUtility.assertStreamEquals(combinedStreams, IntStream.concat(firstTwenty, nextTwenty));
}
@Test
public void findLastOfStream() {
Optional<Integer> lastElement = Streams.findLast(numbers.stream());
Assert.assertNotNull(lastElement.get());
Assert.assertEquals(lastElement.get(), numbers.get(20));
}
@Test
public void mapWithIndexTest() {
Stream stringSream = Stream.of("a", "b", "c");
Stream<String> mappedStream = Streams.mapWithIndex(stringSream, (str, index) -> str + ":" + index);
//Assert.assertNotNull(mappedStream);
Assert.assertEquals(mappedStream
.findFirst()
.get(), "a:0");
}
@Test
public void streamsZipTest() {
Stream stringSream = Stream.of("a", "b", "c");
Stream intStream = Stream.of(1, 2, 3);
Stream<String> mappedStream = Streams.zip(stringSream, intStream, (str, index) -> str + ":" + index);
//Assert.assertNotNull(mappedStream);
Assert.assertEquals(mappedStream
.findFirst()
.get(), "a:1");
}
}

View File

@ -0,0 +1,18 @@
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import org.junit.Assert;
import org.junit.Test;
public class InternBuilderUnitTests {
@Test
public void interBuilderTest() {
Interner<Integer> interners = Interners.<Integer> newBuilder()
.concurrencyLevel(2)
.strong().<Integer> build();
Assert.assertNotNull(interners);
}
}

View File

@ -0,0 +1,53 @@
import com.google.common.util.concurrent.Monitor;
import org.junit.Assert;
import org.junit.Test;
public class MonitorUnitTests {
@Test
public void whenGaurdConditionIsTrue_IsSuccessful() {
Monitor monitor = new Monitor();
boolean enteredInCriticalSection = false;
Monitor.Guard gaurdCondition = monitor.newGuard(this::returnTrue);
if (monitor.enterIf(gaurdCondition)) {
try {
System.out.println("Entered in critical section");
enteredInCriticalSection = true;
} finally {
monitor.leave();
}
}
Assert.assertTrue(enteredInCriticalSection);
}
@Test
public void whenGaurdConditionIsFalse_IsSuccessful() {
Monitor monitor = new Monitor();
boolean enteredInCriticalSection = false;
Monitor.Guard gaurdCondition = monitor.newGuard(this::returnFalse);
if (monitor.enterIf(gaurdCondition)) {
try {
System.out.println("Entered in critical section");
enteredInCriticalSection = true;
} finally {
monitor.leave();
}
}
Assert.assertFalse(enteredInCriticalSection);
}
private boolean returnTrue() {
return true;
}
private boolean returnFalse() {
return false;
}
}

View File

@ -0,0 +1,36 @@
import com.google.common.collect.MoreCollectors;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class MoreCollectorsUnitTests {
@Test
public void toOptionalTest() {
List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.toOptional());
Assert.assertEquals(number.get(), new Integer(2));
}
@Test
public void onlyElementTest() {
List<Integer> numbers = Arrays.asList(1);
Integer number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.onlyElement());
Assert.assertEquals(number, new Integer(2));
}
}

View File

@ -0,0 +1,66 @@
import org.junit.Assert;
import java.util.Iterator;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class StreamUtility {
public static <T> boolean assertStreamEquals(Stream<T> stream1, Stream<T> stream2) {
Iterator<T> iterator1 = stream1.iterator();
Iterator<T> iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(LongStream stream1, LongStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(DoubleStream stream1, DoubleStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(IntStream stream1, IntStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
}

View File

@ -33,6 +33,7 @@
<groupId>org.apache.hbase</groupId>
<artifactId>hbase</artifactId>
<version>${hbase.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>junit</groupId>

View File

@ -26,3 +26,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance)
- [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat)
- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional)
- [Map Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-map)

View File

@ -195,7 +195,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.8.6</jackson.version>
<jackson.version>2.8.7</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>

View File

@ -0,0 +1,24 @@
package com.baeldung.jackson.entities;
import java.util.Map;
import com.baeldung.jackson.serialization.MyPairDeserializer;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class ClassWithAMap {
@JsonProperty("map")
@JsonDeserialize(keyUsing = MyPairDeserializer.class)
private final Map<MyPair, String> map;
@JsonCreator
public ClassWithAMap(Map<MyPair, String> map) {
this.map = map;
}
public Map<MyPair, String> getMap() {
return map;
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.jackson.entities;
import com.fasterxml.jackson.annotation.JsonValue;
public class MyPair {
private String first;
private String second;
public MyPair(String first, String second) {
this.first = first;
this.second = second;
}
public MyPair(String both) {
String[] pairs = both.split("and");
this.first = pairs[0].trim();
this.second = pairs[1].trim();
}
@Override
@JsonValue
public String toString() {
return first + " and " + second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MyPair)) {
return false;
}
MyPair other = (MyPair) obj;
if (first == null) {
if (other.first != null) {
return false;
}
} else if (!first.equals(other.first)) {
return false;
}
if (second == null) {
if (other.second != null) {
return false;
}
} else if (!second.equals(other.second)) {
return false;
}
return true;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.jackson.serialization;
import java.io.IOException;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
public class MyPairDeserializer extends KeyDeserializer {
@Override
public MyPair deserializeKey(String key, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
return new MyPair(key);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.jackson.serialization;
import java.io.IOException;
import java.io.StringWriter;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
public class MyPairSerializer extends JsonSerializer<MyPair> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void serialize(MyPair value, JsonGenerator gen,
SerializerProvider serializers) throws IOException,
JsonProcessingException {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, value);
gen.writeFieldName(writer.toString());
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.jackson.deserialization;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.jackson.entities.ClassWithAMap;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonMapDeserializeTest {
private Map<MyPair, String> map;
private Map<MyPair, MyPair> cmap;
final ObjectMapper mapper = new ObjectMapper();
@Test
public void whenSimpleMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"key\": \"value\"}";
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
};
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals("value", map.get("key"));
}
@Test
public void whenObjectStringMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
};
map = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
ClassWithAMap classWithMap = mapper.readValue(jsonInput,
ClassWithAMap.class);
Assert.assertEquals("Comedy",
classWithMap.getMap().get(new MyPair("Abbott", "Costello")));
}
@Test
public void whenObjectObjectMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
};
cmap = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals(new MyPair("Comedy", "1940s"),
cmap.get(new MyPair("Abbott", "Costello")));
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.jackson.serialization;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.MapSerializer;
public class JacksonMapSerializeTest {
@JsonSerialize(keyUsing = MyPairSerializer.class)
private Map<MyPair, String> map;
@JsonSerialize(keyUsing = MapSerializer.class)
private Map<MyPair, MyPair> cmap;
@JsonSerialize(keyUsing = MyPairSerializer.class)
private MyPair mapKey;
@JsonSerialize(keyUsing = MyPairSerializer.class)
private MyPair mapValue;
final ObjectMapper mapper = new ObjectMapper();
@Test
public void whenSimpleMapSerialize_thenCorrect()
throws JsonProcessingException {
Map<String, String> map = new HashMap<>();
map.put("key", "value");
final String jsonResult = mapper.writeValueAsString(map);
Assert.assertEquals("{\"key\":\"value\"}", jsonResult);
}
@Test
public void whenCustomObjectStringMapSerialize_thenCorrect()
throws JsonProcessingException {
map = new HashMap<>();
MyPair key = new MyPair("Abbott", "Costello");
map.put(key, "Comedy");
final String jsonResult = mapper.writeValueAsString(map);
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult);
}
@Test
public void whenCustomObjectObjectMapSerialize_thenCorrect()
throws JsonProcessingException {
cmap = new HashMap<>();
mapKey = new MyPair("Abbott", "Costello");
mapValue = new MyPair("Comedy", "1940's");
cmap.put(mapKey, mapValue);
final String jsonResult = mapper.writeValueAsString(cmap);
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}",
jsonResult);
}
}

View File

@ -0,0 +1,119 @@
package com.baeldung.jackson.streaming;
import com.fasterxml.jackson.core.*;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
public class JacksonStreamingAPITest {
@Test
public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException {
//given
ByteArrayOutputStream stream = new ByteArrayOutputStream();
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8);
//when
jGenerator.writeStartObject();
jGenerator.writeStringField("name", "Tom");
jGenerator.writeNumberField("age", 25);
jGenerator.writeFieldName("address");
jGenerator.writeStartArray();
jGenerator.writeString("Poland");
jGenerator.writeString("5th avenue");
jGenerator.writeEndArray();
jGenerator.writeEndObject();
jGenerator.close();
//then
String json = new String(stream.toByteArray(), "UTF-8");
assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}");
}
@Test
public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException {
//given
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createParser(json);
String parsedName = null;
Integer parsedAge = null;
List<String> addresses = new LinkedList<>();
//when
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("name".equals(fieldname)) {
jParser.nextToken();
parsedName = jParser.getText();
}
if ("age".equals(fieldname)) {
jParser.nextToken();
parsedAge = jParser.getIntValue();
}
if ("address".equals(fieldname)) {
jParser.nextToken();
while (jParser.nextToken() != JsonToken.END_ARRAY) {
addresses.add(jParser.getText());
}
}
}
jParser.close();
//then
assertEquals(parsedName, "Tom");
assertEquals(parsedAge, (Integer) 25);
assertEquals(addresses, Arrays.asList("Poland", "5th avenue"));
}
@Test
public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException {
//given
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createParser(json);
String parsedName = null;
Integer parsedAge = null;
List<String> addresses = new LinkedList<>();
//when
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("age".equals(fieldname)) {
jParser.nextToken();
parsedAge = jParser.getIntValue();
return;
}
}
jParser.close();
//then
assertNull(parsedName);
assertEquals(parsedAge, (Integer) 25);
assertTrue(addresses.isEmpty());
}
}

View File

@ -22,19 +22,40 @@
<artifactId>javaslang</artifactId>
<version>2.1.0-alpha</version>
</dependency>
<dependency>
<groupId>io.javaslang</groupId>
<artifactId>javaslang-test</artifactId>
<version>${javaslang.test.version}</version>
</dependency>
</dependencies>
<properties>
<javaslang.test.version>2.0.5</javaslang.test.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,71 @@
package com.baeldung.javaslang;
import javaslang.CheckedFunction1;
import javaslang.collection.Stream;
import javaslang.test.Arbitrary;
import javaslang.test.CheckResult;
import javaslang.test.Property;
import org.junit.Test;
import java.util.function.Predicate;
import static javaslang.API.*;
public class PropertyBasedLongRunningUnitTest {
private static Predicate<Integer> divisibleByTwo = i -> i % 2 == 0;
private static Predicate<Integer> divisibleByFive = i -> i % 5 == 0;
private Stream<String> stringsSupplier() {
return Stream.from(0).map(i -> Match(i).of(
Case($(divisibleByFive.and(divisibleByTwo)), "DividedByTwoAndFiveWithoutRemainder"),
Case($(divisibleByFive), "DividedByFiveWithoutRemainder"),
Case($(divisibleByTwo), "DividedByTwoWithoutRemainder"),
Case($(), "")));
}
@Test
public void givenArbitrarySeq_whenCheckThatEverySecondElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf2 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 2 == 0 && i % 5 != 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.equals("DividedByTwoWithoutRemainder");
//then
CheckResult result = Property
.def("Every second element must equal to DividedByTwoWithoutRemainder")
.forAll(multiplesOf2)
.suchThat(mustEquals)
.check(10_000, 100);
result.assertIsSatisfied();
}
@Test
public void givenArbitrarySeq_whenCheckThatEveryFifthElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf5 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 5 == 0 && i % 2 == 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.endsWith("DividedByTwoAndFiveWithoutRemainder");
//then
Property
.def("Every fifth element must equal to DividedByTwoAndFiveWithoutRemainder")
.forAll(multiplesOf5)
.suchThat(mustEquals)
.check(10_000, 1_000)
.assertIsSatisfied();
}
}

View File

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>jee7schedule</artifactId>
<artifactId>jee7</artifactId>
<version>1.0-SNAPSHOT</version>
<description>JavaEE 7 Arquillian Archetype Sample</description>
<packaging>war</packaging>

View File

@ -0,0 +1,57 @@
<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.javaeeannotations</groupId>
<artifactId>JavaEEAnnotationsSample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>JavaEEAnnotationsSample</name>
<description>JavaEEAnnotationsSample</description>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>SpringFieldConstructorInjection</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>JavaEEAnnotationsSample</finalName>
</build>
</project>

View File

@ -5,9 +5,6 @@ import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.HttpMethodConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
@ -19,20 +16,20 @@ import javax.servlet.http.HttpServletResponse;
urlPatterns = {"/account", "/bankAccount" },
initParams = { @WebInitParam(name = "type", value = "savings") }
)
@ServletSecurity(
/*@ServletSecurity(
value = @HttpConstraint(rolesAllowed = {"admin"}),
httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"admin"})}
)
)*/
public class AccountServlet extends javax.servlet.http.HttpServlet {
String accountType = null;
@Override
public void init(ServletConfig config) throws ServletException {
accountType = config.getInitParameter("type");
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
writer.println("<html>Hello, I am an AccountServlet!</html>");
writer.flush();
@ -49,8 +46,8 @@ public class AccountServlet extends javax.servlet.http.HttpServlet {
PrintWriter writer = response.getWriter();
writer.println("<html> Balance of " + accountType + " account is: " +
accountBalance + "<br> This account bares an interest rate of " + interestRate +
" % </html>");
accountBalance + "<br> This account bares an interest rate of " + interestRate +
" % </html>");
writer.flush();
}

View File

@ -1,17 +1,17 @@
package com.baeldung.javaeeannotations;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class BankAppServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute("ATTR_DEFAULT_LANGUAGE", "english");
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("CONTEXT DESTROYED");
}
}
package com.baeldung.javaeeannotations;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class BankAppServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute("ATTR_DEFAULT_LANGUAGE", "english");
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("CONTEXT DESTROYED");
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.javaeeannotations;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
@WebListener
public class DepositRequestListener implements ServletRequestListener {
public void requestDestroyed(ServletRequestEvent event) {
}
public void requestInitialized(ServletRequestEvent evet) {
HttpServletRequest req = (HttpServletRequest)evet.getServletRequest();
req.setAttribute("interest", new Double(10));
}
}

View File

@ -11,13 +11,13 @@ import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(
/*@WebFilter(
urlPatterns = "/bankAccount/*",
filterName = "LogInFilter",
description = "Filter all account transaction URLs"
)
)*/
public class LogInFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@ -29,8 +29,8 @@ public class LogInFilter implements javax.servlet.Filter {
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}

View File

@ -1,29 +1,29 @@
package com.baeldung.javaeeannotations;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet(urlPatterns = { "/uploadCustDocs" })
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 20,
maxFileSize = 1024 * 1024 * 20,
maxRequestSize = 1024 * 1024 * 25,
location = "D:/custDocs"
)
public class UploadCustomerDocumentsServlet extends HttpServlet {
protected void doPost(
HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
for (Part part : request.getParts()) {
part.write("myFile");
}
}
}
package com.baeldung.javaeeannotations;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet(urlPatterns = { "/uploadCustDocs" })
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 20,
maxFileSize = 1024 * 1024 * 20,
maxRequestSize = 1024 * 1024 * 25,
location = "D:/custDocs"
)
public class UploadCustomerDocumentsServlet extends HttpServlet {
protected void doPost(
HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
for (Part part : request.getParts()) {
part.write("myFile");
}
}
}

View File

@ -1,16 +1,16 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Account</title>
</head>
<body>
<form action="account" method="post">
Width: <input type="text" size="5" name="dep"/>
&nbsp;&nbsp;
<input type="submit" value="Deposit" />
</form>
</body>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Account</title>
</head>
<body>
<form action="bankAccount" method="post">
Amount: <input type="text" size="5" name="dep"/>
&nbsp;&nbsp;
<input type="submit" value="Deposit" />
</form>
</body>
</html>

View File

@ -1,12 +1,12 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
Login Here...
</body>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
Login Here...
</body>
</html>

View File

@ -1,16 +1,16 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="uploadCustDocs" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="uploadCustDocs" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

View File

@ -1,11 +1,11 @@
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>
</web-app>

View File

@ -0,0 +1,32 @@
package com.baeldung.jaxws;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.baeldung.jaxws.exception.EmployeeAlreadyExists;
import com.baeldung.jaxws.exception.EmployeeNotFound;
import com.baeldung.jaxws.model.Employee;
@WebService
public interface EmployeeService {
@WebMethod
Employee getEmployee(int id) throws EmployeeNotFound;
@WebMethod
Employee updateEmployee(int id, String name) throws EmployeeNotFound;
@WebMethod
boolean deleteEmployee(int id) throws EmployeeNotFound;
@WebMethod
Employee addEmployee(int id, String name) throws EmployeeAlreadyExists;
@WebMethod
int countEmployees();
@WebMethod
List<Employee> getAllEmployees();
}

View File

@ -0,0 +1,49 @@
package com.baeldung.jaxws;
import java.util.List;
import javax.inject.Inject;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.baeldung.jaxws.exception.EmployeeAlreadyExists;
import com.baeldung.jaxws.exception.EmployeeNotFound;
import com.baeldung.jaxws.model.Employee;
import com.baeldung.jaxws.repository.EmployeeRepository;
@WebService(serviceName = "EmployeeService", endpointInterface = "com.baeldung.jaxws.EmployeeService")
public class EmployeeServiceImpl implements EmployeeService {
@Inject
private EmployeeRepository employeeRepositoryImpl;
@WebMethod
public Employee getEmployee(int id) throws EmployeeNotFound {
return employeeRepositoryImpl.getEmployee(id);
}
@WebMethod
public Employee updateEmployee(int id, String name) throws EmployeeNotFound {
return employeeRepositoryImpl.updateEmployee(id, name);
}
@WebMethod
public boolean deleteEmployee(int id) throws EmployeeNotFound {
return employeeRepositoryImpl.deleteEmployee(id);
}
@WebMethod
public Employee addEmployee(int id, String name) throws EmployeeAlreadyExists {
return employeeRepositoryImpl.addEmployee(id, name);
}
@WebMethod
public int countEmployees() {
return employeeRepositoryImpl.count();
}
@WebMethod
public List<Employee> getAllEmployees() {
return employeeRepositoryImpl.getAllEmployees();
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.jaxws.config;
import javax.xml.ws.Endpoint;
import com.baeldung.jaxws.EmployeeServiceImpl;
public class EmployeeServicePublisher {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/employeeservice", new EmployeeServiceImpl());
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.jaxws.exception;
import java.io.Serializable;
import javax.xml.ws.WebFault;
@WebFault
public class EmployeeAlreadyExists extends Exception implements Serializable {
private static final long serialVersionUID = 1L;
public EmployeeAlreadyExists() {
super("This employee already exists");
}
public EmployeeAlreadyExists(String str) {
super(str);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.jaxws.exception;
import javax.xml.ws.WebFault;
import java.io.Serializable;
@WebFault
public class EmployeeNotFound extends Exception implements Serializable {
public EmployeeNotFound() {
super("The specified employee does not exist");
}
public EmployeeNotFound(String str) {
super(str);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.jaxws.model;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String firstName;
public Employee() {
}
public Employee(int id, String firstName) {
this.id = id;
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.jaxws.repository;
import java.util.List;
import com.baeldung.jaxws.exception.EmployeeAlreadyExists;
import com.baeldung.jaxws.exception.EmployeeNotFound;
import com.baeldung.jaxws.model.Employee;
public interface EmployeeRepository {
List<Employee> getAllEmployees();
Employee getEmployee(int id) throws EmployeeNotFound;
Employee updateEmployee(int id, String name) throws EmployeeNotFound;
boolean deleteEmployee(int id) throws EmployeeNotFound;
Employee addEmployee(int id, String name) throws EmployeeAlreadyExists;
int count();
}

View File

@ -0,0 +1,68 @@
package com.baeldung.jaxws.repository;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jaxws.exception.EmployeeAlreadyExists;
import com.baeldung.jaxws.exception.EmployeeNotFound;
import com.baeldung.jaxws.model.Employee;
public class EmployeeRepositoryImpl implements EmployeeRepository {
private List<Employee> employeeList;
public EmployeeRepositoryImpl() {
employeeList = new ArrayList<>();
employeeList.add(new Employee(1, "Jane"));
employeeList.add(new Employee(2, "Jack"));
employeeList.add(new Employee(3, "George"));
}
public List<Employee> getAllEmployees() {
return employeeList;
}
public Employee getEmployee(int id) throws EmployeeNotFound {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
return emp;
}
}
throw new EmployeeNotFound();
}
public Employee updateEmployee(int id, String name) throws EmployeeNotFound {
for (Employee employee1 : employeeList) {
if (employee1.getId() == id) {
employee1.setId(id);
employee1.setFirstName(name);
return employee1;
}
}
throw new EmployeeNotFound();
}
public boolean deleteEmployee(int id) throws EmployeeNotFound {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
employeeList.remove(emp);
return true;
}
}
throw new EmployeeNotFound();
}
public Employee addEmployee(int id, String name) throws EmployeeAlreadyExists {
for (Employee emp : employeeList) {
if (emp.getId() == id) {
throw new EmployeeAlreadyExists();
}
}
Employee employee = new Employee(id, name);
employeeList.add(employee);
return employee;
}
public int count() {
return employeeList.size();
}
}

View File

@ -0,0 +1,110 @@
package com.baeldung.jaxws;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.baeldung.jaxws.exception.EmployeeAlreadyExists;
import com.baeldung.jaxws.exception.EmployeeNotFound;
import com.baeldung.jaxws.model.Employee;
import com.baeldung.jaxws.repository.EmployeeRepository;
@RunWith(Arquillian.class)
public class EmployeeServiceLiveTest {
private static final String APP_NAME = "jee7";
private static final String WSDL_PATH = "EmployeeService?wsdl";
private static QName SERVICE_NAME = new QName("http://jaxws.baeldung.com/", "EmployeeService");
private static URL wsdlUrl;
@ArquillianResource
private URL deploymentUrl;
private EmployeeService employeeServiceProxy;
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, APP_NAME + ".war").addPackage(EmployeeService.class.getPackage()).addPackage(Employee.class.getPackage()).addPackage(EmployeeNotFound.class.getPackage()).addPackage(EmployeeRepository.class.getPackage())
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Before
public void setUp() {
try {
wsdlUrl = new URL(deploymentUrl, WSDL_PATH);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Service service = Service.create(wsdlUrl, SERVICE_NAME);
employeeServiceProxy = service.getPort(EmployeeService.class);
}
@Test
public void givenEmployees_whenGetCount_thenCorrectNumberOfEmployeesReturned() {
int employeeCount = employeeServiceProxy.countEmployees();
List<Employee> employeeList = employeeServiceProxy.getAllEmployees();
assertEquals(employeeList.size(), employeeCount);
}
@Test
public void givenEmployees_whenGetAvailableEmployee_thenCorrectEmployeeReturned() throws EmployeeNotFound {
Employee employee = employeeServiceProxy.getEmployee(2);
assertEquals(employee.getFirstName(), "Jack");
}
@Test(expected = EmployeeNotFound.class)
public void givenEmployees_whenGetNonAvailableEmployee_thenEmployeeNotFoundException() throws EmployeeNotFound {
employeeServiceProxy.getEmployee(20);
}
@Test
public void givenEmployees_whenAddNewEmployee_thenEmployeeCountIncreased() throws EmployeeAlreadyExists {
int employeeCount = employeeServiceProxy.countEmployees();
employeeServiceProxy.addEmployee(4, "Anna");
assertEquals(employeeServiceProxy.countEmployees(), employeeCount + 1);
}
@Test(expected = EmployeeAlreadyExists.class)
public void givenEmployees_whenAddAlreadyExistingEmployee_thenEmployeeAlreadyExistsException() throws EmployeeAlreadyExists {
employeeServiceProxy.addEmployee(1, "Anna");
}
@Test
public void givenEmployees_whenUpdateExistingEmployee_thenUpdatedEmployeeReturned() throws EmployeeNotFound {
Employee updated = employeeServiceProxy.updateEmployee(1, "Joan");
assertEquals(updated.getFirstName(), "Joan");
}
@Test(expected = EmployeeNotFound.class)
public void givenEmployees_whenUpdateNonExistingEmployee_thenEmployeeNotFoundException() throws EmployeeNotFound {
employeeServiceProxy.updateEmployee(20, "Joan");
}
@Test
public void givenEmployees_whenDeleteExistingEmployee_thenSuccessReturned() throws EmployeeNotFound {
boolean deleteEmployee = employeeServiceProxy.deleteEmployee(3);
assertEquals(deleteEmployee, true);
}
@Test(expected = EmployeeNotFound.class)
public void givenEmployee_whenDeleteNonExistingEmployee_thenEmployeeNotFoundException() throws EmployeeNotFound {
employeeServiceProxy.deleteEmployee(20);
}
}

View File

@ -19,25 +19,27 @@ import static com.jayway.awaitility.Awaitility.to;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(Arquillian.class)
public class ScheduleTimerBeanIntegrationTest {
final static long TIMEOUT = 5000l;
final static long TOLERANCE = 1000l;
private final static long TIMEOUT = 5000l;
private final static long TOLERANCE = 1000l;
@Inject
TimerEventListener timerEventListener;
@Inject TimerEventListener timerEventListener;
@Deployment
public static WebArchive deploy() {
File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
.resolve("com.jayway.awaitility:awaitility")
.withTransitivity().asFile();
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);
return ShrinkWrap
.create(WebArchive.class)
.addAsLibraries(jars)
.addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ScheduleTimerBean.class);
}
@Test
@ -46,9 +48,15 @@ public class ScheduleTimerBeanIntegrationTest {
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);
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)));

24
jhipster/.editorconfig Normal file
View File

@ -0,0 +1,24 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# Change these settings to your own preference
indent_style = space
indent_size = 4
# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package,bower}.json]
indent_style = space
indent_size = 2

22
jhipster/.gitattributes vendored Normal file
View File

@ -0,0 +1,22 @@
# All text files should have the "lf" (Unix) line endings
* text eol=lf
# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.java text
*.js text
*.css text
*.html text
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
*.jar binary
*.pdf binary
*.eot binary
*.ttf binary
*.gzip binary
*.gz binary
*.ai binary
*.eps binary
*.swf binary

143
jhipster/.gitignore vendored Normal file
View File

@ -0,0 +1,143 @@
######################
# Project Specific
######################
/src/main/webapp/content/css/main.css
/target/www/**
/src/test/javascript/coverage/
/src/test/javascript/PhantomJS*/
######################
# Node
######################
/node/
node_tmp/
node_modules/
npm-debug.log.*
######################
# SASS
######################
.sass-cache/
######################
# Eclipse
######################
*.pydevproject
.project
.metadata
tmp/
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
.factorypath
/src/main/resources/rebel.xml
# External tool builders
.externalToolBuilders/**
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
######################
# Intellij
######################
.idea/
*.iml
*.iws
*.ipr
*.ids
*.orig
######################
# Visual Studio Code
######################
.vscode/
######################
# Maven
######################
/log/
/target/
######################
# Gradle
######################
.gradle/
/build/
######################
# Package Files
######################
*.jar
*.war
*.ear
*.db
######################
# Windows
######################
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
######################
# Mac OSX
######################
.DS_Store
.svn
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
######################
# Directories
######################
/bin/
/deploy/
######################
# Logs
######################
*.log
######################
# Others
######################
*.class
*.*~
*~
.merge_file*
######################
# Gradle Wrapper
######################
!gradle/wrapper/gradle-wrapper.jar
######################
# Maven Wrapper
######################
!.mvn/wrapper/maven-wrapper.jar
######################
# ESLint
######################
.eslintcache
/.apt_generated/

56
jhipster/.gitlab-ci.yml Normal file
View File

@ -0,0 +1,56 @@
cache:
key: "$CI_BUILD_REF_NAME"
paths:
- node_modules
- .maven
stages:
- build
- test
- package
before_script:
- export MAVEN_USER_HOME=`pwd`/.maven
- chmod +x mvnw
- ./mvnw com.github.eirslett:frontend-maven-plugin:install-node-and-npm -DnodeVersion=v6.10.0 -DnpmVersion=4.3.0
- ./mvnw com.github.eirslett:frontend-maven-plugin:npm
maven-build:
stage: build
script: ./mvnw compile -Dmaven.repo.local=$MAVEN_USER_HOME
maven-test:
stage: test
script:
- ./mvnw test -Dmaven.repo.local=$MAVEN_USER_HOME
artifacts:
paths:
- target/surefire-reports/*
maven-front-test:
stage: test
script:
- ./mvnw com.github.eirslett:frontend-maven-plugin:npm -Dfrontend.yarn.arguments=test
artifacts:
paths:
- target/test-results/karma/*
gatling-test:
stage: test
allow_failure: true
script:
- ./mvnw gatling:execute -Dmaven.repo.local=$MAVEN_USER_HOME
before_script:
- export MAVEN_USER_HOME=`pwd`/.maven
- chmod +x mvnw
- ./mvnw com.github.eirslett:frontend-maven-plugin:install-node-and-npm -DnodeVersion=v6.10.0 -DnpmVersion=4.3.0
- ./mvnw com.github.eirslett:frontend-maven-plugin:npm
- ./mvnw &
artifacts:
paths:
- target/gatling/*
maven-package:
stage: package
script:
- ./mvnw package -Pprod -DskipTests -Dmaven.repo.local=$MAVEN_USER_HOME
artifacts:
paths:
- target/*.war

View File

@ -0,0 +1,39 @@
{
"fluentMethods": true,
"relationships": [
{
"relationshipName": "post",
"otherEntityName": "post",
"relationshipType": "many-to-one",
"relationshipValidateRules": [
"required"
],
"otherEntityField": "title"
}
],
"fields": [
{
"fieldName": "text",
"fieldType": "String",
"fieldValidateRules": [
"required",
"minlength",
"maxlength"
],
"fieldValidateRulesMinlength": "10",
"fieldValidateRulesMaxlength": "100"
},
{
"fieldName": "creationDate",
"fieldType": "LocalDate",
"fieldValidateRules": [
"required"
]
}
],
"changelogDate": "20170316224021",
"dto": "no",
"service": "no",
"entityTableName": "comment",
"pagination": "infinite-scroll"
}

View File

@ -0,0 +1,52 @@
{
"fluentMethods": true,
"relationships": [
{
"relationshipName": "creator",
"otherEntityName": "user",
"relationshipType": "many-to-one",
"relationshipValidateRules": [
"required"
],
"otherEntityField": "login",
"ownerSide": true,
"otherEntityRelationshipName": "post"
}
],
"fields": [
{
"fieldName": "title",
"fieldType": "String",
"fieldValidateRules": [
"required",
"minlength",
"maxlength"
],
"fieldValidateRulesMinlength": "10",
"fieldValidateRulesMaxlength": "100"
},
{
"fieldName": "content",
"fieldType": "String",
"fieldValidateRules": [
"required",
"minlength",
"maxlength"
],
"fieldValidateRulesMinlength": "10",
"fieldValidateRulesMaxlength": "1000"
},
{
"fieldName": "creationDate",
"fieldType": "LocalDate",
"fieldValidateRules": [
"required"
]
}
],
"changelogDate": "20170316223211",
"dto": "no",
"service": "no",
"entityTableName": "post",
"pagination": "infinite-scroll"
}

BIN
jhipster/.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

41
jhipster/.travis.yml Normal file
View File

@ -0,0 +1,41 @@
os:
- linux
services:
- docker
language: node_js
node_js:
- "6.10.0"
jdk:
- oraclejdk8
sudo: false
cache:
directories:
- node
- node_modules
- $HOME/.m2
env:
global:
- NODE_VERSION=6.10.0
- SPRING_OUTPUT_ANSI_ENABLED=ALWAYS
- SPRING_JPA_SHOW_SQL=false
before_install:
- jdk_switcher use oraclejdk8
- java -version
- sudo /etc/init.d/mysql stop
- sudo /etc/init.d/postgresql stop
- nvm install $NODE_VERSION
- npm install -g npm
- node -v
- npm -v
install:
- npm install
script:
- chmod +x mvnw
- ./mvnw clean test
- npm test
- ./mvnw package -Pprod -DskipTests
notifications:
webhooks:
on_success: change # options: [always|never|change] default: always
on_failure: always # options: [always|never|change] default: always
on_start: false # default: false

36
jhipster/.yo-rc.json Normal file
View File

@ -0,0 +1,36 @@
{
"generator-jhipster": {
"jhipsterVersion": "4.0.8",
"baseName": "baeldung",
"packageName": "com.baeldung",
"packageFolder": "com/baeldung",
"serverPort": "8080",
"authenticationType": "jwt",
"hibernateCache": "ehcache",
"clusteredHttpSession": false,
"websocket": false,
"databaseType": "sql",
"devDatabaseType": "h2Disk",
"prodDatabaseType": "mysql",
"searchEngine": false,
"messageBroker": false,
"serviceDiscoveryType": false,
"buildTool": "maven",
"enableSocialSignIn": false,
"jwtSecretKey": "e1d4b69d3f953e3fa622121e882e6f459ca20ca4",
"clientFramework": "angular2",
"useSass": true,
"clientPackageManager": "npm",
"applicationType": "monolith",
"testFrameworks": [
"gatling",
"protractor"
],
"jhiPrefix": "jhi",
"enableTranslation": true,
"nativeLanguage": "en",
"languages": [
"en"
]
}
}

50
jhipster/Jenkinsfile vendored Normal file
View File

@ -0,0 +1,50 @@
#!/usr/bin/env groovy
node {
stage('checkout') {
checkout scm
}
stage('check java') {
sh "java -version"
}
stage('clean') {
sh "chmod +x mvnw"
sh "./mvnw clean"
}
stage('install tools') {
sh "./mvnw com.github.eirslett:frontend-maven-plugin:install-node-and-npm -DnodeVersion=v6.10.0 -DnpmVersion=4.3.0"
}
stage('npm install') {
sh "./mvnw com.github.eirslett:frontend-maven-plugin:npm"
}
stage('backend tests') {
try {
sh "./mvnw test"
} catch(err) {
throw err
} finally {
junit '**/target/surefire-reports/TEST-*.xml'
}
}
stage('frontend tests') {
try {
sh "./mvnw com.github.eirslett:frontend-maven-plugin:npm -Dfrontend.yarn.arguments=test"
} catch(err) {
throw err
} finally {
junit '**/target/test-results/karma/TESTS-*.xml'
}
}
stage('packaging') {
sh "./mvnw package -Pprod -DskipTests"
archiveArtifacts artifacts: '**/target/*.war', fingerprint: true
}
}

153
jhipster/README.md Normal file
View File

@ -0,0 +1,153 @@
# baeldung
This application was generated using JHipster 4.0.8, you can find documentation and help at [https://jhipster.github.io/documentation-archive/v4.0.8](https://jhipster.github.io/documentation-archive/v4.0.8).
## Development
Before you can build this project, you must install and configure the following dependencies on your machine:
1. [Node.js][]: We use Node to run a development web server and build the project.
Depending on your system, you can install Node either from source or as a pre-packaged bundle.
After installing Node, you should be able to run the following command to install development tools.
You will only need to run this command when dependencies change in [package.json](package.json).
npm install
We use npm scripts and [Webpack][] as our build system.
Run the following commands in two separate terminals to create a blissful development experience where your browser
auto-refreshes when files change on your hard drive.
./mvnw
npm start
[Npm][] is also used to manage CSS and JavaScript dependencies used in this application. You can upgrade dependencies by
specifying a newer version in [package.json](package.json). You can also run `npm update` and `npm install` to manage dependencies.
Add the `help` flag on any command to see how you can use it. For example, `npm help update`.
The `npm run` command will list all of the scripts available to run for this project.
### Managing dependencies
For example, to add [Leaflet][] library as a runtime dependency of your application, you would run following command:
npm install --save --save-exact leaflet
To benefit from TypeScript type definitions from [DefinitelyTyped][] repository in development, you would run following command:
npm install --save-dev --save-exact @types/leaflet
Then you would import the JS and CSS files specified in library's installation instructions so that [Webpack][] knows about them:
Edit [src/main/webapp/app/vendor.ts](src/main/webapp/app/vendor.ts) file:
~~~
import 'leaflet/dist/leaflet.js';
~~~
Edit [src/main/webapp/content/css/vendor.css](src/main/webapp/content/css/vendor.css) file:
~~~
@import '~leaflet/dist/leaflet.css';
~~~
Note: there are still few other things remaining to do for Leaflet that we won't detail here.
For further instructions on how to develop with JHipster, have a look at [Using JHipster in development][].
### Using angular-cli
You can also use [Angular CLI][] to generate some custom client code.
For example, the following command:
ng generate component my-component
will generate few files:
create src/main/webapp/app/my-component/my-component.component.html
create src/main/webapp/app/my-component/my-component.component.ts
update src/main/webapp/app/app.module.ts
## Building for production
To optimize the baeldung application for production, run:
./mvnw -Pprod clean package
This will concatenate and minify the client CSS and JavaScript files. It will also modify `index.html` so it references these new files.
To ensure everything worked, run:
java -jar target/*.war
Then navigate to [http://localhost:8080](http://localhost:8080) in your browser.
Refer to [Using JHipster in production][] for more details.
## Testing
To launch your application's tests, run:
./mvnw clean test
### Client tests
Unit tests are run by [Karma][] and written with [Jasmine][]. They're located in [src/test/javascript/](src/test/javascript/) and can be run with:
npm test
UI end-to-end tests are powered by [Protractor][], which is built on top of WebDriverJS. They're located in [src/test/javascript/e2e](src/test/javascript/e2e)
and can be run by starting Spring Boot in one terminal (`./mvnw spring-boot:run`) and running the tests (`gulp itest`) in a second one.
### Other tests
Performance tests are run by [Gatling][] and written in Scala. They're located in [src/test/gatling](src/test/gatling) and can be run with:
./mvnw gatling:execute
For more information, refer to the [Running tests page][].
## Using Docker to simplify development (optional)
You can use Docker to improve your JHipster development experience. A number of docker-compose configuration are available in the [src/main/docker](src/main/docker) folder to launch required third party services.
For example, to start a mysql database in a docker container, run:
docker-compose -f src/main/docker/mysql.yml up -d
To stop it and remove the container, run:
docker-compose -f src/main/docker/mysql.yml down
You can also fully dockerize your application and all the services that it depends on.
To achieve this, first build a docker image of your app by running:
./mvnw package -Pprod docker:build
Then run:
docker-compose -f src/main/docker/app.yml up -d
For more information refer to [Using Docker and Docker-Compose][], this page also contains information on the docker-compose sub-generator (`yo jhipster:docker-compose`), which is able to generate docker configurations for one or several JHipster applications.
## Continuous Integration (optional)
To configure CI for your project, run the ci-cd sub-generator (`yo jhipster:ci-cd`), this will let you generate configuration files for a number of Continuous Integration systems. Consult the [Setting up Continuous Integration][] page for more information.
[JHipster Homepage and latest documentation]: https://jhipster.github.io
[JHipster 4.0.8 archive]: https://jhipster.github.io/documentation-archive/v4.0.8
[Using JHipster in development]: https://jhipster.github.io/documentation-archive/v4.0.8/development/
[Using Docker and Docker-Compose]: https://jhipster.github.io/documentation-archive/v4.0.8/docker-compose
[Using JHipster in production]: https://jhipster.github.io/documentation-archive/v4.0.8/production/
[Running tests page]: https://jhipster.github.io/documentation-archive/v4.0.8/running-tests/
[Setting up Continuous Integration]: https://jhipster.github.io/documentation-archive/v4.0.8/setting-up-ci/
[Gatling]: http://gatling.io/
[Node.js]: https://nodejs.org/
[Yarn]: https://yarnpkg.org/
[Webpack]: https://webpack.github.io/
[Angular CLI]: https://cli.angular.io/
[BrowserSync]: http://www.browsersync.io/
[Karma]: http://karma-runner.github.io/
[Jasmine]: http://jasmine.github.io/2.0/introduction.html
[Protractor]: https://angular.github.io/protractor/
[Leaflet]: http://leafletjs.com/
[DefinitelyTyped]: http://definitelytyped.org/

55
jhipster/angular-cli.json Normal file
View File

@ -0,0 +1,55 @@
{
"project": {
"version": "1.0.0-beta.24",
"name": "baeldung"
},
"apps": [
{
"root": "src/main/webapp/",
"outDir": "target/www/app",
"assets": [
"content",
"favicon.ico"
],
"index": "index.html",
"main": "app/app.main.ts",
"test": "",
"tsconfig": "../../../tsconfig.json",
"prefix": "jhi",
"mobile": false,
"styles": [
"content/css/main.css"
],
"scripts": [],
"environments": {}
}
],
"addons": [],
"packages": [],
"e2e": {
"protractor": {
"config": "src/test/javascript/protractor.conf.js"
}
},
"test": {
"karma": {
"config": "src/test/javascript/karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"prefixInterfaces": false,
"inline": {
"style": true,
"template": false
},
"spec": {
"class": false,
"component": false,
"directive": false,
"module": false,
"pipe": false,
"service": false
}
}
}

25
jhipster/circle.yml Normal file
View File

@ -0,0 +1,25 @@
machine:
services:
- docker
java:
version: oraclejdk8
node:
version: 6.10.0
dependencies:
cache_directories:
- node
- node_modules
- ~/.m2
override:
- java -version
- npm install -g npm
- node -v
- npm -v
- java -version
- npm install
test:
override:
- chmod +x mvnw
- ./mvnw clean test
- npm test
- ./mvnw package -Pprod -DskipTests

233
jhipster/mvnw vendored Executable file
View File

@ -0,0 +1,233 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} "$@"

145
jhipster/mvnw.cmd vendored Normal file
View File

@ -0,0 +1,145 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

112
jhipster/package.json Normal file
View File

@ -0,0 +1,112 @@
{
"name": "baeldung",
"version": "0.0.0",
"description": "Description for baeldung",
"private": true,
"cacheDirectories": [
"node_modules"
],
"dependencies": {
"@angular/common": "2.4.7",
"@angular/compiler": "2.4.7",
"@angular/core": "2.4.7",
"@angular/forms": "2.4.7",
"@angular/http": "2.4.7",
"@angular/platform-browser": "2.4.7",
"@angular/platform-browser-dynamic": "2.4.7",
"@angular/router": "3.4.7",
"@ng-bootstrap/ng-bootstrap": "1.0.0-alpha.20",
"angular2-infinite-scroll": "0.3.0",
"bootstrap": "4.0.0-alpha.6",
"font-awesome": "4.7.0",
"angular2-cookie": "1.2.6",
"core-js": "2.4.1",
"jquery": "3.1.1",
"ng-jhipster": "0.1.9",
"ng2-webstorage": "1.5.0",
"reflect-metadata": "0.1.9",
"rxjs": "5.1.0",
"swagger-ui": "2.2.10",
"tether": "1.4.0",
"zone.js": "0.7.6"
},
"devDependencies": {
"@angular/cli": "1.0.0-beta.28.3",
"@types/jasmine": "2.5.42",
"@types/node": "7.0.5",
"@types/selenium-webdriver": "2.53.39",
"add-asset-html-webpack-plugin": "1.0.2",
"angular2-template-loader": "0.6.2",
"awesome-typescript-loader": "3.0.7",
"browser-sync": "2.18.7",
"browser-sync-webpack-plugin": "1.1.4",
"codelyzer": "2.0.0",
"copy-webpack-plugin": "4.0.1",
"css-loader": "0.26.1",
"del": "2.2.2",
"event-stream": "3.3.4",
"exports-loader": "0.6.3",
"extract-text-webpack-plugin": "2.0.0-beta.5",
"file-loader": "0.10.0",
"generator-jhipster": "4.0.8",
"html-webpack-plugin": "2.28.0",
"image-webpack-loader": "3.2.0",
"jasmine-core": "2.5.2",
"jasmine-reporters": "2.2.0",
"karma": "1.4.1",
"karma-chrome-launcher": "2.0.0",
"karma-coverage": "1.1.1",
"karma-intl-shim": "1.0.3",
"karma-jasmine": "1.1.0",
"karma-junit-reporter": "1.2.0",
"karma-phantomjs-launcher": "1.0.2",
"karma-remap-istanbul": "0.6.0",
"karma-sourcemap-loader": "0.3.7",
"karma-webpack": "2.0.2",
"lazypipe": "1.0.1",
"lodash": "4.17.4",
"map-stream": "0.0.6",
"phantomjs-prebuilt": "2.1.14",
"protractor": "5.1.1",
"protractor-jasmine2-screenshot-reporter": "0.3.3",
"ts-node": "2.1.0",
"proxy-middleware": "0.15.0",
"raw-loader": "0.5.1",
"run-sequence": "1.2.2",
"sourcemap-istanbul-instrumenter-loader": "0.2.0",
"string-replace-webpack-plugin": "0.0.5",
"style-loader": "0.13.1",
"to-string-loader": "1.1.5",
"tslint": "4.4.2",
"tslint-loader": "3.4.1",
"typescript": "2.1.6",
"webpack": "2.2.1",
"webpack-dev-server": "2.3.0",
"webpack-merge": "2.6.1",
"webpack-visualizer-plugin": "0.1.10",
"write-file-webpack-plugin": "3.4.2",
"xml2js": "0.4.17",
"sass-loader": "5.0.1",
"node-sass": "4.5.0",
"postcss-loader": "1.3.0",
"yargs": "6.6.0"
},
"engines": {
"node": ">=6.9.0"
},
"scripts": {
"lint": "tslint 'src/main/webapp/app/**/*.ts' --force",
"lint:fix": "tslint 'src/main/webapp/app/**/*.ts' --fix --force",
"tsc": "tsc",
"tsc:w": "tsc -w",
"start": "npm run webpack:dev",
"webpack:build": "webpack --config webpack/webpack.vendor.js && webpack --config webpack/webpack.dev.js",
"webpack:build:dev": "webpack --config webpack/webpack.dev.js",
"webpack:dev": "webpack-dev-server --config webpack/webpack.dev.js --progress --inline --hot --profile --port=9060",
"webpack:prod": "npm test && webpack -p --config webpack/webpack.vendor.js && webpack -p --config webpack/webpack.prod.js",
"test": "npm run lint && karma start src/test/javascript/karma.conf.js",
"test:watch": "karma start --watch",
"e2e": "protractor src/test/javascript/protractor.conf.js",
"postinstall": "webdriver-manager update && npm run webpack:build"
}
}

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