Merge branch 'master' into Mercator

This commit is contained in:
Grigorios Dimopoulos 2018-11-05 11:09:23 +02:00
commit cc54876147
771 changed files with 72437 additions and 737 deletions

View File

@ -1,4 +1,6 @@
## Relevant articles:
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)

View File

@ -1 +0,0 @@
/bin/

View File

@ -1,20 +0,0 @@
package com.java.src;
import java.util.Scanner;
public class RoundUpToHundred {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double input = scanner.nextDouble();
scanner.close();
RoundUpToHundred.round(input);
}
static long round(double input) {
long i = (long) Math.ceil(input);
return ((i + 99) / 100) * 100;
};
}

View File

@ -1,14 +0,0 @@
package com.java.src;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class RoundUpToHundredTest {
@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
}
}

View File

@ -5,7 +5,6 @@ import java.util.Scanner;
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
@ -13,11 +12,8 @@ public class RunAlgorithm {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
System.out.println("4 - Ant Colony");
System.out.println("5 - Dijkstra");
System.out.println("6 - All pairs in an array that add up to a given sum");
System.out.println("2 - Simple Genetic Algorithm");
System.out.println("3 - Ant Colony");
int decision = in.nextInt();
switch (decision) {
case 1:
@ -25,19 +21,13 @@ public class RunAlgorithm {
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break;
case 2:
SlopeOne.slopeOne(3);
break;
case 3:
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
case 4:
case 3:
AntColonyOptimization antColony = new AntColonyOptimization(21);
antColony.startAntOptimization();
break;
case 5:
System.out.println("Please run the DijkstraAlgorithmTest.");
break;
default:
System.out.println("Unknown option");
break;

View File

@ -9,4 +9,5 @@
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)

View File

@ -1 +0,0 @@
/bin/

View File

@ -1,14 +0,0 @@
package com.java.src;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class RoundUpToHundredTest {
@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
}
}

View File

@ -1,12 +0,0 @@
S ########
# #
# ### ## #
# # # #
# # # # #
# ## #####
# # #
# # # # #
##### ####
# # E
# # # #
##########

View File

@ -1,22 +0,0 @@
S ##########################
# # # #
# # #### ############### #
# # # # # #
# # #### # # ###############
# # # # # # #
# # # #### ### ########### #
# # # # # #
# ################## #
######### # # # # #
# # #### # ####### # #
# # ### ### # # # # #
# # ## # ##### # #
##### ####### # # # # #
# # ## ## #### # #
# ##### ####### # #
# # ############
####### ######### # #
# # ######## #
# ####### ###### ## # E
# # # ## #
############################

View File

@ -10,7 +10,6 @@
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)

View File

@ -1 +0,0 @@
/bin/

View File

@ -1,20 +0,0 @@
package com.java.src;
import java.util.Scanner;
public class RoundUpToHundred {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double input = scanner.nextDouble();
scanner.close();
RoundUpToHundred.round(input);
}
static long round(double input) {
long i = (long) Math.ceil(input);
return ((i + 99) / 100) * 100;
};
}

View File

@ -0,0 +1,28 @@
package com.baeldung.algorithms;
import java.util.Scanner;
import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Scanner in = new Scanner(System.in);
System.out.println("1 - Slope One");
System.out.println("2 - Dijkstra");
int decision = in.nextInt();
switch (decision) {
case 1:
SlopeOne.slopeOne(3);
break;
case 2:
System.out.println("Please run the DijkstraAlgorithmLongRunningUnitTest.");
break;
default:
System.out.println("Unknown option");
break;
}
in.close();
}
}

View File

@ -1,10 +1,10 @@
package com.java.src;
package com.baeldung.algorithms.roundedup;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class RoundUpToHundredTest {
public class RoundUpToHundredUnitTest {
@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));

View File

@ -1 +0,0 @@
/bin/

View File

@ -1,20 +0,0 @@
package com.java.src;
import java.util.Scanner;
public class RoundUpToHundred {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double input = scanner.nextDouble();
scanner.close();
RoundUpToHundred.round(input);
}
static long round(double input) {
long i = (long) Math.ceil(input);
return ((i + 99) / 100) * 100;
};
}

View File

@ -1,14 +0,0 @@
package com.java.src;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class RoundUpToHundredTest {
@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
}
}

View File

@ -1,38 +0,0 @@
<?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>
<artifactId>flyway-cdi</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>cdi-portable-extension</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>5.1.4</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>8.5.33</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</project>

View File

@ -1,74 +0,0 @@
package com.baeldung.cdi.extension;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.flywaydb.core.Flyway;
import javax.annotation.sql.DataSourceDefinition;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.literal.InjectLiteral;
import javax.enterprise.inject.spi.*;
import javax.enterprise.util.AnnotationLiteral;
/**
* Flyway is now under CDI container like:
*
* @ApplicationScoped
* @FlywayType public class Flyway{
* @Inject setDataSource(DataSource dataSource){
* //...
* }
* }
*/
public class FlywayExtension implements Extension {
DataSourceDefinition dataSourceDefinition = null;
public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) {
bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName());
}
public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType<?> patEvent) {
AnnotatedType at = patEvent.getAnnotatedType();
dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class);
}
public void processAnnotatedType(@Observes ProcessAnnotatedType<Flyway> patEvent) {
patEvent.configureAnnotatedType()
//Add Scope
.add(ApplicationScoped.Literal.INSTANCE)
//Add Qualifier
.add(new AnnotationLiteral<FlywayType>() {
})
//Decorate setDataSource(DataSource dataSource){} with @Inject
.filterMethods(annotatedMethod -> {
return annotatedMethod.getParameters().size() == 1 &&
annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class);
})
.findFirst().get().add(InjectLiteral.INSTANCE);
}
void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
abdEvent.addBean()
.types(javax.sql.DataSource.class, DataSource.class)
.qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {})
.scope(ApplicationScoped.class)
.name(DataSource.class.getName())
.beanClass(DataSource.class)
.createWith(creationalContext -> {
DataSource instance = new DataSource();
instance.setUrl(dataSourceDefinition.url());
instance.setDriverClassName(dataSourceDefinition.className());
return instance;
});
}
void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get();
flyway.migrate();
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.cdi.extension;
import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD, METHOD, PARAMETER, TYPE})
@Qualifier
public @interface FlywayType {
}

View File

@ -1,6 +0,0 @@
<beans version="2.0" 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/beans_2_0.xsd"
bean-discovery-mode="annotated">
</beans>

View File

@ -1,2 +0,0 @@
com.baeldung.cdi.extension.FlywayExtension

View File

@ -1,52 +0,0 @@
<?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>
<artifactId>main-app</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>cdi-portable-extension</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>3.0.5.Final</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>flyway-cdi</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</project>

View File

@ -1,16 +0,0 @@
package com.baeldung.cdi.extension;
import javax.annotation.sql.DataSourceDefinition;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;
@ApplicationScoped
@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb")
public class MainApp {
public static void main(String[] args) {
SeContainerInitializer initializer = SeContainerInitializer.newInstance();
try (SeContainer container = initializer.initialize()) {
}
}
}

View File

@ -1,6 +0,0 @@
<beans version="2.0" 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/beans_2_0.xsd"
bean-discovery-mode="annotated">
</beans>

View File

@ -1,4 +0,0 @@
create table PERSON (
ID int not null,
NAME varchar(100) not null
);

View File

@ -1,3 +0,0 @@
insert into PERSON (ID, NAME) values (1, 'Axel');
insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
insert into PERSON (ID, NAME) values (3, 'Ms. Bar');

View File

@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>cdi-portable-extension</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<modules>
<module>main-app</module>
<module>flyway-cdi</module>
</modules>
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
</dependency>
</dependencies>
</project>

View File

@ -61,11 +61,11 @@
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.6.1</assertj.version>
<assertj.version>3.11.1</assertj.version>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
</properties>
</project>

View File

