Merge remote-tracking branch 'origin/master'

This commit is contained in:
Slavisa Baeldung 2016-09-28 16:29:28 +02:00
commit a9dff7f259
28 changed files with 511 additions and 102 deletions

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>annotations</artifactId>
<relativePath>../</relativePath>
</parent>
<artifactId>annotation-processing</artifactId>
<properties>
<auto-service.version>1.0-rc2</auto-service.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>${auto-service.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,132 @@
package com.baeldung.annotation.processor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ExecutableType;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import com.google.auto.service.AutoService;
@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@AutoService(Processor.class)
public class BuilderProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
.collect(Collectors.partitioningBy(element ->
((ExecutableType) element.asType()).getParameterTypes().size() == 1
&& element.getSimpleName().toString().startsWith("set")));
List<Element> setters = annotatedMethods.get(true);
List<Element> otherMethods = annotatedMethods.get(false);
otherMethods.forEach(element ->
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"@BuilderProperty must be applied to a setXxx method with a single argument", element));
if (setters.isEmpty()) {
continue;
}
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
setter -> setter.getSimpleName().toString(),
setter -> ((ExecutableType) setter.asType())
.getParameterTypes().get(0).toString()
));
try {
writeBuilderFile(className, setterMap);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
private void writeBuilderFile(String className, Map<String, String> setterMap) throws IOException {
String packageName = null;
int lastDot = className.lastIndexOf('.');
if (lastDot > 0) {
packageName = className.substring(0, lastDot);
}
String simpleClassName = className.substring(lastDot + 1);
String builderClassName = className + "Builder";
String builderSimpleClassName = builderClassName.substring(lastDot + 1);
JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName);
try (PrintWriter out = new PrintWriter(builderFile.openWriter())) {
if (packageName != null) {
out.print("package ");
out.print(packageName);
out.println(";");
out.println();
}
out.print("public class ");
out.print(builderSimpleClassName);
out.println(" {");
out.println();
out.print(" private ");
out.print(simpleClassName);
out.print(" object = new ");
out.print(simpleClassName);
out.println("();");
out.println();
out.print(" public ");
out.print(simpleClassName);
out.println(" build() {");
out.println(" return object;");
out.println(" }");
out.println();
setterMap.entrySet().forEach(setter -> {
String methodName = setter.getKey();
String argumentType = setter.getValue();
out.print(" public ");
out.print(builderSimpleClassName);
out.print(" ");
out.print(methodName);
out.print("(");
out.print(argumentType);
out.println(" value) {");
out.print(" object.");
out.print(methodName);
out.println("(value);");
out.println(" return this;");
out.println(" }");
out.println();
});
out.println("}");
}
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.annotation.processor;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface BuilderProperty {
}

View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>annotations</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<artifactId>annotation-user</artifactId>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>annotation-processing</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,29 @@
package com.baeldung.annotation;
import com.baeldung.annotation.processor.BuilderProperty;
public class Person {
private int age;
private String name;
public int getAge() {
return age;
}
@BuilderProperty
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
@BuilderProperty
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.annotation;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PersonBuilderTest {
@Test
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
Person person = new PersonBuilder()
.setAge(25)
.setName("John")
.build();
assertEquals(25, person.getAge());
assertEquals("John", person.getName());
}
}

20
annotations/pom.xml Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>annotations</artifactId>
<packaging>pom</packaging>
<modules>
<module>annotation-processing</module>
<module>annotation-user</module>
</modules>
</project>

View File

@ -11,4 +11,14 @@
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) - [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Guide to Java 8s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture)
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams)
- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)

View File

@ -1,9 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>core-java8</artifactId> <artifactId>core-java8</artifactId>
<version>0.1-SNAPSHOT</version>
<name>core-java8</name> <name>core-java8</name>
@ -111,6 +112,9 @@
</build> </build>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version> <org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.0.13</logback.version> <logback.version>1.0.13</logback.version>

View File

@ -0,0 +1,47 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
public class CurrentDateTimeTest {
@Test
public void shouldReturnCurrentDate() {
final LocalDate now = LocalDate.now();
final Calendar calendar = GregorianCalendar.getInstance();
assertEquals("10-10-2010".length(), now.toString().length());
assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH));
assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1);
assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR));
}
@Test
public void shouldReturnCurrentTime() {
final LocalTime now = LocalTime.now();
final Calendar calendar = GregorianCalendar.getInstance();
assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY));
assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR));
assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE));
}
@Test
public void shouldReturnCurrentTimestamp() {
final Instant now = Instant.now();
final Calendar calendar = GregorianCalendar.getInstance();
assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond());
}
}

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat.

View File

@ -60,12 +60,8 @@
<configuration> <configuration>
<source>1.9</source> <source>1.9</source>
<target>1.9</target> <target>1.9</target>
<verbose>true</verbose> <verbose>true</verbose>
<!-- <executable>C:\develop\jdks\jdk-9_ea122\bin\javac</executable>
<compilerVersion>1.9</compilerVersion> -->
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
@ -85,12 +81,7 @@
<!-- maven plugins --> <!-- maven plugins -->
<!-- <maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version> -->
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- testing --> <!-- testing -->

