Merge remote-tracking branch 'origin/master'

This commit is contained in:
Grzegorz Piwowarek 2017-06-10 11:51:40 +02:00
commit c9cd941fc7
48 changed files with 1776 additions and 454 deletions

View File

@ -5,7 +5,6 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Stack; import java.util.Stack;
import java.util.stream.Collectors;
public class HillClimbing { public class HillClimbing {
public static void main(String[] args) { 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<Stack<String>> stackList = state.getState(); List<Stack<String>> stackList = state.getState();
System.out.println("----------------"); System.out.println("----------------");
stackList.forEach(stack -> { stackList.forEach(stack -> {
@ -33,8 +32,8 @@ public class HillClimbing {
}); });
} }
public Stack<String> getStackWithValues(String[] blocks) { private Stack<String> getStackWithValues(String[] blocks) {
Stack<String> stack = new Stack<String>(); Stack<String> stack = new Stack<>();
for (String block : blocks) for (String block : blocks)
stack.push(block); stack.push(block);
return stack; return stack;
@ -42,14 +41,9 @@ public class HillClimbing {
/** /**
* This method prepares path from init state to goal state * This method prepares path from init state to goal state
*
* @param initStateStack
* @param goalStateStack
* @return
* @throws Exception
*/ */
public List<State> getRouteWithHillClimbing(Stack<String> initStateStack, Stack<String> goalStateStack) throws Exception { public List<State> getRouteWithHillClimbing(Stack<String> initStateStack, Stack<String> goalStateStack) throws Exception {
List<Stack<String>> initStateStackList = new ArrayList<Stack<String>>(); List<Stack<String>> initStateStackList = new ArrayList<>();
initStateStackList.add(initStateStack); initStateStackList.add(initStateStack);
int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack); int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
State initState = new State(initStateStackList, initStateHeuristics); State initState = new State(initStateStackList, initStateHeuristics);
@ -71,27 +65,32 @@ public class HillClimbing {
} }
} }
if (noStateFound)
throw new Exception("No path found");
return resultPath; return resultPath;
} }
/** /**
* This method finds new state from current state based on goal and * This method finds new state from current state based on goal and
* heuristics * heuristics
*
* @param currentState
* @param goalStateStack
* @return a next state
*/ */
public State findNextState(State currentState, Stack<String> goalStateStack) { public State findNextState(State currentState, Stack<String> goalStateStack) {
List<Stack<String>> listOfStacks = currentState.getState(); List<Stack<String>> listOfStacks = currentState.getState();
int currentStateHeuristics = currentState.getHeuristics(); int currentStateHeuristics = currentState.getHeuristics();
Optional<State> newState = listOfStacks.stream() return listOfStacks.stream()
.map(stack -> { .map(stack -> {
State tempState = null; return applyOperationsOnState(listOfStacks, stack, currentStateHeuristics, goalStateStack);
List<Stack<String>> tempStackList = new ArrayList<Stack<String>>(listOfStacks); })
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
}
/**
* This method applies operations on the current state to get a new state
*/
public State applyOperationsOnState(List<Stack<String>> listOfStacks, Stack<String> stack, int currentStateHeuristics, Stack<String> goalStateStack) {
State tempState;
List<Stack<String>> tempStackList = new ArrayList<>(listOfStacks);
String block = stack.pop(); String block = stack.pop();
if (stack.size() == 0) if (stack.size() == 0)
tempStackList.remove(stack); tempStackList.remove(stack);
@ -102,26 +101,15 @@ public class HillClimbing {
if (tempState == null) if (tempState == null)
stack.push(block); stack.push(block);
return tempState; return tempState;
})
.filter(Objects::nonNull)
.findFirst();
return newState.orElse(null);
} }
/** /**
* Operation to be applied on a state in order to find new states. This * Operation to be applied on a state in order to find new states. This
* operation pushes an element into a new stack * operation pushes an element into a new stack
*
* @param currentStackList
* @param block
* @param currentStateHeuristics
* @param goalStateStack
* @return a new state
*/ */
private State pushElementToNewStack(List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) { private State pushElementToNewStack(List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
State newState = null; State newState = null;
Stack<String> newStack = new Stack<String>(); Stack<String> newStack = new Stack<>();
newStack.push(block); newStack.push(block);
currentStackList.add(newStack); currentStackList.add(newStack);
@ -138,26 +126,13 @@ public class HillClimbing {
* Operation to be applied on a state in order to find new states. This * 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 * operation pushes an element into one of the other stacks to explore new
* states * states
*
* @param stack
* @param currentStackList
* @param block
* @param currentStateHeuristics
* @param goalStateStack
* @return a new state
*/ */
private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) { private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
Optional<State> newState = currentStackList.stream() Optional<State> newState = currentStackList.stream()
.filter(stack -> stack != currentStack) .filter(stack -> stack != currentStack)
.map(stack -> { .map(stack -> {
stack.push(block); return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack);
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
if (newStateHeuristics > currentStateHeuristics) {
return new State(currentStackList, newStateHeuristics);
}
stack.pop();
return null;
}) })
.filter(Objects::nonNull) .filter(Objects::nonNull)
.findFirst(); .findFirst();
@ -165,19 +140,37 @@ public class HillClimbing {
return newState.orElse(null); 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<Stack<String>> currentStackList, int currentStateHeuristics, Stack<String> 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 * This method returns heuristics value for given state with respect to goal
* state * state
*
* @param currentState
* @param goalStateStack
* @return
*/ */
public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) { public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) {
Integer heuristicValue;
Integer heuristicValue = 0;
heuristicValue = currentState.stream() heuristicValue = currentState.stream()
.mapToInt(stack -> { .mapToInt(stack -> {
return getHeuristicsValueForStack(stack, currentState, goalStateStack);
})
.sum();
return heuristicValue;
}
/**
* This method returns heuristics value for a particular stack
*/
public int getHeuristicsValueForStack(Stack<String> stack, List<Stack<String>> currentState, Stack<String> goalStateStack) {
int stackHeuristics = 0; int stackHeuristics = 0;
boolean isPositioneCorrect = true; boolean isPositioneCorrect = true;
int goalStartIndex = 0; int goalStartIndex = 0;
@ -191,9 +184,6 @@ public class HillClimbing {
goalStartIndex++; goalStartIndex++;
} }
return stackHeuristics; return stackHeuristics;
})
.sum();
return heuristicValue;
} }
} }