@ -0,0 +1,197 @@
package com.baeldung.array.operations;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayOperations {
// Get the first and last item of an array
public static <T> T getFirstObject(T[] array) {
return array[0];
}
public static int getFirstInt(int[] array) {
return array[0];
}
public static <T> T getLastObject(T[] array) {
return array[array.length - 1];
}
public static int getLastInt(int[] array) {
return array[array.length - 1];
}
// Append a new item to an array
public static <T> T[] appendObject(T[] array, T newItem) {
return ArrayUtils.add(array, newItem);
}
public static int[] appendInt(int[] array, int newItem) {
int[] newArray = Arrays.copyOf(array, array.length + 1);
newArray[newArray.length - 1] = newItem;
return newArray;
}
public static int[] appendIntWithUtils(int[] array, int newItem) {
return ArrayUtils.add(array, newItem);
}
// Compare two arrays to check if they have the same elements
public static <T> boolean compareObjectArrays(T[] array1, T[] array2) {
return Arrays.equals(array1, array2);
}
public static boolean compareIntArrays(int[] array1, int[] array2) {
return Arrays.equals(array1, array2);
}
// Deep Compare (for nested arrays)
public static <T> boolean deepCompareObjectArrayUsingArrays(T[][] array1, T[][] array2) {
// We can use Objects.deepEquals for a broader approach
return Arrays.deepEquals(array1, array2);
}
public static boolean deepCompareIntArrayUsingArrays(int[][] array1, int[][] array2) {
return Arrays.deepEquals(array1, array2);
}
// Check if array is empty
public static <T> boolean isEmptyObjectArrayUsingUtils(T[] array1) {
return ArrayUtils.isEmpty(array1);
}
public static boolean isEmptyIntArrayUsingUtils(int[] array1) {
return ArrayUtils.isEmpty(array1);
}
// Remove duplicates
public static Integer[] removeDuplicateObjects(Integer[] array) {
// We can use other ways of converting the array to a set too
Set<Integer> set = new HashSet<>(Arrays.asList(array));
return set.toArray(new Integer[set.size()]);
}
public static int[] removeDuplicateInts(int[] array) {
// Box
Integer[] list = ArrayUtils.toObject(array);
// Remove duplicates
Set<Integer> set = new HashSet<Integer>(Arrays.asList(list));
// Create array and unbox
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
// Remove duplicates preserving the order
public static Integer[] removeDuplicateWithOrderObjectArray(Integer[] array) {
// We can use other ways of converting the array to a set too
Set<Integer> set = new LinkedHashSet<>(Arrays.asList(array));
return set.toArray(new Integer[set.size()]);
}
public static int[] removeDuplicateWithOrderIntArray(int[] array) {
// Box
Integer[] list = ArrayUtils.toObject(array);
// Remove duplicates
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(list));
// Create array and unbox
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
// Print an array
public static String printObjectArray(Integer[] array) {
return ArrayUtils.toString(array);
}
public static String printObjectArray(Integer[][] array) {
return ArrayUtils.toString(array);
}
public static String printIntArray(int[] array) {
return ArrayUtils.toString(array);
}
public static String printIntArray(int[][] array) {
return ArrayUtils.toString(array);
}
// Box or Unbox values
public static int[] unboxIntegerArray(Integer[] array) {
return ArrayUtils.toPrimitive(array);
}
public static Integer[] boxIntArray(int[] array) {
return ArrayUtils.toObject(array);
}
// Map array values
@SuppressWarnings("unchecked")
public static <T, U> U[] mapObjectArray(T[] array, Function<T, U> function, Class<U> targetClazz) {
U[] newArray = (U[]) Array.newInstance(targetClazz, array.length);
for (int i = 0; i < array.length; i++) {
newArray[i] = function.apply(array[i]);
}
return newArray;
}
public static String[] mapIntArrayToString(int[] array) {
return Arrays.stream(array)
.mapToObj(value -> String.format("Value: %s", value))
.toArray(String[]::new);
}
// Filter array values
public static Integer[] filterObjectArray(Integer[] array, Predicate<Integer> predicate) {
return Arrays.stream(array)
.filter(predicate)
.toArray(Integer[]::new);
}
public static int[] filterIntArray(int[] array, IntPredicate predicate) {
return Arrays.stream(array)
.filter(predicate)
.toArray();
}
// Insert item between others
public static int[] insertBetweenIntArray(int[] array, int... values) {
return ArrayUtils.insert(2, array, values);
}
@SuppressWarnings("unchecked")
public static <T> T[] insertBetweenObjectArray(T[] array, T... values) {
return ArrayUtils.insert(2, array, values);
}
// Shuffling arrays
public static int[] shuffleIntArray(int[] array) {
// we create a different array instance for testing purposes
int[] shuffled = Arrays.copyOf(array, array.length);
ArrayUtils.shuffle(shuffled);
return shuffled;
}
public static <T> T[] shuffleObjectArray(T[] array) {
// we create a different array instance for testing purposes
T[] shuffled = Arrays.copyOf(array, array.length);
ArrayUtils.shuffle(shuffled);
return shuffled;
}
// Get random number
public static int getRandomFromIntArray(int[] array) {
return array[new Random().nextInt(array.length)];
}
public static <T> T getRandomFromObjectArray(T[] array) {
return array[new Random().nextInt(array.length)];
}
}

View File

@ -0,0 +1,365 @@
package com.baeldung.array.operations;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ArrayOperationsUnitTest {
private Integer[] defaultObjectArray;
private int[] defaultIntArray;
private Integer[][] defaultJaggedObjectArray;
private int[][] defaultJaggedIntArray;
@BeforeEach
public void setupDefaults() {
defaultObjectArray = new Integer[] { 3, 5, 2, 5, 14, 4 };
defaultIntArray = new int[] { 3, 5, 2, 5, 14, 4 };
defaultJaggedObjectArray = new Integer[][] { { 1, 3 }, { 5 }, {} };
defaultJaggedIntArray = new int[][] { { 1, 3 }, { 5 }, {} };
}
// Get the first and last item of an array
@Test
public void whenGetFirstObjectCalled_thenReturnFirstItemOfArray() {
Integer output = ArrayOperations.getFirstObject(defaultObjectArray);
assertThat(output).isEqualTo(3);
}
@Test
public void whenGetFirstIntCalled_thenReturnFirstItemOfArray() {
int output = ArrayOperations.getFirstInt(defaultIntArray);
assertThat(output).isEqualTo(3);
}
@Test
public void whenGetLastObjectCalled_thenReturnLastItemOfArray() {
Integer output = ArrayOperations.getLastObject(defaultObjectArray);
assertThat(output).isEqualTo(4);
}
@Test
public void whenGetLastIntCalled_thenReturnLastItemOfArray() {
int output = ArrayOperations.getLastInt(defaultIntArray);
assertThat(output).isEqualTo(4);
}
// Append a new item to an array
@Test
public void whenAppendObject_thenReturnArrayWithExtraItem() {
Integer[] output = ArrayOperations.appendObject(defaultObjectArray, 7);
assertThat(output).endsWith(4, 7)
.hasSize(7);
}
@Test
public void whenAppendInt_thenReturnArrayWithExtraItem() {
int[] output = ArrayOperations.appendInt(defaultIntArray, 7);
int[] outputUsingUtils = ArrayOperations.appendIntWithUtils(defaultIntArray, 7);
assertThat(output).endsWith(4, 7)
.hasSize(7);
assertThat(outputUsingUtils).endsWith(4, 7)
.hasSize(7);
}
// Compare two arrays to check if they have the same elements
@Test
public void whenCompareObjectArrays_thenReturnBoolean() {
Integer[] array2 = { 8, 7, 6 };
Integer[] sameArray = { 3, 5, 2, 5, 14, 4 };
boolean output = ArrayOperations.compareObjectArrays(defaultObjectArray, array2);
boolean output2 = ArrayOperations.compareObjectArrays(defaultObjectArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
@Test
public void whenCompareIntArrays_thenReturnBoolean() {
int[] array2 = { 8, 7, 6 };
int[] sameArray = { 3, 5, 2, 5, 14, 4 };
boolean output = ArrayOperations.compareIntArrays(defaultIntArray, array2);
boolean output2 = ArrayOperations.compareIntArrays(defaultIntArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Deep compare
@Test
public void whenDeepCompareObjectArrays_thenReturnBoolean() {
Integer[][] sameArray = { { 1, 3 }, { 5 }, {} };
Integer[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
boolean output = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, array2);
boolean output2 = ArrayOperations.deepCompareObjectArrayUsingArrays(defaultJaggedObjectArray, sameArray);
// Because arrays are Objects, we could wrongly use the non-deep approach
boolean outputUsingNonDeep = ArrayOperations.compareObjectArrays(defaultJaggedObjectArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
// This is not what we would expect!
assertThat(outputUsingNonDeep).isFalse();
}
@Test
public void whenDeepCompareIntArrays_thenReturnBoolean() {
int[][] sameArray = { { 1, 3 }, { 5 }, {} };
int[][] array2 = { { 1, 3 }, { 5 }, { 3 } };
boolean output = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, array2);
boolean output2 = ArrayOperations.deepCompareIntArrayUsingArrays(defaultJaggedIntArray, sameArray);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Empty Check
@Test
public void whenIsEmptyObjectArray_thenReturnBoolean() {
Integer[] array2 = {};
Integer[] array3 = null;
Integer[] array4 = { null, null, null };
Integer[] array5 = { null };
Integer[][] array6 = { {}, {}, {} };
boolean output = ArrayOperations.isEmptyObjectArrayUsingUtils(defaultObjectArray);
boolean output2 = ArrayOperations.isEmptyObjectArrayUsingUtils(array2);
boolean output3 = ArrayOperations.isEmptyObjectArrayUsingUtils(array3);
boolean output4 = ArrayOperations.isEmptyObjectArrayUsingUtils(array4);
boolean output5 = ArrayOperations.isEmptyObjectArrayUsingUtils(array5);
boolean output6 = ArrayOperations.isEmptyObjectArrayUsingUtils(array6);
assertThat(output).isFalse();
assertThat(output2).isTrue();
assertThat(output3).isTrue();
// Mind these edge cases!
assertThat(output4).isFalse();
assertThat(output5).isFalse();
assertThat(output6).isFalse();
}
@Test
public void whenIsEmptyIntArray_thenReturnBoolean() {
int[] array2 = {};
boolean output = ArrayOperations.isEmptyIntArrayUsingUtils(defaultIntArray);
boolean output2 = ArrayOperations.isEmptyIntArrayUsingUtils(array2);
assertThat(output).isFalse();
assertThat(output2).isTrue();
}
// Remove Duplicates
@Test
public void whenRemoveDuplicateObjectArray_thenReturnArrayWithNoDuplicates() {
Integer[] output = ArrayOperations.removeDuplicateObjects(defaultObjectArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.doesNotHaveDuplicates();
}
@Test
public void whenRemoveDuplicateIntArray_thenReturnArrayWithNoDuplicates() {
int[] output = ArrayOperations.removeDuplicateInts(defaultIntArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.doesNotHaveDuplicates();
}
// Remove Duplicates Preserving order
@Test
public void whenRemoveDuplicatePreservingOrderObjectArray_thenReturnArrayWithNoDuplicates() {
Integer[] array2 = { 3, 5, 2, 14, 4 };
Integer[] output = ArrayOperations.removeDuplicateWithOrderObjectArray(defaultObjectArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.containsExactly(array2);
}
@Test
public void whenRemoveDuplicatePreservingOrderIntArray_thenReturnArrayWithNoDuplicates() {
int[] array2 = { 3, 5, 2, 14, 4 };
int[] output = ArrayOperations.removeDuplicateWithOrderIntArray(defaultIntArray);
assertThat(output).containsOnlyOnce(5)
.hasSize(5)
.containsExactly(array2);
}
// Print
@Test
public void whenPrintObjectArray_thenReturnString() {
String output = ArrayOperations.printObjectArray(defaultObjectArray);
String jaggedOutput = ArrayOperations.printObjectArray(defaultJaggedObjectArray);
// Comparing to Arrays output:
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
// We should use Arrays.deepToString for jagged arrays
String differentFormatJaggedArraysOutput = Arrays.deepToString(defaultJaggedObjectArray);
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
assertThat(differentFormatJaggedArraysOutput).contains("[[1, 3], [5], []]");
}
@Test
public void whenPrintIntArray_thenReturnString() {
String output = ArrayOperations.printIntArray(defaultIntArray);
String jaggedOutput = ArrayOperations.printIntArray(defaultJaggedIntArray);
// Comparing to Arrays output:
String wrongArraysOutput = Arrays.toString(defaultJaggedObjectArray);
String differentFormatArraysOutput = Arrays.toString(defaultObjectArray);
assertThat(output).isEqualTo("{3,5,2,5,14,4}");
assertThat(jaggedOutput).isEqualTo("{{1,3},{5},{}}");
assertThat(differentFormatArraysOutput).isEqualTo("[3, 5, 2, 5, 14, 4]");
assertThat(wrongArraysOutput).contains("[[Ljava.lang.Integer;@");
}
// Box and unbox
@Test
public void whenUnboxObjectArray_thenReturnPrimitiveArray() {
int[] output = ArrayOperations.unboxIntegerArray(defaultObjectArray);
assertThat(output).containsExactly(defaultIntArray);
}
@Test
public void henBoxPrimitiveArray_thenReturnObjectArray() {
Integer[] output = ArrayOperations.boxIntArray(defaultIntArray);
assertThat(output).containsExactly(defaultObjectArray);
}
// Map values
@Test
public void whenMapMultiplyingObjectArray_thenReturnMultipliedArray() {
Integer[] multipliedExpectedArray = new Integer[] { 6, 10, 4, 10, 28, 8 };
Integer[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value * 2, Integer.class);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenMapDividingObjectArray_thenReturnDividedArray() {
Double[] multipliedExpectedArray = new Double[] { 1.5, 2.5, 1.0, 2.5, 7.0, 2.0 };
Double[] output = ArrayOperations.mapObjectArray(defaultObjectArray, value -> value / 2.0, Double.class);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenMapIntArrayToString_thenReturnArray() {
String[] expectedArray = new String[] { "Value: 3", "Value: 5", "Value: 2", "Value: 5", "Value: 14",
"Value: 4" };
String[] output = ArrayOperations.mapIntArrayToString(defaultIntArray);
assertThat(output).containsExactly(expectedArray);
}
// Filter values
@Test
public void whenFilterObjectArray_thenReturnFilteredArray() {
Integer[] multipliedExpectedArray = new Integer[] { 2, 14, 4 };
Integer[] output = ArrayOperations.filterObjectArray(defaultObjectArray, value -> value % 2 == 0);
assertThat(output).containsExactly(multipliedExpectedArray);
}
@Test
public void whenFilterIntArray_thenReturnFilteredArray() {
int[] expectedArray = new int[] { 2, 14, 4 };
int[] output = ArrayOperations.filterIntArray(defaultIntArray, value -> (int) value % 2 == 0);
assertThat(output).containsExactly(expectedArray);
}
// Insert between
@Test
public void whenInsertBetweenIntArrayToString_thenReturnNewArray() {
int[] expectedArray = { 3, 5, 77, 88, 2, 5, 14, 4 };
int[] output = ArrayOperations.insertBetweenIntArray(defaultIntArray, 77, 88);
assertThat(output).containsExactly(expectedArray);
}
@Test
public void whenInsertBetweenObjectArrayToString_thenReturnNewArray() {
Integer[] expectedArray = { 3, 5, 77, 99, 2, 5, 14, 4 };
Integer[] output = ArrayOperations.insertBetweenObjectArray(defaultObjectArray, 77, 99);
assertThat(output).containsExactly(expectedArray);
}
// Shuffle between
@Test
public void whenShufflingIntArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
int[] output = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output2 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output3 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output4 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output5 = ArrayOperations.shuffleIntArray(defaultIntArray);
int[] output6 = ArrayOperations.shuffleIntArray(defaultIntArray);
Condition<int[]> atLeastOneArraysIsNotEqual = new Condition<int[]>(
"at least one output should be different (order-wise)") {
@Override
public boolean matches(int[] value) {
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3)
|| !Arrays.equals(value, output4) || !Arrays.equals(value, output5)
|| !Arrays.equals(value, output6);
}
};
assertThat(defaultIntArray).has(atLeastOneArraysIsNotEqual);
}
@Test
public void whenShufflingObjectArraySeveralTimes_thenAtLeastOneWithDifferentOrder() {
Integer[] output = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output2 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output3 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output4 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output5 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Integer[] output6 = ArrayOperations.shuffleObjectArray(defaultObjectArray);
Condition<Integer[]> atLeastOneArraysIsNotEqual = new Condition<Integer[]>(
"at least one output should be different (order-wise)") {
@Override
public boolean matches(Integer[] value) {
return !Arrays.equals(value, output) || !Arrays.equals(value, output2) || !Arrays.equals(value, output3)
|| !Arrays.equals(value, output4) || !Arrays.equals(value, output5)
|| !Arrays.equals(value, output6);
}
};
assertThat(defaultObjectArray).has(atLeastOneArraysIsNotEqual);
}
// Get random item
@Test
public void whenGetRandomFromIntArrayToString_thenReturnItemContainedInArray() {
int output = ArrayOperations.getRandomFromIntArray(defaultIntArray);
assertThat(defaultIntArray).contains(output);
}
@Test
public void whenGetRandomFromObjectArrayToString_thenReturnItemContainedInArray() {
Integer output = ArrayOperations.getRandomFromObjectArray(defaultObjectArray);
assertThat(defaultObjectArray).contains(output);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.enummap;
/**
* This enum is used for benchmarking, therefore has many values.
*/
public enum DummyEnum {
CCC_000,
CCC_001,CCC_002,CCC_003,CCC_004,CCC_005,CCC_006,CCC_007,CCC_008,CCC_009,CCC_010,
CCC_011,CCC_012,CCC_013,CCC_014,CCC_015,CCC_016,CCC_017,CCC_018,CCC_019,CCC_020,
CCC_021,CCC_022,CCC_023,CCC_024,CCC_025,CCC_026,CCC_027,CCC_028,CCC_029,CCC_030,
CCC_031,CCC_032,CCC_033,CCC_034,CCC_035,CCC_036,CCC_037,CCC_038,CCC_039,CCC_040,
CCC_041,CCC_042,CCC_043,CCC_044,CCC_045,CCC_046,CCC_047,CCC_048,CCC_049,
}

View File

@ -0,0 +1,119 @@
package com.baeldung.enummap;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.*;
import java.util.concurrent.TimeUnit;
@BenchmarkMode({ Mode.AverageTime })
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
public class EnumMapBenchmarkLiveTest {
@State(Scope.Thread)
public static class BenchmarkState {
EnumMap<DummyEnum, String> enumMap = new EnumMap<>(DummyEnum.class);
HashMap<DummyEnum, String> hashMap = new HashMap<>();
TreeMap<DummyEnum, String> treeMap = new TreeMap<>();
int len = DummyEnum.values().length;
Random random = new Random();
int randomIndex;
@Setup(Level.Trial)
public void setUp() {
DummyEnum[] values = DummyEnum.values();
for (int i = 0; i < len; i++) {
enumMap.put(values[i], values[i].toString());
hashMap.put(values[i], values[i].toString());
treeMap.put(values[i], values[i].toString());
}
}
@Setup(Level.Invocation)
public void additionalSetup() {
randomIndex = random.nextInt(len);
}
}
@Benchmark
public int benchmark01_EnumMapPut(BenchmarkState s) {
s.enumMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark01_HashMapPut(BenchmarkState s) {
s.hashMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark01_TreeMapPut(BenchmarkState s) {
s.treeMap.put(DummyEnum.values()[s.randomIndex], DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark02_EnumMapGet(BenchmarkState s) {
s.enumMap.get(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark02_HashMapGet(BenchmarkState s) {
s.hashMap.get(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark02_TreeMapGet(BenchmarkState s) {
s.treeMap.get(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark03_EnumMapContainsKey(BenchmarkState s) {
s.enumMap.containsKey(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark03_HashMapContainsKey(BenchmarkState s) {
s.hashMap.containsKey(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark03_TreeMapContainsKey(BenchmarkState s) {
s.treeMap.containsKey(DummyEnum.values()[s.randomIndex]);
return ++s.randomIndex;
}
@Benchmark
public int benchmark04_EnumMapContainsValue(BenchmarkState s) {
s.enumMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark04_HashMapContainsValue(BenchmarkState s) {
s.hashMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
@Benchmark
public int benchmark04_TreeMapContainsValue(BenchmarkState s) {
s.treeMap.containsValue(DummyEnum.values()[s.randomIndex].toString());
return ++s.randomIndex;
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(EnumMapBenchmarkLiveTest.class.getSimpleName()).threads(1).forks(0).shouldFailOnError(true).shouldDoGC(false).jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -0,0 +1,144 @@
package com.baeldung.enummap;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static java.util.AbstractMap.SimpleEntry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
public class EnumMapUnitTest {
public enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
@Test
public void whenContructedWithEnumType_ThenOnlyAcceptThatAsKey() {
Map dayMap = new EnumMap<>(DayOfWeek.class);
assertThatCode(
() -> dayMap.put(TimeUnit.NANOSECONDS, "NANOSECONDS"))
.isInstanceOf(ClassCastException.class);
}
@Test
public void whenConstructedWithEnumMap_ThenSameKeyTypeAndInitialMappings() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");
EnumMap<DayOfWeek, String> activityMapCopy = new EnumMap<>(activityMap);
assertThat(activityMapCopy.size()).isEqualTo(2);
assertThat(activityMapCopy.get(DayOfWeek.MONDAY))
.isEqualTo("Soccer");
assertThat(activityMapCopy.get(DayOfWeek.TUESDAY))
.isEqualTo("Basketball");
}
@Test
public void givenEmptyMap_whenConstructedWithMap_ThenException() {
HashMap ordinaryMap = new HashMap();
assertThatCode(() -> new EnumMap(ordinaryMap))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Specified map is empty");
}
@Test
public void givenMapWithEntries_whenConstructedWithMap_ThenSucceed() {
HashMap<DayOfWeek, String> ordinaryMap = new HashMap<>();
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");
ordinaryMap.put(DayOfWeek.TUESDAY, "Basketball");
EnumMap<DayOfWeek, String> enumMap = new EnumMap<>(ordinaryMap);
assertThat(enumMap.size()).isEqualTo(2);
assertThat(enumMap.get(DayOfWeek.MONDAY)).isEqualTo("Soccer");
assertThat(enumMap.get(DayOfWeek.TUESDAY)).isEqualTo("Basketball");
}
@Test
public void givenMapWithMultiTypeEntries_whenConstructedWithMap_ThenException() {
HashMap<Enum, String> ordinaryMap = new HashMap<>();
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");
ordinaryMap.put(TimeUnit.MILLISECONDS, "Other enum type");
assertThatCode(() -> new EnumMap(ordinaryMap))
.isInstanceOf(ClassCastException.class);
}
@Test
public void whenPut_thenGet() {
Map<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
activityMap.put(DayOfWeek.THURSDAY, null);
assertThat(activityMap.get(DayOfWeek.WEDNESDAY)).isEqualTo("Hiking");
assertThat(activityMap.get(DayOfWeek.THURSDAY)).isNull();
}
@Test
public void givenMapping_whenContains_thenTrue() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isFalse();
assertThat(activityMap.containsValue("Hiking")).isFalse();
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isTrue();
assertThat(activityMap.containsValue("Hiking")).isTrue();
assertThat(activityMap.containsKey(DayOfWeek.SATURDAY)).isFalse();
assertThat(activityMap.containsValue(null)).isFalse();
activityMap.put(DayOfWeek.SATURDAY, null);
assertThat(activityMap.containsKey(DayOfWeek.SATURDAY)).isTrue();
assertThat(activityMap.containsValue(null)).isTrue();
}
@Test
public void whenRemove_thenRemoved() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
assertThat(activityMap.remove(DayOfWeek.MONDAY)).isEqualTo("Soccer");
assertThat(activityMap.containsKey(DayOfWeek.MONDAY)).isFalse();
activityMap.put(DayOfWeek.MONDAY, "Soccer");
assertThat(activityMap.remove(DayOfWeek.MONDAY, "Hiking")).isEqualTo(false);
assertThat(activityMap.remove(DayOfWeek.MONDAY, "Soccer")).isEqualTo(true);
}
@Test
public void whenSubView_thenSubViewOrdered() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
activityMap.put(DayOfWeek.THURSDAY, "Karate");
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
activityMap.put(DayOfWeek.MONDAY, "Soccer");
Collection<String> values = activityMap.values();
assertThat(values).containsExactly("Soccer", "Hiking", "Karate");
Set<DayOfWeek> keys = activityMap.keySet();
assertThat(keys)
.containsExactly(DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY,DayOfWeek.THURSDAY);
assertThat(activityMap.entrySet())
.containsExactly(
new SimpleEntry(DayOfWeek.MONDAY, "Soccer"),
new SimpleEntry(DayOfWeek.WEDNESDAY, "Hiking"),
new SimpleEntry(DayOfWeek.THURSDAY, "Karate"));
}
@Test
public void givenSubView_whenChange_thenReflected() {
EnumMap<DayOfWeek, String> activityMap = new EnumMap(DayOfWeek.class);
activityMap.put(DayOfWeek.THURSDAY, "Karate");
activityMap.put(DayOfWeek.WEDNESDAY, "Hiking");
activityMap.put(DayOfWeek.MONDAY, "Soccer");
Collection<String> values = activityMap.values();
assertThat(values).containsExactly("Soccer", "Hiking", "Karate");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");
assertThat(values)
.containsExactly("Soccer", "Basketball", "Hiking", "Karate");
values.remove("Hiking");
assertThat(activityMap.containsKey(DayOfWeek.WEDNESDAY)).isFalse();
assertThat(activityMap.size()).isEqualTo(3);
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.concurrent.evenandodd;
public class PrintEvenOdd {
public static void main(String... args) {
Printer print = new Printer();
Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));
t1.setName("Odd");
Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
t2.setName("Even");
t1.start();
t2.start();
}
}
class TaskEvenOdd implements Runnable {
private int max;
private Printer print;
private boolean isEvenNumber;
TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
this.print = print;
this.max = max;
this.isEvenNumber = isEvenNumber;
}
@Override
public void run() {
int number = isEvenNumber == true ? 2 : 1;
while (number <= max) {
if (isEvenNumber) {
print.printEven(number);
} else {
print.printOdd(number);
}
number += 2;
}
}
}
class Printer {
boolean isOdd = false;
synchronized void printEven(int number) {
while (isOdd == false) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread()
.getName() + ":" + number);
isOdd = false;
notify();
}
synchronized void printOdd(int number) {
while (isOdd == true) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread()
.getName() + ":" + number);
isOdd = true;
notify();
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.concurrent.evenandodd;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
public static void main(String[] args) {
SharedPrinter sp = new SharedPrinter();
Thread odd = new Thread(new Odd(sp, 10));
odd.setName("Odd");
Thread even = new Thread(new Even(sp, 10));
even.setName("Even");
odd.start();
even.start();
}
}
class SharedPrinter {
Semaphore semEven = new Semaphore(0);
Semaphore semOdd = new Semaphore(1);
public void printEvenNum(int num) {
try {
semEven.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()
.getName() + ":"+num);
semOdd.release();
}
public void printOddNum(int num) {
try {
semOdd.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread()
.getName() + ":"+ num);
semEven.release();
}
}
class Even implements Runnable {
SharedPrinter sp;
int max;
Even(SharedPrinter sp, int max) {
this.sp = sp;
this.max = max;
}
@Override
public void run() {
for (int i = 2; i <= max; i = i + 2) {
sp.printEvenNum(i);
}
}
}
class Odd implements Runnable {
SharedPrinter sp;
int max;
Odd(SharedPrinter sp, int max) {
this.sp = sp;
this.max = max;
}
@Override
public void run() {
for (int i = 1; i <= max; i = i + 2) {
sp.printOddNum(i);
}
}
}

View File

@ -17,12 +17,9 @@
- [Sorting in Java](http://www.baeldung.com/java-sorting)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [Grep in Java](http://www.baeldung.com/grep-in-java)
- [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
- [Slope One Algorithm: Collaborative Filtering Recommendation Systems](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
- [The Basics of Java Generics](http://www.baeldung.com/java-generics)
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
@ -159,3 +156,4 @@
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)

View File

@ -0,0 +1,30 @@
package com.baeldung.abstractclasses.application;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
import com.baeldung.abstractclasses.filereaders.StandardFileReader;
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
import java.io.IOException;
public class Application {
public static void main(String[] args) throws IOException {
Application application = new Application();
String filePath = application.getFilePathFromResourcesFolder("files/test.txt");
BaseFileReader lowercaseFileReader = new LowercaseFileReader(filePath);
lowercaseFileReader.readFile().forEach(line -> System.out.println(line));
BaseFileReader upperCaseFileReader = new UppercaseFileReader(filePath);
upperCaseFileReader.readFile().forEach(line -> System.out.println(line));
BaseFileReader standardFileReader = new StandardFileReader(filePath);
standardFileReader.readFile().forEach(line -> System.out.println(line));
}
private String getFilePathFromResourcesFolder(String fileName) {
return getClass().getClassLoader().getResource(fileName).getPath().substring(1);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.abstractclasses.filereaders;
import java.io.IOException;
import java.util.List;
public abstract class BaseFileReader {
protected String filePath;
protected BaseFileReader(String filePath) {
this.filePath = filePath;
}
public String getFilePath() {
return filePath;
}
public abstract List<String> readFile() throws IOException;
}

View File

@ -0,0 +1,21 @@
package com.baeldung.abstractclasses.filereaders;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class LowercaseFileReader extends BaseFileReader {
public LowercaseFileReader(String filePath) {
super(filePath);
}
@Override
public List<String> readFile() throws IOException {
return Files.lines(Paths.get(filePath))
.map(String::toLowerCase)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.abstractclasses.filereaders;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class StandardFileReader extends BaseFileReader {
public StandardFileReader(String filePath) {
super(filePath);
}
@Override
public List<String> readFile() throws IOException {
return Files.lines(Paths.get(filePath)).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.abstractclasses.filereaders;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class UppercaseFileReader extends BaseFileReader {
public UppercaseFileReader(String filePath) {
super(filePath);
}
@Override
public List<String> readFile() throws IOException {
return Files.lines(Paths.get(filePath))
.map(String::toUpperCase)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,10 @@
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10

View File

@ -0,0 +1,18 @@
package com.baeldung.abstractclasses;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class LowercaseFileReaderUnitTest {
@Test
public void givenLowercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
String filePath = getClass().getClassLoader().getResource("files/test.txt").getPath().substring(1);
BaseFileReader lowercaseFileReader = new LowercaseFileReader(filePath);
assertThat(lowercaseFileReader.readFile()).isInstanceOf(List.class);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.abstractclasses;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.StandardFileReader;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class StandardFileReaderUnitTest {
@Test
public void givenStandardFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
String filePath = getClass().getClassLoader().getResource("files/test.txt").getPath().substring(1);
BaseFileReader standardFileReader = new StandardFileReader(filePath);
assertThat(standardFileReader.readFile()).isInstanceOf(List.class);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.abstractclasses;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class UppercaseFileReaderUnitTest {
@Test
public void givenUppercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
String filePath = getClass().getClassLoader().getResource("files/test.txt").getPath().substring(1);
BaseFileReader uppercaseFileReader = new UppercaseFileReader(filePath);
assertThat(uppercaseFileReader.readFile()).isInstanceOf(List.class);
}
}

View File

@ -34,3 +34,4 @@
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)

View File

@ -11,11 +11,14 @@ public class WordIndexer {
String lowerCaseTextString = textString.toLowerCase();
String lowerCaseWord = word.toLowerCase();
while(index != -1){
index = lowerCaseTextString.indexOf(lowerCaseWord, index + 1);
if (index != -1) {
indexes.add(index);
while(index != -1) {
index = lowerCaseTextString.indexOf(lowerCaseWord, index);
if (index == -1) {
break;
}
indexes.add(index);
index++;
}
return indexes;
}

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

View File

@ -0,0 +1,149 @@
# This file is inspired by https://github.com/alexkaratarakis/gitattributes
#
# Auto detect text files and perform LF normalization
# http://davidlaing.com/2012/09/19/customise-your-gitattributes-to-become-a-git-ninja/
* text=auto
# The above will handle all files NOT found below
# These files are text and should be normalized (Convert crlf => lf)
*.bat text eol=crlf
*.coffee text
*.css text
*.cql text
*.df text
*.ejs text
*.html text
*.java text
*.js text
*.json text
*.less text
*.properties text
*.sass text
*.scss text
*.sh text eol=lf
*.sql text
*.txt text
*.ts text
*.xml text
*.yaml text
*.yml text
# Documents
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
*.markdown text
*.md text
*.adoc text
*.textile text
*.mustache text
*.csv text
*.tab text
*.tsv text
*.txt text
AUTHORS text
CHANGELOG text
CHANGES text
CONTRIBUTING text
COPYING text
copyright text
*COPYRIGHT* text
INSTALL text
license text
LICENSE text
NEWS text
readme text
*README* text
TODO text
# Graphics
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.tif binary
*.tiff binary
*.ico binary
# SVG treated as an asset (binary) by default. If you want to treat it as text,
# comment-out the following line and uncomment the line after.
*.svg binary
#*.svg text
*.eps binary
# These files are binary and should be left untouched
# (binary is a macro for -text -diff)
*.class binary
*.jar binary
*.war binary
## LINTERS
.csslintrc text
.eslintrc text
.jscsrc text
.jshintrc text
.jshintignore text
.stylelintrc text
## CONFIGS
*.bowerrc text
*.conf text
*.config text
.editorconfig text
.gitattributes text
.gitconfig text
.gitignore text
.htaccess text
*.npmignore text
## HEROKU
Procfile text
.slugignore text
## AUDIO
*.kar binary
*.m4a binary
*.mid binary
*.midi binary
*.mp3 binary
*.ogg binary
*.ra binary
## VIDEO
*.3gpp binary
*.3gp binary
*.as binary
*.asf binary
*.asx binary
*.fla binary
*.flv binary
*.m4v binary
*.mng binary
*.mov binary
*.mp4 binary
*.mpeg binary
*.mpg binary
*.swc binary
*.swf binary
*.webm binary
## ARCHIVES
*.7z binary
*.gz binary
*.rar binary
*.tar binary
*.zip binary
## FONTS
*.ttf binary
*.eot binary
*.otf binary
*.woff binary
*.woff2 binary

145
jhipster/jhipster-uaa/gateway/.gitignore vendored Normal file
View File

@ -0,0 +1,145 @@
######################
# Project Specific
######################
/src/main/webapp/content/css/main.css
/target/www/**
/src/test/javascript/coverage/
######################
# Node
######################
/node/
node_tmp/
node_modules/
npm-debug.log.*
/.awcache/*
/.cache-loader/*
######################
# 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
classes/
out/
######################
# 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

View File

@ -0,0 +1,5 @@
{
"hooks": {
"pre-commit": "lint-staged"
}
}

View File

@ -0,0 +1,38 @@
{
"name": "Quote",
"fields": [
{
"fieldName": "symbol",
"fieldType": "String",
"fieldValidateRules": [
"required",
"unique"
]
},
{
"fieldName": "price",
"fieldType": "BigDecimal",
"fieldValidateRules": [
"required"
]
},
{
"fieldName": "lastTrade",
"fieldType": "ZonedDateTime",
"fieldValidateRules": [
"required"
]
}
],
"relationships": [],
"changelogDate": "20181020145525",
"entityTableName": "quote",
"dto": "mapstruct",
"pagination": "pagination",
"service": "serviceImpl",
"jpaMetamodelFiltering": true,
"fluentMethods": true,
"clientRootFolder": "quotes",
"applications": "*",
"microserviceName": "quotes"
}

View File

@ -0,0 +1,110 @@
/*
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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

View File

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

View File

@ -0,0 +1,2 @@
node_modules
target

View File

@ -0,0 +1,12 @@
# Prettier configuration
printWidth: 140
singleQuote: true
tabWidth: 4
useTabs: false
# js and ts rules:
arrowParens: avoid
# jsx and tsx rules:
jsxBracketSameLine: false

View File

@ -0,0 +1,39 @@
{
"generator-jhipster": {
"promptValues": {
"packageName": "com.baeldung.jhipster.gateway",
"nativeLanguage": "en"
},
"jhipsterVersion": "5.4.2",
"applicationType": "gateway",
"baseName": "gateway",
"packageName": "com.baeldung.jhipster.gateway",
"packageFolder": "com/baeldung/jhipster/gateway",
"serverPort": "8080",
"authenticationType": "uaa",
"uaaBaseName": "uaa",
"cacheProvider": "hazelcast",
"enableHibernateCache": true,
"websocket": false,
"databaseType": "sql",
"devDatabaseType": "h2Disk",
"prodDatabaseType": "mysql",
"searchEngine": false,
"messageBroker": false,
"serviceDiscoveryType": "eureka",
"buildTool": "maven",
"enableSwaggerCodegen": false,
"clientFramework": "angularX",
"useSass": true,
"clientPackageManager": "npm",
"testFrameworks": [],
"jhiPrefix": "jhi",
"enableTranslation": true,
"nativeLanguage": "en",
"languages": [
"en",
"fr",
"pt-br"
]
}
}

View File

@ -0,0 +1,186 @@
# gateway
This application was generated using JHipster 5.4.2, you can find documentation and help at [https://www.jhipster.tech/documentation-archive/v5.4.2](https://www.jhipster.tech/documentation-archive/v5.4.2).
This is a "gateway" application intended to be part of a microservice architecture, please refer to the [Doing microservices with JHipster][] page of the documentation for more information.
This application is configured for Service Discovery and Configuration with the JHipster-Registry. On launch, it will refuse to start if it is not able to connect to the JHipster-Registry at [http://localhost:8761](http://localhost:8761). For more information, read our documentation on [Service Discovery and Configuration with the JHipster-Registry][].
## 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.
### Service workers
Service workers are commented by default, to enable them please uncomment the following code.
* The service worker registering script in index.html
```html
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./service-worker.js')
.then(function() { console.log('Service Worker Registered'); });
}
</script>
```
Note: workbox creates the respective service worker and dynamically generate the `service-worker.js`
### 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 gateway 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 [Jest][] and written with [Jasmine][]. They're located in [src/test/javascript/](src/test/javascript/) and can be run with:
npm test
For more information, refer to the [Running tests page][].
### Code quality
Sonar is used to analyse code quality. You can start a local Sonar server (accessible on http://localhost:9001) with:
```
docker-compose -f src/main/docker/sonar.yml up -d
```
Then, run a Sonar analysis:
```
./mvnw -Pprod clean test sonar:sonar
```
For more information, refer to the [Code quality 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 jib:dockerBuild
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 (`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 (`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://www.jhipster.tech
[JHipster 5.4.2 archive]: https://www.jhipster.tech/documentation-archive/v5.4.2
[Doing microservices with JHipster]: https://www.jhipster.tech/documentation-archive/v5.4.2/microservices-architecture/
[Using JHipster in development]: https://www.jhipster.tech/documentation-archive/v5.4.2/development/
[Service Discovery and Configuration with the JHipster-Registry]: https://www.jhipster.tech/documentation-archive/v5.4.2/microservices-architecture/#jhipster-registry
[Using Docker and Docker-Compose]: https://www.jhipster.tech/documentation-archive/v5.4.2/docker-compose
[Using JHipster in production]: https://www.jhipster.tech/documentation-archive/v5.4.2/production/
[Running tests page]: https://www.jhipster.tech/documentation-archive/v5.4.2/running-tests/
[Code quality page]: https://www.jhipster.tech/documentation-archive/v5.4.2/code-quality/
[Setting up Continuous Integration]: https://www.jhipster.tech/documentation-archive/v5.4.2/setting-up-ci/
[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/
[Jest]: https://facebook.github.io/jest/
[Jasmine]: http://jasmine.github.io/2.0/introduction.html
[Protractor]: https://angular.github.io/protractor/
[Leaflet]: http://leafletjs.com/
[DefinitelyTyped]: http://definitelytyped.org/

View File

@ -0,0 +1,39 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"gateway": {
"root": "",
"sourceRoot": "src/main/webapp",
"projectType": "application",
"architect": {}
}
},
"defaultProject": "gateway",
"cli": {
"packageManager": "yarn"
},
"schematics": {
"@schematics/angular:component": {
"inlineStyle": true,
"inlineTemplate": false,
"spec": false,
"prefix": "jhi",
"styleExt": "scss"
},
"@schematics/angular:directive": {
"spec": false,
"prefix": "jhi"
},
"@schematics/angular:guard": {
"spec": false
},
"@schematics/angular:pipe": {
"spec": false
},
"@schematics/angular:service": {
"spec": false
}
}
}

286
jhipster/jhipster-uaa/gateway/mvnw vendored Normal file
View File

@ -0,0 +1,286 @@
#!/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
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
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 Mingw, 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
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# 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"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
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} $MAVEN_CONFIG "$@"

161
jhipster/jhipster-uaa/gateway/mvnw.cmd vendored Normal file
View File

@ -0,0 +1,161 @@
@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 set title of command window
title %0
@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
@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="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
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%

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,131 @@
{
"name": "gateway",
"version": "0.0.0",
"description": "Description for gateway",
"private": true,
"license": "UNLICENSED",
"cacheDirectories": [
"node_modules"
],
"dependencies": {
"@angular/common": "6.1.0",
"@angular/compiler": "6.1.0",
"@angular/core": "6.1.0",
"@angular/forms": "6.1.0",
"@angular/platform-browser": "6.1.0",
"@angular/platform-browser-dynamic": "6.1.0",
"@angular/router": "6.1.0",
"@fortawesome/angular-fontawesome": "0.2.0",
"@fortawesome/fontawesome-svg-core": "1.2.4",
"@fortawesome/free-solid-svg-icons": "5.3.1",
"@ng-bootstrap/ng-bootstrap": "3.0.0",
"bootstrap": "4.1.3",
"core-js": "2.5.7",
"moment": "2.22.2",
"ng-jhipster": "0.5.4",
"ngx-cookie": "2.0.1",
"ngx-infinite-scroll": "0.5.1",
"ngx-webstorage": "2.0.1",
"reflect-metadata": "0.1.12",
"rxjs": "6.1.0",
"rxjs-compat": "6.1.0",
"swagger-ui": "2.2.10",
"tslib": "1.9.3",
"zone.js": "0.8.26"
},
"devDependencies": {
"@angular/cli": "6.1.2",
"@angular/compiler-cli": "6.1.0",
"@ngtools/webpack": "6.0.0",
"@types/jest": "22.2.3",
"@types/node": "9.4.7",
"angular-router-loader": "0.8.5",
"angular2-template-loader": "0.6.2",
"browser-sync": "2.24.6",
"browser-sync-webpack-plugin": "2.2.2",
"cache-loader": "1.2.2",
"codelyzer": "4.2.1",
"copy-webpack-plugin": "4.5.1",
"css-loader": "0.28.10",
"exports-loader": "0.7.0",
"file-loader": "1.1.11",
"fork-ts-checker-webpack-plugin": "0.4.1",
"friendly-errors-webpack-plugin": "1.7.0",
"generator-jhipster": "5.4.2",
"html-loader": "0.5.5",
"html-webpack-plugin": "3.2.0",
"husky": "1.1.0",
"jest": "22.4.3",
"jest-junit": "5.1.0",
"jest-preset-angular": "5.2.2",
"jest-sonar-reporter": "2.0.0",
"lint-staged": "7.3.0",
"merge-jsons-webpack-plugin": "1.0.14",
"mini-css-extract-plugin": "0.4.2",
"moment-locales-webpack-plugin": "1.0.5",
"optimize-css-assets-webpack-plugin": "5.0.1",
"prettier": "1.11.1",
"proxy-middleware": "0.15.0",
"raw-loader": "0.5.1",
"rimraf": "2.6.1",
"simple-progress-webpack-plugin": "1.1.2",
"style-loader": "0.20.3",
"tapable": "1.0.0",
"terser-webpack-plugin": "1.0.0",
"thread-loader": "1.1.5",
"to-string-loader": "1.1.5",
"ts-loader": "4.0.1",
"tslint": "5.9.1",
"tslint-config-prettier": "1.9.0",
"tslint-loader": "3.6.0",
"typescript": "2.7.2",
"sass": "1.13.0",
"sass-loader": "7.1.0",
"postcss-loader": "2.1.1",
"xml2js": "0.4.19",
"webpack": "4.8.0",
"webpack-cli": "2.1.3",
"webpack-dev-server": "3.1.5",
"webpack-merge": "4.1.2",
"webpack-notifier": "1.6.0",
"webpack-visualizer-plugin": "0.1.11",
"workbox-webpack-plugin": "3.2.0",
"write-file-webpack-plugin": "4.2.0"
},
"engines": {
"node": ">=8.9.0"
},
"lint-staged": {
"src/**/*.{ts,css,scss}": [
"prettier --write",
"git add"
]
},
"scripts": {
"prettier:format": "prettier --write \"src/**/*.{ts,css,scss}\"",
"lint": "tslint --project tsconfig.json -e 'node_modules/**'",
"lint:fix": "npm run lint -- --fix",
"ngc": "ngc -p tsconfig-aot.json",
"cleanup": "rimraf target/{aot,www}",
"clean-www": "rimraf target//www/app/{src,target/}",
"start": "npm run webpack:dev",
"start-tls": "npm run webpack:dev -- --env.tls",
"serve": "npm run start",
"build": "npm run webpack:prod",
"test": "npm run lint && jest --coverage --logHeapUsage -w=2 --config src/test/javascript/jest.conf.js",
"test:watch": "npm test -- --watch --clearCache",
"webpack:dev": "npm run webpack-dev-server -- --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --env.stats=minimal",
"webpack:dev-verbose": "npm run webpack-dev-server -- --config webpack/webpack.dev.js --inline --hot --port=9060 --watch-content-base --profile --progress --env.stats=normal",
"webpack:build:main": "npm run webpack -- --config webpack/webpack.dev.js --env.stats=normal",
"webpack:build": "npm run cleanup && npm run webpack:build:main",
"webpack:prod:main": "npm run webpack -- --config webpack/webpack.prod.js --profile",
"webpack:prod": "npm run cleanup && npm run webpack:prod:main && npm run clean-www",
"webpack:test": "npm run test",
"webpack-dev-server": "node --max_old_space_size=4096 node_modules/webpack-dev-server/bin/webpack-dev-server.js",
"webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js"
},
"jestSonar": {
"reportPath": "target/test-results/jest",
"reportFile": "TESTS-results-sonar.xml"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
module.exports = {
plugins: []
}

View File

@ -0,0 +1,7 @@
{
"*": {
"target": "http://localhost:8080",
"secure": false,
"loglevel": "debug"
}
}

View File

@ -0,0 +1,14 @@
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
classes/
generated-sources/
generated-test-sources/
h2db/
maven-archiver/
maven-status/
reports/
surefire-reports/
test-classes/
test-results/
www/
!*.jar
!*.war

View File

@ -0,0 +1,20 @@
FROM openjdk:8-jre-alpine
ENV SPRING_OUTPUT_ANSI_ENABLED=ALWAYS \
JHIPSTER_SLEEP=0 \
JAVA_OPTS=""
# Add a jhipster user to run our application so that it doesn't need to run as root
RUN adduser -D -s /bin/sh jhipster
WORKDIR /home/jhipster
ADD entrypoint.sh entrypoint.sh
RUN chmod 755 entrypoint.sh && chown jhipster:jhipster entrypoint.sh
USER jhipster
ENTRYPOINT ["./entrypoint.sh"]
EXPOSE 8080 5701/udp
ADD *.war app.war

View File

@ -0,0 +1,24 @@
version: '2'
services:
gateway-app:
image: gateway
environment:
# - _JAVA_OPTIONS=-Xmx512m -Xms256m
- SPRING_PROFILES_ACTIVE=prod,swagger
- EUREKA_CLIENT_SERVICE_URL_DEFAULTZONE=http://admin:$${jhipster.registry.password}@jhipster-registry:8761/eureka
- SPRING_CLOUD_CONFIG_URI=http://admin:$${jhipster.registry.password}@jhipster-registry:8761/config
- SPRING_DATASOURCE_URL=jdbc:mysql://gateway-mysql:3306/gateway?useUnicode=true&characterEncoding=utf8&useSSL=false
- JHIPSTER_SLEEP=30 # gives time for the JHipster Registry to boot before the application
ports:
- 8080:8080
gateway-mysql:
extends:
file: mysql.yml
service: gateway-mysql
jhipster-registry:
extends:
file: jhipster-registry.yml
service: jhipster-registry
environment:
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_TYPE=native
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_SEARCH_LOCATIONS=file:./central-config/docker-config/

View File

@ -0,0 +1,7 @@
# Central configuration sources details
The JHipster-Registry will use the following directories as its configuration source :
- localhost-config : when running the registry in docker with the jhipster-registry.yml docker-compose file
- docker-config : when running the registry and the app both in docker with the app.yml docker-compose file
For more info, refer to https://www.jhipster.tech/microservices-architecture/#registry_app_configuration

View File

@ -0,0 +1,15 @@
# Common configuration shared between all applications
configserver:
name: Docker JHipster Registry
status: Connected to the JHipster Registry running in Docker
jhipster:
security:
authentication:
jwt:
secret: my-secret-key-which-should-be-changed-in-production-and-be-base64-encoded
eureka:
client:
service-url:
defaultZone: http://admin:${jhipster.registry.password}@jhipster-registry:8761/eureka/

View File

@ -0,0 +1,15 @@
# Common configuration shared between all applications
configserver:
name: Docker JHipster Registry
status: Connected to the JHipster Registry running in Docker
jhipster:
security:
authentication:
jwt:
secret: my-secret-key-which-should-be-changed-in-production-and-be-base64-encoded
eureka:
client:
service-url:
defaultZone: http://admin:${jhipster.registry.password}@localhost:8761/eureka/

View File

@ -0,0 +1,4 @@
#!/bin/sh
echo "The application will start in ${JHIPSTER_SLEEP}s..." && sleep ${JHIPSTER_SLEEP}
exec java ${JAVA_OPTS} -Djava.security.egd=file:/dev/./urandom -jar "${HOME}/app.war" "$@"

View File

@ -0,0 +1,6 @@
version: '2'
services:
gateway-hazelcast-management-center:
image: hazelcast/management-center:3.9.3
ports:
- 8180:8080

View File

@ -0,0 +1,22 @@
version: '2'
services:
jhipster-registry:
image: jhipster/jhipster-registry:v4.0.4
volumes:
- ./central-server-config:/central-config
# When run with the "dev" Spring profile, the JHipster Registry will
# read the config from the local filesystem (central-server-config directory)
# When run with the "prod" Spring profile, it will read the configuration from a Git repository
# See https://www.jhipster.tech/microservices-architecture/#registry_app_configuration
environment:
# - _JAVA_OPTIONS=-Xmx512m -Xms256m
- SPRING_PROFILES_ACTIVE=dev,swagger,uaa
- SPRING_SECURITY_USER_PASSWORD=admin
- JHIPSTER_REGISTRY_PASSWORD=admin
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_TYPE=native
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_SEARCH_LOCATIONS=file:./central-config/localhost-config/
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_TYPE=git
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_URI=https://github.com/jhipster/jhipster-registry/
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_SEARCH_PATHS=central-config
ports:
- 8761:8761

View File

@ -0,0 +1,13 @@
version: '2'
services:
gateway-mysql:
image: mysql:5.7.20
# volumes:
# - ~/volumes/jhipster/gateway/mysql/:/var/lib/mysql/
environment:
- MYSQL_USER=root
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
- MYSQL_DATABASE=gateway
ports:
- 3306:3306
command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8mb4 --explicit_defaults_for_timestamp

View File

@ -0,0 +1,7 @@
version: '2'
services:
gateway-sonar:
image: sonarqube:7.1-alpine
ports:
- 9001:9000
- 9092:9092

View File

@ -0,0 +1,21 @@
package com.baeldung.jhipster.gateway;
import com.baeldung.jhipster.gateway.config.DefaultProfileUtil;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* This is a helper Java class that provides an alternative to creating a web.xml.
* This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc.
*/
public class ApplicationWebXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
/**
* set a default to use when no profile is configured.
*/
DefaultProfileUtil.addDefaultProfile(application.application());
return application.sources(GatewayApp.class);
}
}

View File

@ -0,0 +1,109 @@
package com.baeldung.jhipster.gateway;
import com.baeldung.jhipster.gateway.config.ApplicationProperties;
import com.baeldung.jhipster.gateway.config.DefaultProfileUtil;
import io.github.jhipster.config.JHipsterConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.core.env.Environment;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
@EnableDiscoveryClient
@EnableZuulProxy
public class GatewayApp {
private static final Logger log = LoggerFactory.getLogger(GatewayApp.class);
private final Environment env;
public GatewayApp(Environment env) {
this.env = env;
}
/**
* Initializes gateway.
* <p>
* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>.
*/
@PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! It should not run " +
"with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
/**
* Main method, used to run the application.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(GatewayApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
String configServerStatus = env.getProperty("configserver.status");
if (configServerStatus == null) {
configServerStatus = "Not found or not setup for this application";
}
log.info("\n----------------------------------------------------------\n\t" +
"Config Server: \t{}\n----------------------------------------------------------", configServerStatus);
}
}

View File

@ -0,0 +1,98 @@
package com.baeldung.jhipster.gateway.aop.logging;
import io.github.jhipster.config.JHipsterConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import java.util.Arrays;
/**
* Aspect for logging execution of service and repository Spring components.
*
* By default, it only runs with the "dev" profile.
*/
@Aspect
public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final Environment env;
public LoggingAspect(Environment env) {
this.env = env;
}
/**
* Pointcut that matches all repositories, services and Web REST endpoints.
*/
@Pointcut("within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)")
public void springBeanPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Pointcut that matches all Spring beans in the application's main packages.
*/
@Pointcut("within(com.baeldung.jhipster.gateway.repository..*)"+
" || within(com.baeldung.jhipster.gateway.service..*)"+
" || within(com.baeldung.jhipster.gateway.web.rest..*)")
public void applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.jhipster.gateway.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties specific to Gateway.
* <p>
* Properties are configured in the application.yml file.
* See {@link io.github.jhipster.config.JHipsterProperties} for a good example.
*/
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {
}

View File

@ -0,0 +1,59 @@
package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
import io.github.jhipster.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final JHipsterProperties jHipsterProperties;
public AsyncConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
executor.setThreadNamePrefix("gateway-Executor-");
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(scheduledTaskExecutor());
}
@Bean
public Executor scheduledTaskExecutor() {
return Executors.newScheduledThreadPool(jHipsterProperties.getAsync().getCorePoolSize());
}
}

View File

@ -0,0 +1,155 @@
package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import com.hazelcast.config.*;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.Hazelcast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import javax.annotation.PreDestroy;
@Configuration
@EnableCaching
public class CacheConfiguration {
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
private final Environment env;
private final ServerProperties serverProperties;
private final DiscoveryClient discoveryClient;
private Registration registration;
public CacheConfiguration(Environment env, ServerProperties serverProperties, DiscoveryClient discoveryClient) {
this.env = env;
this.serverProperties = serverProperties;
this.discoveryClient = discoveryClient;
}
@Autowired(required = false)
public void setRegistration(Registration registration) {
this.registration = registration;
}
@PreDestroy
public void destroy() {
log.info("Closing Cache Manager");
Hazelcast.shutdownAll();
}
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
log.debug("Starting HazelcastCacheManager");
CacheManager cacheManager = new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance);
return cacheManager;
}
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
log.debug("Configuring Hazelcast");
HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("gateway");
if (hazelCastInstance != null) {
log.debug("Hazelcast already initialized");
return hazelCastInstance;
}
Config config = new Config();
config.setInstanceName("gateway");
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
if (this.registration == null) {
log.warn("No discovery service is set up, Hazelcast cannot create a cluster.");
} else {
// The serviceId is by default the application's name,
// see the "spring.application.name" standard Spring property
String serviceId = registration.getServiceId();
log.debug("Configuring Hazelcast clustering for instanceId: {}", serviceId);
// In development, everything goes through 127.0.0.1, with a different port
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
log.debug("Application is running with the \"dev\" profile, Hazelcast " +
"cluster will only work with localhost instances");
System.setProperty("hazelcast.local.localAddress", "127.0.0.1");
config.getNetworkConfig().setPort(serverProperties.getPort() + 5701);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
String clusterMember = "127.0.0.1:" + (instance.getPort() + 5701);
log.debug("Adding Hazelcast (dev) cluster member " + clusterMember);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember);
}
} else { // Production configuration, one host per instance all using port 5701
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
String clusterMember = instance.getHost() + ":5701";
log.debug("Adding Hazelcast (prod) cluster member " + clusterMember);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember);
}
}
}
config.getMapConfigs().put("default", initializeDefaultMapConfig(jHipsterProperties));
// Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html
config.setManagementCenterConfig(initializeDefaultManagementCenterConfig(jHipsterProperties));
config.getMapConfigs().put("com.baeldung.jhipster.gateway.domain.*", initializeDomainMapConfig(jHipsterProperties));
return Hazelcast.newHazelcastInstance(config);
}
private ManagementCenterConfig initializeDefaultManagementCenterConfig(JHipsterProperties jHipsterProperties) {
ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig();
managementCenterConfig.setEnabled(jHipsterProperties.getCache().getHazelcast().getManagementCenter().isEnabled());
managementCenterConfig.setUrl(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUrl());
managementCenterConfig.setUpdateInterval(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUpdateInterval());
return managementCenterConfig;
}
private MapConfig initializeDefaultMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
/*
Number of backups. If 1 is set as the backup-count for example,
then all entries of the map will be copied to another JVM for
fail-safety. Valid numbers are 0 (no backup), 1, 2, 3.
*/
mapConfig.setBackupCount(jHipsterProperties.getCache().getHazelcast().getBackupCount());
/*
Valid values are:
NONE (no eviction),
LRU (Least Recently Used),
LFU (Least Frequently Used).
NONE is the default.
*/
mapConfig.setEvictionPolicy(EvictionPolicy.LRU);
/*
Maximum size of the map. When max size is reached,
map is evicted based on the policy defined.
Any integer between 0 and Integer.MAX_VALUE. 0 means
Integer.MAX_VALUE. Default is 0.
*/
mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds());
return mapConfig;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
@Configuration
@Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {
private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
@Bean
public DataSource dataSource(CacheManager cacheManager) {
log.info("Configuring JDBC datasource from a cloud provider");
return connectionFactory().dataSource();
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.jhipster.gateway.config;
/**
* Application constants.
*/
public final class Constants {
// Regex for acceptable logins
public static final String LOGIN_REGEX = "^[_.@A-Za-z0-9-]*$";
public static final String SYSTEM_ACCOUNT = "system";
public static final String ANONYMOUS_USER = "anonymoususer";
public static final String DEFAULT_LANGUAGE = "en";
private Constants() {
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.sql.SQLException;
@Configuration
@EnableJpaRepositories("com.baeldung.jhipster.gateway.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
/**
* Open the TCP port for the H2 database, so it is available remotely.
*
* @return the H2 database TCP server
* @throws SQLException if the server failed to start
*/
@Bean(initMethod = "start", destroyMethod = "stop")
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public Object h2TCPServer() throws SQLException {
log.debug("Starting H2 database");
return H2ConfigurationHelper.createServer();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.jhipster.gateway.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Configure the converters to use the ISO format for dates by default.
*/
@Configuration
public class DateTimeFormatConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterConstants;
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.Environment;
import java.util.*;
/**
* Utility class to load a Spring profile to be used as default
* when there is no <code>spring.profiles.active</code> set in the environment or as command line argument.
* If the value is not available in <code>application.yml</code> then <code>dev</code> profile will be used as default.
*/
public final class DefaultProfileUtil {
private static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default";
private DefaultProfileUtil() {
}
/**
* Set a default to use when no profile is configured.
*
* @param app the Spring application
*/
public static void addDefaultProfile(SpringApplication app) {
Map<String, Object> defProperties = new HashMap<>();
/*
* The default profile to use when no other profiles are defined
* This cannot be set in the <code>application.yml</code> file.
* See https://github.com/spring-projects/spring-boot/issues/1219
*/
defProperties.put(SPRING_PROFILE_DEFAULT, JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
app.setDefaultProperties(defProperties);
}
/**
* Get the profiles that are applied else get default profiles.
*
* @param env spring environment
* @return profiles
*/
public static String[] getActiveProfiles(Environment env) {
String[] profiles = env.getActiveProfiles();
if (profiles.length == 0) {
return env.getDefaultProfiles();
}
return profiles;
}
}

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