View File

@ -42,6 +42,19 @@ public class Java9OptionalsStreamTest {
assertEquals("bar", filteredList.get(1)); assertEquals("bar", filteredList.get(1));
} }
@Test
public void filterOutPresentOptionalsWithFlatMap2() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test @Test
public void filterOutPresentOptionalsWithJava9() { public void filterOutPresentOptionalsWithJava9() {
assertEquals(4, listOfOptionals.size()); assertEquals(4, listOfOptionals.size());

View File

@ -1,6 +1,5 @@
package com.baeldung.java9; package com.baeldung.java9;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;

View File

@ -0,0 +1,21 @@
package com.baeldung.java9;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class OptionalToStreamTest {
@Test
public void testOptionalToStream() {
Optional<String> op = Optional.ofNullable("String value");
Stream<String> strOptionalStream = op.stream();
Stream<String> filteredStream = strOptionalStream.filter((str) -> {
return str != null && str.startsWith("String");
});
assertEquals(1, filteredStream.count());
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.java9;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SetExamplesTest {
@Test
public void testUnmutableSet() {
Set<String> strKeySet = Set.of("key1", "key2", "key3");
try {
strKeySet.add("newKey");
} catch (UnsupportedOperationException uoe) {
}
assertEquals(strKeySet.size(), 3);
}
@Test
public void testArrayToSet() {
Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
Set<Integer> intSet = Set.of(intArray);
assertEquals(intSet.size(), intArray.length);
}
}

View File

@ -0,0 +1,65 @@
package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ComplexClass {
private List<?> genericList;
private Set<Integer> integerSet;
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
super();
this.genericList = genericArrayList;
this.integerSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericList == null) {
if (other.genericList != null)
return false;
} else if (!genericList.equals(other.genericList))
return false;
if (integerSet == null) {
if (other.integerSet != null)
return false;
} else if (!integerSet.equals(other.integerSet))
return false;
return true;
}
protected List<?> getGenericList() {
return genericList;
}
protected void setGenericArrayList(List<?> genericList) {
this.genericList = genericList;
}
protected Set<Integer> getIntegerSet() {
return integerSet;
}
protected void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
}

View File

@ -11,13 +11,11 @@ public class Rectangle extends Shape {
@Override @Override
public double area() { public double area() {
// A = w * l
return width * length; return width * length;
} }
@Override @Override
public double perimeter() { public double perimeter() {
// P = 2(w + l)
return 2 * (width + length); return 2 * (width + length);
} }

View File

@ -22,11 +22,10 @@ public class ComplexClassTest {
strArrayListD.add("pqr"); strArrayListD.add("pqr");
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67)); ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject)); Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
} }

View File

@ -12,11 +12,10 @@ public class PrimitiveClassTest {
PrimitiveClass bObject = new PrimitiveClass(false, 2); PrimitiveClass bObject = new PrimitiveClass(false, 2);
PrimitiveClass dObject = new PrimitiveClass(true, 2); PrimitiveClass dObject = new PrimitiveClass(true, 2);
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject)); Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
} }

View File

@ -15,11 +15,10 @@ public class SquareClassTest {
Square dObject = new Square(20, Color.BLUE); Square dObject = new Square(20, Color.BLUE);
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject)); Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode()); Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject)); Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode()); Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
} }

View File

@ -1,63 +0,0 @@
package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
public class ComplexClass {
private ArrayList<?> genericArrayList;
private HashSet<Integer> integerHashSet;
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
super();
this.genericArrayList = genericArrayList;
this.integerHashSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericArrayList == null) ? 0 : genericArrayList.hashCode());
result = prime * result + ((integerHashSet == null) ? 0 : integerHashSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericArrayList == null) {
if (other.genericArrayList != null)
return false;
} else if (!genericArrayList.equals(other.genericArrayList))
return false;
if (integerHashSet == null) {
if (other.integerHashSet != null)
return false;
} else if (!integerHashSet.equals(other.integerHashSet))
return false;
return true;
}
protected ArrayList<?> getGenericArrayList() {
return genericArrayList;
}
protected void setGenericArrayList(ArrayList<?> genericArrayList) {
this.genericArrayList = genericArrayList;
}
protected HashSet<Integer> getIntegerHashSet() {
return integerHashSet;
}
protected void setIntegerHashSet(HashSet<Integer> integerHashSet) {
this.integerHashSet = integerHashSet;
}
}

View File

@ -132,6 +132,7 @@
<module>wicket</module> <module>wicket</module>
<module>xstream</module> <module>xstream</module>
<module>java-cassandra</module> <module>java-cassandra</module>
<module>annotations</module>
</modules> </modules>
</project> </project>

View File

@ -1,7 +1,7 @@
## Spring Data Neo4j ## Spring Data Neo4j
### Relevant Articles: ### Relevant Articles:
- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-tutorial) - [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-intro)
### Build the Project with Tests Running ### Build the Project with Tests Running
``` ```