diff --git a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java index 3523ff07c0..d278418a87 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Stack; -import java.util.stream.Collectors; public class HillClimbing { public static void main(String[] args) { @@ -22,7 +21,7 @@ public class HillClimbing { } } - public static void printEachStep(State state) { + private static void printEachStep(State state) { List> stackList = state.getState(); System.out.println("----------------"); stackList.forEach(stack -> { @@ -33,8 +32,8 @@ public class HillClimbing { }); } - public Stack getStackWithValues(String[] blocks) { - Stack stack = new Stack(); + private Stack getStackWithValues(String[] blocks) { + Stack stack = new Stack<>(); for (String block : blocks) stack.push(block); return stack; @@ -42,14 +41,9 @@ public class HillClimbing { /** * This method prepares path from init state to goal state - * - * @param initStateStack - * @param goalStateStack - * @return - * @throws Exception */ public List getRouteWithHillClimbing(Stack initStateStack, Stack goalStateStack) throws Exception { - List> initStateStackList = new ArrayList>(); + List> initStateStackList = new ArrayList<>(); initStateStackList.add(initStateStack); int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack); State initState = new State(initStateStackList, initStateHeuristics); @@ -71,57 +65,51 @@ public class HillClimbing { } } - if (noStateFound) - throw new Exception("No path found"); return resultPath; } /** * This method finds new state from current state based on goal and * heuristics - * - * @param currentState - * @param goalStateStack - * @return a next state */ public State findNextState(State currentState, Stack goalStateStack) { List> listOfStacks = currentState.getState(); int currentStateHeuristics = currentState.getHeuristics(); - Optional newState = listOfStacks.stream() + return listOfStacks.stream() .map(stack -> { - State tempState = null; - List> tempStackList = new ArrayList>(listOfStacks); - String block = stack.pop(); - if (stack.size() == 0) - tempStackList.remove(stack); - tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack); - if (tempState == null) { - tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack); - } - if (tempState == null) - stack.push(block); - return tempState; + return applyOperationsOnState(listOfStacks, stack, currentStateHeuristics, goalStateStack); }) .filter(Objects::nonNull) - .findFirst(); - - return newState.orElse(null); + .findFirst() + .orElse(null); } + /** + * This method applies operations on the current state to get a new state + */ + public State applyOperationsOnState(List> listOfStacks, Stack stack, int currentStateHeuristics, Stack goalStateStack) { + State tempState; + List> tempStackList = new ArrayList<>(listOfStacks); + String block = stack.pop(); + if (stack.size() == 0) + tempStackList.remove(stack); + tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack); + if (tempState == null) { + tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack); + } + if (tempState == null) + stack.push(block); + return tempState; + } + /** * Operation to be applied on a state in order to find new states. This * operation pushes an element into a new stack - * - * @param currentStackList - * @param block - * @param currentStateHeuristics - * @param goalStateStack - * @return a new state */ private State pushElementToNewStack(List> currentStackList, String block, int currentStateHeuristics, Stack goalStateStack) { State newState = null; - Stack newStack = new Stack(); + Stack newStack = new Stack<>(); newStack.push(block); currentStackList.add(newStack); @@ -138,62 +126,64 @@ public class HillClimbing { * Operation to be applied on a state in order to find new states. This * operation pushes an element into one of the other stacks to explore new * states - * - * @param stack - * @param currentStackList - * @param block - * @param currentStateHeuristics - * @param goalStateStack - * @return a new state */ private State pushElementToExistingStacks(Stack currentStack, List> currentStackList, String block, int currentStateHeuristics, Stack goalStateStack) { Optional newState = currentStackList.stream() .filter(stack -> stack != currentStack) .map(stack -> { - stack.push(block); - int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack); - if (newStateHeuristics > currentStateHeuristics) { - return new State(currentStackList, newStateHeuristics); - } - stack.pop(); - return null; + return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack); }) .filter(Objects::nonNull) .findFirst(); return newState.orElse(null); } + + /** + * This method pushes a block to the stack and returns new state if its closer to goal + */ + private State pushElementToStack(Stack stack, String block, List> currentStackList, int currentStateHeuristics, Stack goalStateStack) { + stack.push(block); + int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack); + if (newStateHeuristics > currentStateHeuristics) { + return new State(currentStackList, newStateHeuristics); + } + stack.pop(); + return null; + } /** * This method returns heuristics value for given state with respect to goal * state - * - * @param currentState - * @param goalStateStack - * @return */ public int getHeuristicsValue(List> currentState, Stack goalStateStack) { - - Integer heuristicValue = 0; + Integer heuristicValue; heuristicValue = currentState.stream() .mapToInt(stack -> { - int stackHeuristics = 0; - boolean isPositioneCorrect = true; - int goalStartIndex = 0; - for (String currentBlock : stack) { - if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) { - stackHeuristics += goalStartIndex; - } else { - stackHeuristics -= goalStartIndex; - isPositioneCorrect = false; - } - goalStartIndex++; - } - return stackHeuristics; + return getHeuristicsValueForStack(stack, currentState, goalStateStack); }) .sum(); return heuristicValue; } + + /** + * This method returns heuristics value for a particular stack + */ + public int getHeuristicsValueForStack(Stack stack, List> currentState, Stack goalStateStack) { + int stackHeuristics = 0; + boolean isPositioneCorrect = true; + int goalStartIndex = 0; + for (String currentBlock : stack) { + if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) { + stackHeuristics += goalStartIndex; + } else { + stackHeuristics -= goalStartIndex; + isPositioneCorrect = false; + } + goalStartIndex++; + } + return stackHeuristics; + } } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java index dc49c782fa..ad22aa27e7 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java @@ -5,26 +5,23 @@ import java.util.List; import java.util.Stack; public class State { - List> state; - int heuristics; - - public State() { - } + private List> state; + private int heuristics; public State(List> state) { this.state = state; } - public State(List> state, int heuristics) { + State(List> state, int heuristics) { this.state = state; this.heuristics = heuristics; } - public State(State state) { + State(State state) { if (state != null) { - this.state = new ArrayList>(); + this.state = new ArrayList<>(); for (Stack s : state.getState()) { - Stack s1 = new Stack(); + Stack s1; s1 = (Stack) s.clone(); this.state.add(s1); } @@ -36,10 +33,6 @@ public class State { return state; } - public void setState(List> state) { - this.state = state; - } - public int getHeuristics() { return heuristics; } diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java index f040d3a4ca..6e5055da6e 100644 --- a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java +++ b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java @@ -14,17 +14,17 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class HillClimbingAlgorithmTest { - Stack initStack; - Stack goalStack; + private Stack initStack; + private Stack goalStack; @Before public void initStacks() { String blockArr[] = { "B", "C", "D", "A" }; String goalBlockArr[] = { "A", "B", "C", "D" }; - initStack = new Stack(); + initStack = new Stack<>(); for (String block : blockArr) initStack.push(block); - goalStack = new Stack(); + goalStack = new Stack<>(); for (String block : goalBlockArr) goalStack.push(block); } @@ -48,7 +48,7 @@ public class HillClimbingAlgorithmTest { @Test public void givenCurrentState_whenFindNextState_thenBetterHeuristics() { HillClimbing hillClimbing = new HillClimbing(); - List> initList = new ArrayList>(); + List> initList = new ArrayList<>(); initList.add(initStack); State currentState = new State(initList); currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack)); diff --git a/core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java b/core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java new file mode 100644 index 0000000000..ee4e35a77b --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/time/TimeApi.java @@ -0,0 +1,43 @@ +package com.baeldung.java9.time; + +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class TimeApi { + + public static List getDatesBetweenUsingJava7(Date startDate, Date endDate) { + List datesInRange = new ArrayList(); + Calendar calendar = new GregorianCalendar(); + calendar.setTime(startDate); + + Calendar endCalendar = new GregorianCalendar(); + endCalendar.setTime(endDate); + + while (calendar.before(endCalendar)) { + Date result = calendar.getTime(); + datesInRange.add(result); + calendar.add(Calendar.DATE, 1); + } + return datesInRange; + } + + public static List getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate) { + long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate); + return IntStream.iterate(0, i -> i + 1) + .limit(numOfDaysBetween) + .mapToObj(i -> startDate.plusDays(i)) + .collect(Collectors.toList()); + } + + public static List getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) { + return startDate.datesUntil(endDate).collect(Collectors.toList()); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java b/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java new file mode 100644 index 0000000000..a024db19a8 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/time/TimeApiTest.java @@ -0,0 +1,58 @@ +package com.baeldung.java9.time; + +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class TimeApiTest { + + @Test + public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() { + Date startDate = Calendar.getInstance().getTime(); + Calendar endCalendar = Calendar.getInstance(); + endCalendar.add(Calendar.DATE, 2); + Date endDate = endCalendar.getTime(); + + List dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate); + assertEquals(dates.size(), 2); + + Calendar calendar = Calendar.getInstance(); + Date date1 = calendar.getTime(); + assertEquals(dates.get(0).getDay(), date1.getDay()); + assertEquals(dates.get(0).getMonth(), date1.getMonth()); + assertEquals(dates.get(0).getYear(), date1.getYear()); + + calendar.add(Calendar.DATE, 1); + Date date2 = calendar.getTime(); + assertEquals(dates.get(1).getDay(), date2.getDay()); + assertEquals(dates.get(1).getMonth(), date2.getMonth()); + assertEquals(dates.get(1).getYear(), date2.getYear()); + } + + @Test + public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() { + LocalDate startDate = LocalDate.now(); + LocalDate endDate = LocalDate.now().plusDays(2); + + List dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate); + assertEquals(dates.size(), 2); + assertEquals(dates.get(0), LocalDate.now()); + assertEquals(dates.get(1), LocalDate.now().plusDays(1)); + } + + @Test + public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() { + LocalDate startDate = LocalDate.now(); + LocalDate endDate = LocalDate.now().plusDays(2); + + List dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate); + assertEquals(dates.size(), 2); + assertEquals(dates.get(0), LocalDate.now()); + assertEquals(dates.get(1), LocalDate.now().plusDays(1)); + } + +} diff --git a/core-java/.gitignore b/core-java/.gitignore index 2a03a0f72e..3de4cc647e 100644 --- a/core-java/.gitignore +++ b/core-java/.gitignore @@ -17,9 +17,10 @@ # Files generated by integration tests *.txt +backup-pom.xml /bin/ /temp #IntelliJ specific -.idea +.idea/ *.iml \ No newline at end of file diff --git a/core-java/pom.xml b/core-java/pom.xml index 1f4804e059..2267dba1e6 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,405 +1,404 @@ - 4.0.0 - com.baeldung - core-java - 0.1.0-SNAPSHOT - jar + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + core-java + 0.1.0-SNAPSHOT + jar - core-java + core-java - + - - - net.sourceforge.collections - collections-generic - ${collections-generic.version} - - - com.google.guava - guava - ${guava.version} - + + + net.sourceforge.collections + collections-generic + ${collections-generic.version} + + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + - - commons-io - commons-io - ${commons-io.version} - + + commons-io + commons-io + ${commons-io.version} + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - org.apache.commons - commons-math3 - ${commons-math3.version} - + + org.apache.commons + commons-math3 + ${commons-math3.version} + - - org.decimal4j - decimal4j - ${decimal4j.version} - + + org.decimal4j + decimal4j + ${decimal4j.version} + - - org.bouncycastle - bcprov-jdk15on - ${bouncycastle.version} - + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + - - org.unix4j - unix4j-command - ${unix4j.version} - + + org.unix4j + unix4j-command + ${unix4j.version} + - - com.googlecode.grep4j - grep4j - ${grep4j.version} - - + + com.googlecode.grep4j + grep4j + ${grep4j.version} + + - + - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + - + - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - org.projectlombok - lombok - ${lombok.version} - provided - + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + - + - - org.hamcrest - hamcrest-all - 1.3 - test - + + org.hamcrest + hamcrest-all + 1.3 + test + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.assertj - assertj-core - ${assertj.version} - test - + + org.assertj + assertj-core + ${assertj.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - - - com.jayway.awaitility - awaitility - ${avaitility.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + - - commons-codec - commons-codec - ${commons-codec.version} - + + commons-codec + commons-codec + ${commons-codec.version} + - - org.javamoney - moneta - 1.1 - + + org.javamoney + moneta + 1.1 + - - org.owasp.esapi - esapi - 2.1.0.1 - + + org.owasp.esapi + esapi + 2.1.0.1 + - - com.sun.messaging.mq - fscontext - ${fscontext.version} - - + + com.sun.messaging.mq + fscontext + ${fscontext.version} + + - - core-java - - - src/main/resources - true - - + + core-java + + + src/main/resources + true + + - + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - - true - - + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + + true + + - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - prepare-package - - copy-dependencies - - - ${project.build.directory}/libs - - - - + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + - - org.apache.maven.plugins - maven-jar-plugin - - - - true - libs/ - org.baeldung.executable.ExecutableMavenJar - - - - + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + org.baeldung.executable.ExecutableMavenJar + + + + - - org.apache.maven.plugins - maven-assembly-plugin - - - package - - single - - - ${project.basedir} - - - org.baeldung.executable.ExecutableMavenJar - - - - jar-with-dependencies - - - - - + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + ${project.basedir} + + + org.baeldung.executable.ExecutableMavenJar + + + + jar-with-dependencies + + + + + - - org.apache.maven.plugins - maven-shade-plugin - - - - shade - - - true - - - org.baeldung.executable.ExecutableMavenJar - - - - - - + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + + true + + + org.baeldung.executable.ExecutableMavenJar + + + + + + - - com.jolira - onejar-maven-plugin - - - - org.baeldung.executable.ExecutableMavenJar - true - ${project.build.finalName}-onejar.${project.packaging} - - - one-jar - - - - + + com.jolira + onejar-maven-plugin + + + + org.baeldung.executable.ExecutableMavenJar + true + ${project.build.finalName}-onejar.${project.packaging} + + + one-jar + + + + - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - spring-boot - org.baeldung.executable.ExecutableMavenJar - - - - + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + spring-boot + org.baeldung.executable.ExecutableMavenJar + + + + - + - + - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + - - - 2.8.5 + + + 2.8.5 - - 1.7.21 - 1.1.7 + + 1.7.21 + 1.1.7 - - 21.0 - 3.5 - 1.55 - 1.10 - 3.6.1 - 1.0.3 - 2.5 - 4.1 - 4.01 - 0.4 - 1.8.7 - 1.16.12 - 4.6-b01 + + 21.0 + 3.5 + 1.55 + 1.10 + 3.6.1 + 1.0.3 + 2.5 + 4.1 + 4.01 + 0.4 + 1.8.7 + 1.16.12 + 4.6-b01 - - 1.3 - 4.12 - 1.10.19 - 3.6.1 - 1.7.0 + + 1.3 + 4.12 + 1.10.19 + 3.6.1 + 1.7.0 - - 3.6.0 - 2.19.1 - - + + 3.6.0 + 2.19.1 + \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/java/reflection/DynamicGreeter.java b/core-java/src/main/java/com/baeldung/java/reflection/DynamicGreeter.java new file mode 100644 index 0000000000..3776ef82e2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/DynamicGreeter.java @@ -0,0 +1,23 @@ +package com.baeldung.java.reflection; + +import java.lang.annotation.Annotation; + +public class DynamicGreeter implements Greeter { + + private String greet; + + public DynamicGreeter(String greet) { + this.greet = greet; + } + + @Override + public Class annotationType() { + return DynamicGreeter.class; + } + + @Override + public String greet() { + return greet; + } + +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java new file mode 100644 index 0000000000..ede269528a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Greeter.java @@ -0,0 +1,10 @@ +package com.baeldung.java.reflection; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface Greeter { + + public String greet() default ""; +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/GreetingAnnotation.java b/core-java/src/main/java/com/baeldung/java/reflection/GreetingAnnotation.java new file mode 100644 index 0000000000..601306f5d2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/GreetingAnnotation.java @@ -0,0 +1,58 @@ +package com.baeldung.java.reflection; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Map; + +public class GreetingAnnotation { + + private static final String ANNOTATION_METHOD = "annotationData"; + private static final String ANNOTATION_FIELDS = "declaredAnnotations"; + private static final String ANNOTATIONS = "annotations"; + + public static void main(String ...args) { + Greeter greetings = Greetings.class.getAnnotation(Greeter.class); + System.err.println("Hello there, " + greetings.greet() + " !!"); + + Greeter targetValue = new DynamicGreeter("Good evening"); + //alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue); + alterAnnotationValueJDK7(Greetings.class, Greeter.class, targetValue); + + greetings = Greetings.class.getAnnotation(Greeter.class); + System.err.println("Hello there, " + greetings.greet() + " !!"); + } + + @SuppressWarnings("unchecked") + public static void alterAnnotationValueJDK8(Class targetClass, Class targetAnnotation, Annotation targetValue) { + try { + Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null); + method.setAccessible(true); + + Object annotationData = method.invoke(targetClass); + + Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS); + annotations.setAccessible(true); + + Map, Annotation> map = (Map, Annotation>) annotations.get(annotationData); + map.put(targetAnnotation, targetValue); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("unchecked") + public static void alterAnnotationValueJDK7(Class targetClass, Class targetAnnotation, Annotation targetValue) { + try { + Field annotations = Class.class.getDeclaredField(ANNOTATIONS); + annotations.setAccessible(true); + + Map, Annotation> map = (Map, Annotation>) annotations.get(targetClass); + System.out.println(map); + map.put(targetAnnotation, targetValue); + System.out.println(map); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Greetings.java b/core-java/src/main/java/com/baeldung/java/reflection/Greetings.java new file mode 100644 index 0000000000..4f3a20c3b9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java/reflection/Greetings.java @@ -0,0 +1,6 @@ +package com.baeldung.java.reflection; + +@Greeter(greet="Good morning") +public class Greetings { + +} diff --git a/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java new file mode 100644 index 0000000000..d795f90419 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/map/iteration/MapIteration.java @@ -0,0 +1,58 @@ +package com.baeldung.map.iteration; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class MapIteration { + + public List iterateUsingEntrySet(Map map) { + List mapKeyValueList = new ArrayList<>(); + for (Map.Entry entry : map.entrySet()) { + mapKeyValueList.add(entry.getKey() + ":" + entry.getValue()); + } + return mapKeyValueList; + } + + public List iterateUsingLambda(Map map) { + List mapKeyValueList = new ArrayList<>(); + map.forEach((k, v) -> mapKeyValueList.add(k + ":" + v)); + return mapKeyValueList; + } + + public List iterateUsingIteratorAndEntry(Map map) { + ArrayList mapKeyValueList = new ArrayList<>(); + Iterator> iterator = map.entrySet().iterator(); + + while (iterator.hasNext()) { + Map.Entry pair = iterator.next(); + mapKeyValueList.add(pair.getKey() + ":" + pair.getValue()); + } + + return mapKeyValueList; + } + + public List iterateUsingKeySetAndForeach(Map map) { + List mapKeyValueList = new ArrayList<>(); + for (String key : map.keySet()) { + mapKeyValueList.add(key + ":" + map.get(key)); + } + return mapKeyValueList; + } + + public List iterateUsingStreamAPI(Map map) { + ArrayList mapKeyValueList = new ArrayList<>(); + map.entrySet().stream().forEach(e -> mapKeyValueList.add(e.getKey() + ":" + e.getValue())); + return mapKeyValueList; + } + + public ArrayList iterateKeys(Map map) { + ArrayList mapKeyList = new ArrayList<>(); + for (String key : map.keySet()) { + mapKeyList.add(key); + } + return mapKeyList; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/reflection/BaeldungReflectionUtils.java b/core-java/src/main/java/com/baeldung/reflection/BaeldungReflectionUtils.java new file mode 100644 index 0000000000..a5b3bf8d2d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/reflection/BaeldungReflectionUtils.java @@ -0,0 +1,43 @@ +package com.baeldung.reflection; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class BaeldungReflectionUtils { + + private static final Logger LOG = LoggerFactory.getLogger(BaeldungReflectionUtils.class); + + + public static List getNullPropertiesList(Customer customer) throws Exception { + PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors(); + List propDescList = Arrays.asList(propDescArr); + + List nullProps = propDescList.stream() + .filter(nulls(customer)) + .map(PropertyDescriptor::getName) + .collect(Collectors.toList()); + return nullProps; + } + + private static Predicate nulls(Customer customer) { + Predicate isNull = pd -> { + Method getterMethod = pd.getReadMethod(); + boolean result = false; + try { + result = (getterMethod != null && getterMethod.invoke(customer) == null); + } catch (Exception e) { + LOG.error("error invoking getter method"); + } + return result; + }; + return isNull; + } +} diff --git a/core-java/src/main/java/com/baeldung/reflection/Customer.java b/core-java/src/main/java/com/baeldung/reflection/Customer.java new file mode 100644 index 0000000000..13d61578fe --- /dev/null +++ b/core-java/src/main/java/com/baeldung/reflection/Customer.java @@ -0,0 +1,58 @@ +package com.baeldung.reflection; + +public class Customer { + + private Integer id; + private String name; + private String emailId; + private Long phoneNumber; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmailId() { + return emailId; + } + + public void setEmailId(String emailId) { + this.emailId = emailId; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Customer [id=").append(id).append(", name=").append(name).append(", emailId=").append(emailId).append(", phoneNumber=") + .append(phoneNumber).append("]"); + return builder.toString(); + } + + public Customer(Integer id, String name, String emailId, Long phoneNumber) { + super(); + this.id = id; + this.name = name; + this.emailId = emailId; + this.phoneNumber = phoneNumber; + } + + public Long getPhoneNumber() { + return phoneNumber; + } + + public void setPhoneNumber(Long phoneNumber) { + this.phoneNumber = phoneNumber; + } + +} diff --git a/core-java/src/main/java/com/baeldung/string/StringToCharStream.java b/core-java/src/main/java/com/baeldung/string/StringToCharStream.java new file mode 100644 index 0000000000..4dc0455192 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/string/StringToCharStream.java @@ -0,0 +1,46 @@ +package com.baeldung.string; + +import java.util.HashMap; +import java.util.Map; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +/** + * Created by smatt on 26/05/2017. + */ +public class StringToCharStream { + + public StringToCharStream() { + + //let's use the Stream API to manipulate a string + //this will count the occurrence of each character in the test string + + System.out.println("Counting Occurrence of Letter"); + String testString = "Noww"; + + //we don't want to use foreach, so . . . + + Map map = new HashMap<>(); + + testString.codePoints() + .mapToObj(c -> (char) c) + .filter(c -> Character.isLetter(c)) + .forEach(c -> { + if(map.containsKey(c)) { + map.put(c, map.get(c) + 1); + } else { + map.put(c, 1); + } + }); + + //printing out the result here + System.out.println(map.toString()); + } + + + public static void main(String [] args) { + new StringToCharStream(); + } + + +} diff --git a/core-java/src/test/java/com/baeldung/map/iteration/MapIterationTest.java b/core-java/src/test/java/com/baeldung/map/iteration/MapIterationTest.java new file mode 100644 index 0000000000..47dcd9ab1a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/map/iteration/MapIterationTest.java @@ -0,0 +1,69 @@ +package com.baeldung.map.iteration; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class MapIterationTest { + + public static Map testMap = new HashMap(); + public static String testString1 = "One:1"; + public static String testString2 = "Two:2"; + public static String testString3 = "Three:3"; + + @BeforeClass + public static void createTestData() { + testMap.put("One", 1); + testMap.put("Three", 3); + testMap.put("Two", 2); + } + + @Test + public void givenMap_whenIterateUsingEntrySetReturnsAllEntries_thenCorrect() { + MapIteration mapIteration = new MapIteration(); + List list = mapIteration.iterateUsingEntrySet(testMap); + assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3))); + } + + @Test + public void givenMap_whenIterateUsingLambdaReturnsAllEntries_thenCorrect() { + MapIteration mapIteration = new MapIteration(); + List list = mapIteration.iterateUsingLambda(testMap); + assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3))); + } + + @Test + public void givenMap_whenIterateUsingIteratorAndEntryReturnsAllEntries_thenCorrect() { + MapIteration mapIteration = new MapIteration(); + List list = mapIteration.iterateUsingIteratorAndEntry(testMap); + assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3))); + } + + @Test + public void givenMap_whenIterateUsingKeySetAndForeachReturnsAllEntries_thenCorrect() { + MapIteration mapIteration = new MapIteration(); + List list = mapIteration.iterateUsingKeySetAndForeach(testMap); + assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3))); + } + + @Test + public void givenMap_whenIterateUsingStreamAPIReturnsAllEntries_thenCorrect() { + MapIteration mapIteration = new MapIteration(); + List list = mapIteration.iterateUsingStreamAPI(testMap); + assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3))); + } + + @Test + public void givenMap_whenIterateUsingKeysReturnsAllKeys_thenCorrect() { + MapIteration mapIteration = new MapIteration(); + ArrayList list = mapIteration.iterateKeys(testMap); + assertTrue((list.contains("One")) && (list.contains("Two")) && (list.contains("Three"))); + } + +} diff --git a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java new file mode 100644 index 0000000000..76916df6ce --- /dev/null +++ b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java @@ -0,0 +1,23 @@ +package com.baeldung.reflection; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +public class BaeldungReflectionUtilsTest { + + @Test + public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception { + Customer customer = new Customer(1, "Himanshu", null, null); + + List result = BaeldungReflectionUtils.getNullPropertiesList(customer); + List expectedFieldNames = Arrays.asList("emailId", "phoneNumber"); + + Assert.assertTrue(result.size() == expectedFieldNames.size()); + Assert.assertTrue(result.containsAll(expectedFieldNames)); + + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java b/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java new file mode 100644 index 0000000000..0c265d0b1f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/StringToCharStreamUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.string; + +import org.junit.Test; + +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Created by smatt on 09/06/2017. + */ +public class StringToCharStreamUnitTest { + + String testString = "Tests"; + + @Test + public void givenTestString_whenChars_thenReturnIntStream() { + assertTrue(testString.chars() instanceof IntStream); + } + + @Test + public void givenTestString_whenCodePoints_thenReturnIntStream() { + assertTrue(testString.codePoints() instanceof IntStream); + } + + @Test + public void givenIntStream_whenMapToObj_thenReturnCharacterStream() { + Stream characterStream = testString.chars().mapToObj(c -> (char) c); + Stream characterStream1 = testString.codePoints().mapToObj(c -> (char) c); + assertNotNull("IntStream returned by chars() did not map to Stream", characterStream); + assertNotNull("IntStream returned by codePoints() did not map to Stream", characterStream1); + } + +} diff --git a/libraries/OpenNLP/PartOfSpeechTag.txt b/libraries/OpenNLP/PartOfSpeechTag.txt new file mode 100644 index 0000000000..fdd8238ec4 --- /dev/null +++ b/libraries/OpenNLP/PartOfSpeechTag.txt @@ -0,0 +1 @@ +Out of the night that covers me \ No newline at end of file diff --git a/libraries/OpenNLP/doc-cat.train b/libraries/OpenNLP/doc-cat.train new file mode 100644 index 0000000000..c457221ec6 --- /dev/null +++ b/libraries/OpenNLP/doc-cat.train @@ -0,0 +1,10 @@ +GOOD good morning / +GOOD good evening / +GOOD have a good day / +GOOD nice party! / +GOOD fine pants / +BAD nightmare volcano in the sea / +BAD darkest sky / +BAD greed and waste / +BAD army attacks / +BAD bomb explodes / \ No newline at end of file diff --git a/libraries/OpenNLP/en-chunker.bin b/libraries/OpenNLP/en-chunker.bin new file mode 100644 index 0000000000..65d9356888 Binary files /dev/null and b/libraries/OpenNLP/en-chunker.bin differ diff --git a/libraries/OpenNLP/en-ner-location.bin b/libraries/OpenNLP/en-ner-location.bin new file mode 100644 index 0000000000..f3788bc1f6 Binary files /dev/null and b/libraries/OpenNLP/en-ner-location.bin differ diff --git a/libraries/OpenNLP/en-ner-person.bin b/libraries/OpenNLP/en-ner-person.bin new file mode 100644 index 0000000000..2f68318203 Binary files /dev/null and b/libraries/OpenNLP/en-ner-person.bin differ diff --git a/libraries/OpenNLP/en-pos-maxent.bin b/libraries/OpenNLP/en-pos-maxent.bin new file mode 100644 index 0000000000..c8cae23c5f Binary files /dev/null and b/libraries/OpenNLP/en-pos-maxent.bin differ diff --git a/libraries/OpenNLP/en-sent.bin b/libraries/OpenNLP/en-sent.bin new file mode 100644 index 0000000000..e89076be5a Binary files /dev/null and b/libraries/OpenNLP/en-sent.bin differ diff --git a/libraries/OpenNLP/en-token.bin b/libraries/OpenNLP/en-token.bin new file mode 100644 index 0000000000..c417277ca7 Binary files /dev/null and b/libraries/OpenNLP/en-token.bin differ diff --git a/libraries/pom.xml b/libraries/pom.xml index f03ba93d27..bc40514b2f 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -308,11 +308,28 @@ jool 0.9.12 + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + io.netty netty-all ${netty.version} + + + org.apache.opennlp + opennlp-tools + 1.8.0 + + 0.7.0 @@ -332,7 +349,7 @@ 2.5 1.2.0 2.8.5 - 1.4.1-rc.3 + 1.4.0 1.24.0 1.1.3-rc.5 1.4.0 @@ -340,4 +357,4 @@ 4.1.10.Final - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/jmh/BenchMark.java b/libraries/src/main/java/com/baeldung/jmh/BenchMark.java new file mode 100644 index 0000000000..bc0c348556 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmh/BenchMark.java @@ -0,0 +1,12 @@ +package com.baeldung.jmh; + +import org.openjdk.jmh.annotations.Benchmark; + +public class BenchMark { + + @Benchmark + public void init() { + + } + +} diff --git a/libraries/src/main/java/com/baeldung/jmh/JmhDemo.java b/libraries/src/main/java/com/baeldung/jmh/JmhDemo.java new file mode 100644 index 0000000000..bcd585e586 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jmh/JmhDemo.java @@ -0,0 +1,14 @@ +package com.baeldung.jmh; + +import java.io.IOException; + +import org.openjdk.jmh.Main; +import org.openjdk.jmh.runner.RunnerException; + +public class JmhDemo { + + public static void main(String[] args) throws RunnerException, IOException { + Main.main(args); + } + +} diff --git a/libraries/src/main/java/com/baeldung/opennlp/OpenNLP.java b/libraries/src/main/java/com/baeldung/opennlp/OpenNLP.java new file mode 100644 index 0000000000..b2fa8e629b --- /dev/null +++ b/libraries/src/main/java/com/baeldung/opennlp/OpenNLP.java @@ -0,0 +1,166 @@ +package com.baeldung.opennlp; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.logging.Logger; + +import opennlp.tools.chunker.ChunkerME; +import opennlp.tools.chunker.ChunkerModel; +import opennlp.tools.cmdline.postag.POSModelLoader; +import opennlp.tools.doccat.DoccatFactory; +import opennlp.tools.doccat.DoccatModel; +import opennlp.tools.doccat.DocumentCategorizerME; +import opennlp.tools.doccat.DocumentSample; +import opennlp.tools.doccat.DocumentSampleStream; +import opennlp.tools.namefind.NameFinderME; +import opennlp.tools.namefind.TokenNameFinderModel; +import opennlp.tools.postag.POSModel; +import opennlp.tools.postag.POSSample; +import opennlp.tools.postag.POSTaggerME; +import opennlp.tools.sentdetect.SentenceDetectorME; +import opennlp.tools.sentdetect.SentenceModel; +import opennlp.tools.tokenize.Tokenizer; +import opennlp.tools.tokenize.TokenizerME; +import opennlp.tools.tokenize.TokenizerModel; +import opennlp.tools.tokenize.WhitespaceTokenizer; +import opennlp.tools.util.InputStreamFactory; +import opennlp.tools.util.InvalidFormatException; +import opennlp.tools.util.ObjectStream; +import opennlp.tools.util.PlainTextByLineStream; +import opennlp.tools.util.Span; +import opennlp.tools.util.TrainingParameters; + +public class OpenNLP { + + private final static Logger LOGGER = Logger.getLogger(OpenNLP.class.getName()); + private final static String text = "To get to the south: Go to the store. Buy a compass. Use the compass. Then walk to the south."; + private final static String sentence[] = new String[] { "James", "Jordan", "live", "in", "Oklahoma", "city", "." }; + + private DoccatModel docCatModel; + + public static void main(String[] args) { + new OpenNLP(); + } + + public OpenNLP() { + try { + sentenceDetector(); + tokenizer(); + nameFinder(); + locationFinder(); + trainDocumentCategorizer(); + documentCategorizer(); + partOfSpeechTagger(); + chunker(); + } catch (InvalidFormatException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void sentenceDetector() throws InvalidFormatException, IOException { + + InputStream is = new FileInputStream("OpenNLP/en-sent.bin"); + SentenceModel model = new SentenceModel(is); + SentenceDetectorME sdetector = new SentenceDetectorME(model); + String sentences[] = sdetector.sentDetect(text); + Arrays.stream(sentences).forEach(LOGGER::info); + is.close(); + } + + public void tokenizer() throws InvalidFormatException, IOException { + InputStream is = new FileInputStream("OpenNLP/en-token.bin"); + TokenizerModel model = new TokenizerModel(is); + Tokenizer tokenizer = new TokenizerME(model); + String tokens[] = tokenizer.tokenize(text); + Arrays.stream(tokens).forEach(LOGGER::info); + is.close(); + } + + public static void nameFinder() throws IOException { + InputStream is = new FileInputStream("OpenNLP/en-ner-person.bin"); + TokenNameFinderModel model = new TokenNameFinderModel(is); + is.close(); + NameFinderME nameFinder = new NameFinderME(model); + Span nameSpans[] = nameFinder.find(sentence); + String[] names = Span.spansToStrings(nameSpans, sentence); + Arrays.stream(names).forEach(LOGGER::info); + } + + public static void locationFinder() throws IOException { + InputStream is = new FileInputStream("OpenNLP/en-ner-location.bin"); + TokenNameFinderModel model = new TokenNameFinderModel(is); + is.close(); + NameFinderME nameFinder = new NameFinderME(model); + Span locationSpans[] = nameFinder.find(sentence); + String[] locations = Span.spansToStrings(locationSpans, sentence); + Arrays.stream(locations).forEach(LOGGER::info); + } + + public void trainDocumentCategorizer() { + + try { + InputStreamFactory isf = new InputStreamFactory() { + public InputStream createInputStream() throws IOException { + return new FileInputStream("OpenNLP/doc-cat.train"); + } + }; + ObjectStream lineStream = new PlainTextByLineStream(isf, "UTF-8"); + ObjectStream sampleStream = new DocumentSampleStream(lineStream); + DoccatFactory docCatFactory = new DoccatFactory(); + docCatModel = DocumentCategorizerME.train("en", sampleStream, TrainingParameters.defaultParams(), docCatFactory); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void documentCategorizer() { + DocumentCategorizerME myCategorizer = new DocumentCategorizerME(docCatModel); + double[] outcomes = myCategorizer.categorize(sentence); + String category = myCategorizer.getBestCategory(outcomes); + + if (category.equalsIgnoreCase("GOOD")) { + LOGGER.info("Document is positive :) "); + } else { + LOGGER.info("Document is negative :( "); + } + } + + public static void partOfSpeechTagger() throws IOException { + try { + POSModel posModel = new POSModelLoader().load(new File("OpenNLP/en-pos-maxent.bin")); + POSTaggerME posTaggerME = new POSTaggerME(posModel); + InputStreamFactory isf = new InputStreamFactory() { + public InputStream createInputStream() throws IOException { + return new FileInputStream("OpenNLP/PartOfSpeechTag.txt"); + } + }; + ObjectStream lineStream = new PlainTextByLineStream(isf, "UTF-8"); + String line; + while ((line = lineStream.read()) != null) { + String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line); + String[] tags = posTaggerME.tag(whitespaceTokenizerLine); + POSSample posSample = new POSSample(whitespaceTokenizerLine, tags); + LOGGER.info(posSample.toString()); + } + lineStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void chunker() throws IOException { + InputStream is = new FileInputStream("OpenNLP/en-chunker.bin"); + ChunkerModel cModel = new ChunkerModel(is); + ChunkerME chunkerME = new ChunkerME(cModel); + String[] taggedSentence = new String[] {"Out", "of", "the", "night", "that", "covers", "me"}; + String pos[] = new String[] { "IN", "IN", "DT", "NN", "WDT", "VBZ", "PRP"}; + String chunks[] = chunkerME.chunk(taggedSentence, pos); + Arrays.stream(chunks).forEach(LOGGER::info); + } + +} diff --git a/libraries/src/main/resources/META-INF/BenchmarkList b/libraries/src/main/resources/META-INF/BenchmarkList new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java b/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java new file mode 100644 index 0000000000..a38791fd61 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/opennlp/OpenNLPTests.java @@ -0,0 +1,158 @@ +package com.baeldung.opennlp; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; + +import opennlp.tools.chunker.ChunkerME; +import opennlp.tools.chunker.ChunkerModel; +import opennlp.tools.cmdline.postag.POSModelLoader; +import opennlp.tools.doccat.DoccatFactory; +import opennlp.tools.doccat.DoccatModel; +import opennlp.tools.doccat.DocumentCategorizerME; +import opennlp.tools.doccat.DocumentSample; +import opennlp.tools.doccat.DocumentSampleStream; +import opennlp.tools.namefind.NameFinderME; +import opennlp.tools.namefind.TokenNameFinderModel; +import opennlp.tools.postag.POSModel; +import opennlp.tools.postag.POSSample; +import opennlp.tools.postag.POSTaggerME; +import opennlp.tools.sentdetect.SentenceDetectorME; +import opennlp.tools.sentdetect.SentenceModel; +import opennlp.tools.tokenize.WhitespaceTokenizer; +import opennlp.tools.util.InputStreamFactory; +import opennlp.tools.util.ObjectStream; +import opennlp.tools.util.PlainTextByLineStream; +import opennlp.tools.util.Span; +import opennlp.tools.util.TrainingParameters; + +public class OpenNLPTests { + + private final static String text = "To get to the south: Go to the store. Buy a compass. Use the compass. Then walk to the south."; + private final static String sentence[] = new String[] { "James", "Jordan", "live", "in", "Oklahoma", "city", "." }; + + @Test + public void givenText_WhenDetectSentences_ThenCountSentences(){ + InputStream is; + SentenceModel model; + try { + is = new FileInputStream("OpenNLP/en-sent.bin"); + model = new SentenceModel(is); + SentenceDetectorME sdetector = new SentenceDetectorME(model); + String sentences[] = sdetector.sentDetect(text); + assertEquals(4, sentences.length); + is.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void givenText_WhenDetectTokens_ThenVerifyNames(){ + InputStream is; + TokenNameFinderModel model; + try { + is = new FileInputStream("OpenNLP/en-ner-person.bin"); + model = new TokenNameFinderModel(is); + is.close(); + NameFinderME nameFinder = new NameFinderME(model); + Span nameSpans[] = nameFinder.find(sentence); + String[] names = Span.spansToStrings(nameSpans, sentence); + assertEquals(1, names.length); + assertEquals("James Jordan", names[0]); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void givenText_WhenDetectTokens_ThenVerifyLocations(){ + InputStream is; + TokenNameFinderModel model; + try { + is = new FileInputStream("OpenNLP/en-ner-location.bin"); + model = new TokenNameFinderModel(is); + is.close(); + NameFinderME nameFinder = new NameFinderME(model); + Span locationSpans[] = nameFinder.find(sentence); + String[] locations = Span.spansToStrings(locationSpans, sentence); + assertEquals(1, locations.length); + assertEquals("Oklahoma", locations[0]); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void givenText_WhenCategorizeDocument_ThenVerifyDocumentContent(){ + DoccatModel docCatModel; + try { + InputStreamFactory isf = new InputStreamFactory() { + public InputStream createInputStream() throws IOException { + return new FileInputStream("OpenNLP/doc-cat.train"); + } + }; + ObjectStream lineStream = new PlainTextByLineStream(isf, "UTF-8"); + ObjectStream sampleStream = new DocumentSampleStream(lineStream); + DoccatFactory docCatFactory = new DoccatFactory(); + docCatModel = DocumentCategorizerME.train("en", sampleStream, TrainingParameters.defaultParams(), docCatFactory); + DocumentCategorizerME myCategorizer = new DocumentCategorizerME(docCatModel); + double[] outcomes = myCategorizer.categorize(sentence); + String category = myCategorizer.getBestCategory(outcomes); + assertEquals("GOOD", category); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void givenText_WhenTagDocument_ThenVerifyTaggedString(){ + try { + POSModel posModel = new POSModelLoader().load(new File("OpenNLP/en-pos-maxent.bin")); + POSTaggerME posTaggerME = new POSTaggerME(posModel); + InputStreamFactory isf = new InputStreamFactory() { + public InputStream createInputStream() throws IOException { + return new FileInputStream("OpenNLP/PartOfSpeechTag.txt"); + } + }; + ObjectStream lineStream = new PlainTextByLineStream(isf, "UTF-8"); + String line; + while ((line = lineStream.read()) != null) { + String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line); + String[] tags = posTaggerME.tag(whitespaceTokenizerLine); + POSSample posSample = new POSSample(whitespaceTokenizerLine, tags); + assertEquals("Out_IN of_IN the_DT night_NN that_WDT covers_VBZ me_PRP", posSample.toString()); + } + lineStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void givenText_WhenChunked_ThenCountChunks(){ + try { + InputStream is = new FileInputStream("OpenNLP/en-chunker.bin"); + ChunkerModel cModel = new ChunkerModel(is); + ChunkerME chunkerME = new ChunkerME(cModel); + String pos[] = new String[] { "NNP", "NNP", "NNP", "POS", "NNP", "NN", "VBD"}; + String chunks[] = chunkerME.chunk(sentence, pos); + assertEquals(7, chunks.length); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/spring-aop/.gitignore b/spring-aop/.gitignore new file mode 100644 index 0000000000..62c893550a --- /dev/null +++ b/spring-aop/.gitignore @@ -0,0 +1 @@ +.idea/ \ No newline at end of file diff --git a/spring-aop/src/main/java/com/baeldung/beaninjection/BeanInjectionApplication.java b/spring-aop/src/main/java/com/baeldung/beaninjection/BeanInjectionApplication.java new file mode 100644 index 0000000000..c8e228c6f2 --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/beaninjection/BeanInjectionApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.beaninjection; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BeanInjectionApplication { + + public static void main(String[] args) { + SpringApplication.run(BeanInjectionApplication.class, args); + } +} diff --git a/spring-aop/src/main/java/com/baeldung/beaninjection/config/StorageProperties.java b/spring-aop/src/main/java/com/baeldung/beaninjection/config/StorageProperties.java new file mode 100644 index 0000000000..18f7d36378 --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/beaninjection/config/StorageProperties.java @@ -0,0 +1,30 @@ +package com.baeldung.beaninjection.config; + +import org.apache.log4j.Logger; +import org.springframework.context.annotation.Configuration; + +/** + * Created by smatt on 12/05/2017. + */ +@Configuration +public class StorageProperties { + /** + * Folder location for storing files + */ + + Logger logger = Logger.getLogger(StorageProperties.class); + + private String location = "upload-dir"; + + public StorageProperties() {} + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + +} diff --git a/spring-aop/src/main/java/com/baeldung/beaninjection/service/FileSystemStorageService.java b/spring-aop/src/main/java/com/baeldung/beaninjection/service/FileSystemStorageService.java new file mode 100644 index 0000000000..d2530d5a2d --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/beaninjection/service/FileSystemStorageService.java @@ -0,0 +1,29 @@ +package com.baeldung.beaninjection.service; + +import com.baeldung.beaninjection.config.StorageProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Created by smatt on 12/05/2017. + */ +@Service +public class FileSystemStorageService { + + StorageProperties storageProperties; + + @Autowired + public FileSystemStorageService(StorageProperties storageProperties) { + this.storageProperties = storageProperties; + } + + //this is for test purpose + public StorageProperties getStorageProperties() { + return storageProperties; + } + + @Override + public String toString() { + return "FileSystemStorageService: Storage Location = " + storageProperties.getLocation(); + } +} diff --git a/spring-aop/src/main/java/com/baeldung/beaninjection/service/NetworkStorageService.java b/spring-aop/src/main/java/com/baeldung/beaninjection/service/NetworkStorageService.java new file mode 100644 index 0000000000..0720ba153e --- /dev/null +++ b/spring-aop/src/main/java/com/baeldung/beaninjection/service/NetworkStorageService.java @@ -0,0 +1,31 @@ +package com.baeldung.beaninjection.service; + +import com.baeldung.beaninjection.config.StorageProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Created by smatt on 12/05/2017. + */ +@Service +public class NetworkStorageService { + + StorageProperties storageProperties; + + public NetworkStorageService() {} + + @Autowired + public void setStorageProperties(StorageProperties storageProperties) { + this.storageProperties = storageProperties; + } + + public StorageProperties getStorageProperties() { + return storageProperties; + } + + @Override + public String toString() { + return "NetworkStorageService: Storage Location = " + storageProperties.getLocation(); + } + +} diff --git a/spring-aop/src/test/java/com/baeldung/beaninjection/BeanInjectionApplicationTests.java b/spring-aop/src/test/java/com/baeldung/beaninjection/BeanInjectionApplicationTests.java new file mode 100644 index 0000000000..d508975481 --- /dev/null +++ b/spring-aop/src/test/java/com/baeldung/beaninjection/BeanInjectionApplicationTests.java @@ -0,0 +1,17 @@ +package com.baeldung.beaninjection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BeanInjectionApplicationTests { + + @Test + public void contextLoads() { + } + + +} diff --git a/spring-aop/src/test/java/com/baeldung/beaninjection/BeanInjectionUnitTests.java b/spring-aop/src/test/java/com/baeldung/beaninjection/BeanInjectionUnitTests.java new file mode 100644 index 0000000000..fe1d224bc4 --- /dev/null +++ b/spring-aop/src/test/java/com/baeldung/beaninjection/BeanInjectionUnitTests.java @@ -0,0 +1,47 @@ +package com.baeldung.beaninjection; + +import com.baeldung.beaninjection.service.FileSystemStorageService; +import com.baeldung.beaninjection.service.NetworkStorageService; +import org.apache.log4j.Logger; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * Created by smatt on 13/05/2017. + */ +@RunWith(SpringRunner.class) +@SpringBootTest +public class BeanInjectionUnitTests { + + @Autowired + NetworkStorageService networkStorageService; + + @Autowired + FileSystemStorageService fileSystemStorageService; + + Logger logger = Logger.getLogger(BeanInjectionApplicationTests.class); + + + @Test + public void contextLoads() { + } + + @Test + public void givenAutowiredOnClassConstructor_whenInstantiatingAndCallingGetter_thenDependencyShouldResolve() { + Assert.assertNotNull("FileSystemStorageService not autowired in test class", fileSystemStorageService); + Assert.assertNotNull("StorageProperties not autowired in FileSystemStorageService", fileSystemStorageService.getStorageProperties()); + logger.info(fileSystemStorageService.toString()); + } + + @Test + public void givenAutowiredOnClassSetter_whenInstantiatingAndCallingGetter_thenDependencyShouldResolve() { + Assert.assertNotNull("NetworkStorageService not autowired in test class", networkStorageService); + Assert.assertNotNull("StorageProperties not autowired in NetworkStorageService", networkStorageService.getStorageProperties()); + logger.info(networkStorageService.toString()); + } + +} diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 691137e495..2a1de00039 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -45,7 +45,13 @@ spring-boot-starter-tomcat provided - + + + org.springframework.boot + spring-boot-starter-test + test + + org.apache.tomcat.embed tomcat-embed-core diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java new file mode 100644 index 0000000000..fcce2725e5 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java @@ -0,0 +1,19 @@ +package com.baeldung.displayallbeans; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + + String[] allBeanNames = applicationContext.getBeanDefinitionNames(); + for(String beanName : allBeanNames) { + System.out.println(beanName); + } + } +} diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/SpringConfig.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/SpringConfig.java new file mode 100644 index 0000000000..1d4a97f843 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/SpringConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.displayallbeans; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import com.baeldung.displayallbeans.model.Person; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.displayallbeans") +public class SpringConfig { + @Bean + public Person person() { + Person person = new Person(); + person.setName("Jon Doe"); + return person; + } +} \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/PersonController.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/PersonController.java new file mode 100644 index 0000000000..93fc278b1c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/PersonController.java @@ -0,0 +1,19 @@ +package com.baeldung.displayallbeans.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.displayallbeans.model.Person; + +@Controller +public class PersonController { + @Autowired + Person person; + + @RequestMapping("/getPerson") + public @ResponseBody Person getPerson() { + return person; + } +} \ No newline at end of file diff --git a/spring-boot/src/main/java/com/baeldung/displayallbeans/model/Person.java b/spring-boot/src/main/java/com/baeldung/displayallbeans/model/Person.java new file mode 100644 index 0000000000..dde471aedb --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/displayallbeans/model/Person.java @@ -0,0 +1,13 @@ +package com.baeldung.displayallbeans.model; + +public class Person { + String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} \ No newline at end of file diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 444f68d50a..458b4e0d46 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -45,4 +45,7 @@ servlet.mapping=/dispatcherExampleURL #banner.image.margin= //TODO #banner.image.invert= //TODO -contactInfoType=email \ No newline at end of file +contactInfoType=email + +endpoints.beans.id=springbeans +endpoints.beans.sensitive=false diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java new file mode 100644 index 0000000000..84d5669aef --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -0,0 +1,84 @@ +package com.baeldung.displayallbeans; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.displayallbeans.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@TestPropertySource(properties = {"management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false"}) +public class DisplayBeanIntegrationTest { + + @LocalServerPort + private int port; + + @Value("${local.management.port}") + private int mgt; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Autowired + private WebApplicationContext context; + + @Test + public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { + @SuppressWarnings("rawtypes") + ResponseEntity entity = this.testRestTemplate.getForEntity( + "http://localhost:" + this.port + "/getPerson", Map.class); + + then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + } + + @Test + public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { + @SuppressWarnings("rawtypes") + ResponseEntity entity = this.testRestTemplate.getForEntity( + "http://localhost:" + this.mgt + "/springbeans", List.class); + + then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + } + + @Test + public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception { + @SuppressWarnings("rawtypes") + ResponseEntity entity = this.testRestTemplate.getForEntity( + "http://localhost:" + this.mgt + "/springbeans", List.class); + + List> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans"); + List beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList()); + + assertThat( beanNamesList, hasItem("personController")); + assertThat( beanNamesList, hasItem("person")); + } + + @Test + public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception { + String[] beanNames = context.getBeanDefinitionNames(); + + List beanNamesList = Arrays.asList(beanNames); + assertTrue(beanNamesList.contains("personController")); + assertTrue(beanNamesList.contains("person")); + } +} diff --git a/testing/pom.xml b/testing/pom.xml index 8c6898ac67..aa10392aa8 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -70,6 +70,12 @@ ${jUnitParams.version} test + + org.jgotesting + jgotesting + ${jgotesting.version} + test + @@ -137,5 +143,6 @@ 3.6.1 0.32 1.1.0 + 0.12 diff --git a/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java b/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java new file mode 100644 index 0000000000..650fb3e5c5 --- /dev/null +++ b/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java @@ -0,0 +1,93 @@ +package com.baeldung.testing.jgotesting; + +import java.io.File; +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.Matchers.is; +import org.jgotesting.rule.JGoTestRule; +import static org.jgotesting.Assert.*; // same methods as org.junit.Assert.* +import static org.jgotesting.Check.*; // ditto, with different names +import static org.jgotesting.Testing.*; +import org.jgotesting.Checker; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; + +public class JGoTestingUnitTest { + @Rule + public final JGoTestRule test = new JGoTestRule(); + + @Test + public void whenComparingIntegers_thenEqual() { + int anInt = 10; + + assertEquals(anInt, 10); + checkEquals(anInt, 10); + } + + @Ignore + @Test + public void whenComparingNumbers_thenLoggedMessage() { + log("There was something wrong when comparing numbers"); + + int anInt = 10; + int anotherInt = 10; + + checkEquals(anInt, 10); + checkTrue("First number should be bigger", 10 > anotherInt); + checkSame(anInt, anotherInt); + } + + @Ignore + @Test + public void whenComparingNumbers_thenFormattedMessage() { + int anInt = 10; + int anotherInt = 10; + + logf("There was something wrong when comparing numbers %d and %d", anInt, anotherInt); + + checkEquals(anInt, 10); + checkTrue("First number should be bigger", 10 > anotherInt); + checkSame(anInt, anotherInt); + } + + @Test + public void whenComparingStrings_thenMultipleAssertions() { + String aString = "This is a string"; + String anotherString = "This Is A String"; + + test.check(aString, equalToIgnoringCase(anotherString)) + .check(aString.length() == 16) + .check(aString.startsWith("This")); + } + + @Ignore + @Test + public void whenComparingStrings_thenMultipleFailingAssertions() { + String aString = "the test string"; + String anotherString = "The Test String"; + + checkEquals("Strings are not equal!", aString, anotherString); + checkTrue("String is longer than one character", aString.length() == 1); + checkSame("Strings are not the same", aString, anotherString); + } + + @Ignore + @Test + public void givenFile_whenDoesnotExists_thenTerminated() throws Exception { + File aFile = new File("a_dummy_file.txt"); + terminateIf(aFile.exists(), is(false)); + + // This doesn't get executed + checkEquals(aFile.getName(), "a_dummy_file.txt"); + } + + @Test + public void givenChecker_whenComparingStrings_thenEqual() throws Exception { + Checker aChecker = s -> s.matches("\\d+"); + + String aString = "1235"; + test.check(aString, aChecker); + } + +} +