View File

@ -5,26 +5,23 @@ import java.util.List;
import java.util.Stack; import java.util.Stack;
public class State { public class State {
List<Stack<String>> state; private List<Stack<String>> state;
int heuristics; private int heuristics;
public State() {
}
public State(List<Stack<String>> state) { public State(List<Stack<String>> state) {
this.state = state; this.state = state;
} }
public State(List<Stack<String>> state, int heuristics) { State(List<Stack<String>> state, int heuristics) {
this.state = state; this.state = state;
this.heuristics = heuristics; this.heuristics = heuristics;
} }
public State(State state) { State(State state) {
if (state != null) { if (state != null) {
this.state = new ArrayList<Stack<String>>(); this.state = new ArrayList<>();
for (Stack s : state.getState()) { for (Stack s : state.getState()) {
Stack s1 = new Stack(); Stack s1;
s1 = (Stack) s.clone(); s1 = (Stack) s.clone();
this.state.add(s1); this.state.add(s1);
} }
@ -36,10 +33,6 @@ public class State {
return state; return state;
} }
public void setState(List<Stack<String>> state) {
this.state = state;
}
public int getHeuristics() { public int getHeuristics() {
return heuristics; return heuristics;
} }

View File

@ -14,17 +14,17 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class HillClimbingAlgorithmTest { public class HillClimbingAlgorithmTest {
Stack<String> initStack; private Stack<String> initStack;
Stack<String> goalStack; private Stack<String> goalStack;
@Before @Before
public void initStacks() { public void initStacks() {
String blockArr[] = { "B", "C", "D", "A" }; String blockArr[] = { "B", "C", "D", "A" };
String goalBlockArr[] = { "A", "B", "C", "D" }; String goalBlockArr[] = { "A", "B", "C", "D" };
initStack = new Stack<String>(); initStack = new Stack<>();
for (String block : blockArr) for (String block : blockArr)
initStack.push(block); initStack.push(block);
goalStack = new Stack<String>(); goalStack = new Stack<>();
for (String block : goalBlockArr) for (String block : goalBlockArr)
goalStack.push(block); goalStack.push(block);
} }
@ -48,7 +48,7 @@ public class HillClimbingAlgorithmTest {
@Test @Test
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() { public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
HillClimbing hillClimbing = new HillClimbing(); HillClimbing hillClimbing = new HillClimbing();
List<Stack<String>> initList = new ArrayList<Stack<String>>(); List<Stack<String>> initList = new ArrayList<>();
initList.add(initStack); initList.add(initStack);
State currentState = new State(initList); State currentState = new State(initList);
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack)); currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));

View File

@ -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<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) {
List<Date> datesInRange = new ArrayList<Date>();
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<LocalDate> 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<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate).collect(Collectors.toList());
}
}

View File

@ -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<Date> 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<LocalDate> 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<LocalDate> dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate);
assertEquals(dates.size(), 2);
assertEquals(dates.get(0), LocalDate.now());
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
}
}

View File

@ -17,9 +17,10 @@
# Files generated by integration tests # Files generated by integration tests
*.txt *.txt
backup-pom.xml
/bin/ /bin/
/temp /temp
#IntelliJ specific #IntelliJ specific
.idea .idea/
*.iml *.iml

View File

@ -401,5 +401,4 @@
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -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<? extends Annotation> annotationType() {
return DynamicGreeter.class;
}
@Override
public String greet() {
return greet;
}
}

View File

@ -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 "";
}

View File

@ -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<? extends Annotation> 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<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
map.put(targetAnnotation, targetValue);
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static void alterAnnotationValueJDK7(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
try {
Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
annotations.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(targetClass);
System.out.println(map);
map.put(targetAnnotation, targetValue);
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.java.reflection;
@Greeter(greet="Good morning")
public class Greetings {
}

View File

@ -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<String> iterateUsingEntrySet(Map<String, Integer> map) {
List<String> mapKeyValueList = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
mapKeyValueList.add(entry.getKey() + ":" + entry.getValue());
}
return mapKeyValueList;
}
public List<String> iterateUsingLambda(Map<String, Integer> map) {
List<String> mapKeyValueList = new ArrayList<>();
map.forEach((k, v) -> mapKeyValueList.add(k + ":" + v));
return mapKeyValueList;
}
public List<String> iterateUsingIteratorAndEntry(Map<String, Integer> map) {
ArrayList<String> mapKeyValueList = new ArrayList<>();
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> pair = iterator.next();
mapKeyValueList.add(pair.getKey() + ":" + pair.getValue());
}
return mapKeyValueList;
}
public List<String> iterateUsingKeySetAndForeach(Map<String, Integer> map) {
List<String> mapKeyValueList = new ArrayList<>();
for (String key : map.keySet()) {
mapKeyValueList.add(key + ":" + map.get(key));
}
return mapKeyValueList;
}
public List<String> iterateUsingStreamAPI(Map<String, Integer> map) {
ArrayList<String> mapKeyValueList = new ArrayList<>();
map.entrySet().stream().forEach(e -> mapKeyValueList.add(e.getKey() + ":" + e.getValue()));
return mapKeyValueList;
}
public ArrayList<String> iterateKeys(Map<String, Integer> map) {
ArrayList<String> mapKeyList = new ArrayList<>();
for (String key : map.keySet()) {
mapKeyList.add(key);
}
return mapKeyList;
}
}

View File

@ -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<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
List<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
List<String> nullProps = propDescList.stream()
.filter(nulls(customer))
.map(PropertyDescriptor::getName)
.collect(Collectors.toList());
return nullProps;
}
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
Predicate<PropertyDescriptor> 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;
}
}

View File

@ -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;
}
}

View File

@ -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<Character, Integer> 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();
}
}

View File

@ -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<String, Integer> testMap = new HashMap<String, Integer>();
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<String> 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<String> 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<String> 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<String> 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<String> 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<String> list = mapIteration.iterateKeys(testMap);
assertTrue((list.contains("One")) && (list.contains("Two")) && (list.contains("Three")));
}
}

View File

@ -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<String> result = BaeldungReflectionUtils.getNullPropertiesList(customer);
List<String> expectedFieldNames = Arrays.asList("emailId", "phoneNumber");
Assert.assertTrue(result.size() == expectedFieldNames.size());
Assert.assertTrue(result.containsAll(expectedFieldNames));
}
}

View File

@ -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<Character> characterStream = testString.chars().mapToObj(c -> (char) c);
Stream<Character> characterStream1 = testString.codePoints().mapToObj(c -> (char) c);
assertNotNull("IntStream returned by chars() did not map to Stream<Character>", characterStream);
assertNotNull("IntStream returned by codePoints() did not map to Stream<Character>", characterStream1);
}
}

View File

@ -0,0 +1 @@
Out of the night that covers me

View File

@ -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 /

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -308,11 +308,28 @@
<artifactId>jool</artifactId> <artifactId>jool</artifactId>
<version>0.9.12</version> <version>0.9.12</version>
</dependency> </dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-all</artifactId> <artifactId>netty-all</artifactId>
<version>${netty.version}</version> <version>${netty.version}</version>
</dependency> </dependency>
<!-- OpenNLP -->
<dependency>
<groupId>org.apache.opennlp</groupId>
<artifactId>opennlp-tools</artifactId>
<version>1.8.0</version>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<multiverse.version>0.7.0</multiverse.version> <multiverse.version>0.7.0</multiverse.version>
@ -332,7 +349,7 @@
<commons.io.version>2.5</commons.io.version> <commons.io.version>2.5</commons.io.version>
<flink.version>1.2.0</flink.version> <flink.version>1.2.0</flink.version>
<jackson.version>2.8.5</jackson.version> <jackson.version>2.8.5</jackson.version>
<serenity.version>1.4.1-rc.3</serenity.version> <serenity.version>1.4.0</serenity.version>
<serenity.jbehave.version>1.24.0</serenity.jbehave.version> <serenity.jbehave.version>1.24.0</serenity.jbehave.version>
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version> <serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
<serenity.plugin.version>1.4.0</serenity.plugin.version> <serenity.plugin.version>1.4.0</serenity.plugin.version>

View File

@ -0,0 +1,12 @@
package com.baeldung.jmh;
import org.openjdk.jmh.annotations.Benchmark;
public class BenchMark {
@Benchmark
public void init() {
}
}

View File

@ -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);
}
}

View File

@ -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<String> lineStream = new PlainTextByLineStream(isf, "UTF-8");
ObjectStream<DocumentSample> 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<String> 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);
}
}

View File

@ -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<String> lineStream = new PlainTextByLineStream(isf, "UTF-8");
ObjectStream<DocumentSample> 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<String> 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();
}
}
}

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

@ -0,0 +1 @@
.idea/

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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() {
}
}

View File

@ -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());
}
}

View File

@ -46,6 +46,12 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.tomcat.embed</groupId> <groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId> <artifactId>tomcat-embed-core</artifactId>

View File

@ -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);
}
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -46,3 +46,6 @@ servlet.mapping=/dispatcherExampleURL
#banner.image.invert= //TODO #banner.image.invert= //TODO
contactInfoType=email contactInfoType=email
endpoints.beans.id=springbeans
endpoints.beans.sensitive=false

View File

@ -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<Map> 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<List> 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<List> entity = this.testRestTemplate.getForEntity(
"http://localhost:" + this.mgt + "/springbeans", List.class);
List<Map<String, Object>> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans");
List<String> 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<String> beanNamesList = Arrays.asList(beanNames);
assertTrue(beanNamesList.contains("personController"));
assertTrue(beanNamesList.contains("person"));
}
}

View File

@ -70,6 +70,12 @@
<version>${jUnitParams.version}</version> <version>${jUnitParams.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.jgotesting</groupId>
<artifactId>jgotesting</artifactId>
<version>${jgotesting.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
@ -137,5 +143,6 @@
<assertj-core.version>3.6.1</assertj-core.version> <assertj-core.version>3.6.1</assertj-core.version>
<truth.version>0.32</truth.version> <truth.version>0.32</truth.version>
<jUnitParams.version>1.1.0</jUnitParams.version> <jUnitParams.version>1.1.0</jUnitParams.version>
<jgotesting.version>0.12</jgotesting.version>
</properties> </properties>
</project> </project>

View File

@ -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<String> aChecker = s -> s.matches("\\d+");
String aString = "1235";
test.check(aString, aChecker);
}
}