Merge remote-tracking branch 'upstream/master'

# Conflicts:
#	spring-security-custom-voter/src/main/java/org/baeldung/security/MinuteBasedVoter.java
This commit is contained in:
Kevin Gilmore 2016-10-23 12:27:54 -05:00
commit 48cd384ea0
219 changed files with 1759 additions and 819 deletions

View File

@ -11,6 +11,7 @@
</parent> </parent>
<properties> <properties>
<cxf.version>3.1.6</cxf.version> <cxf.version>3.1.6</cxf.version>
<surefire.version>2.19.1</surefire.version>
</properties> </properties>
<build> <build>
<plugins> <plugins>
@ -26,7 +27,7 @@
<version>2.19.1</version> <version>2.19.1</version>
<configuration> <configuration>
<excludes> <excludes>
<exclude>**/StudentTest.java</exclude> <exclude>**/*LiveTest.java</exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
@ -44,4 +45,66 @@
<version>${cxf.version}</version> <version>${cxf.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.4.19</version>
<configuration>
<container>
<containerId>tomcat8x</containerId>
<type>embedded</type>
</container>
<configuration>
<properties>
<cargo.hostname>localhost</cargo.hostname>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -2,20 +2,16 @@ package com.baeldung.cxf.introduction;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.Map; import java.util.Map;
import javax.xml.namespace.QName; import javax.xml.namespace.QName;
import javax.xml.ws.Service; import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding; import javax.xml.ws.soap.SOAPBinding;
import com.baeldung.cxf.introduction.Baeldung; import org.junit.Before;
import com.baeldung.cxf.introduction.Student; import org.junit.Test;
import com.baeldung.cxf.introduction.StudentImpl;
public class StudentTest { public class StudentLiveTest {
private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung"); private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung");
private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort"); private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort");
@ -25,7 +21,7 @@ public class StudentTest {
{ {
service = Service.create(SERVICE_NAME); service = Service.create(SERVICE_NAME);
String endpointAddress = "http://localhost:8080/baeldung"; final String endpointAddress = "http://localhost:8082/cxf-introduction/baeldung";
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress); service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
} }
@ -37,28 +33,28 @@ public class StudentTest {
@Test @Test
public void whenUsingHelloMethod_thenCorrect() { public void whenUsingHelloMethod_thenCorrect() {
String endpointResponse = baeldungProxy.hello("Baeldung"); final String endpointResponse = baeldungProxy.hello("Baeldung");
String localResponse = baeldungImpl.hello("Baeldung"); final String localResponse = baeldungImpl.hello("Baeldung");
assertEquals(localResponse, endpointResponse); assertEquals(localResponse, endpointResponse);
} }
@Test @Test
public void whenUsingHelloStudentMethod_thenCorrect() { public void whenUsingHelloStudentMethod_thenCorrect() {
Student student = new StudentImpl("John Doe"); final Student student = new StudentImpl("John Doe");
String endpointResponse = baeldungProxy.helloStudent(student); final String endpointResponse = baeldungProxy.helloStudent(student);
String localResponse = baeldungImpl.helloStudent(student); final String localResponse = baeldungImpl.helloStudent(student);
assertEquals(localResponse, endpointResponse); assertEquals(localResponse, endpointResponse);
} }
@Test @Test
public void usingGetStudentsMethod_thenCorrect() { public void usingGetStudentsMethod_thenCorrect() {
Student student1 = new StudentImpl("Adam"); final Student student1 = new StudentImpl("Adam");
baeldungProxy.helloStudent(student1); baeldungProxy.helloStudent(student1);
Student student2 = new StudentImpl("Eve"); final Student student2 = new StudentImpl("Eve");
baeldungProxy.helloStudent(student2); baeldungProxy.helloStudent(student2);
Map<Integer, Student> students = baeldungProxy.getStudents(); final Map<Integer, Student> students = baeldungProxy.getStudents();
assertEquals("Adam", students.get(1).getName()); assertEquals("Adam", students.get(1).getName());
assertEquals("Eve", students.get(2).getName()); assertEquals("Eve", students.get(2).getName());
} }

View File

@ -13,6 +13,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cxf.version>3.1.7</cxf.version> <cxf.version>3.1.7</cxf.version>
<httpclient.version>4.5.2</httpclient.version> <httpclient.version>4.5.2</httpclient.version>
<surefire.version>2.19.1</surefire.version>
</properties> </properties>
<build> <build>
<plugins> <plugins>
@ -28,7 +29,7 @@
<version>2.19.1</version> <version>2.19.1</version>
<configuration> <configuration>
<excludes> <excludes>
<exclude>**/ServiceTest</exclude> <exclude>**/*LiveTest.java</exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
@ -51,4 +52,66 @@
<version>${httpclient.version}</version> <version>${httpclient.version}</version>
</dependency> </dependency>
</dependencies> </dependencies>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.4.19</version>
<configuration>
<container>
<containerId>tomcat8x</containerId>
<type>embedded</type>
</container>
<configuration>
<properties>
<cargo.hostname>localhost</cargo.hostname>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -37,26 +37,36 @@ public class Baeldung {
} }
@GET @GET
@Path("courses/{courseOrder}") @Path("courses/{courseId}")
public Course getCourse(@PathParam("courseOrder") int courseOrder) { public Course getCourse(@PathParam("courseId") int courseId) {
return courses.get(courseOrder); return findById(courseId);
} }
@PUT @PUT
@Path("courses/{courseOrder}") @Path("courses/{courseId}")
public Response putCourse(@PathParam("courseOrder") int courseOrder, Course course) { public Response updateCourse(@PathParam("courseId") int courseId, Course course) {
Course existingCourse = courses.get(courseOrder); Course existingCourse = findById(courseId);
if (existingCourse == null) {
if (existingCourse == null || existingCourse.getId() != course.getId() || !(existingCourse.getName().equals(course.getName()))) { return Response.status(Response.Status.NOT_FOUND).build();
courses.put(courseOrder, course);
return Response.ok().build();
} }
if (existingCourse.equals(course)) {
return Response.notModified().build(); return Response.notModified().build();
}
courses.put(courseId, course);
return Response.ok().build();
} }
@Path("courses/{courseOrder}/students") @Path("courses/{courseId}/students")
public Course pathToStudent(@PathParam("courseOrder") int courseOrder) { public Course pathToStudent(@PathParam("courseId") int courseId) {
return courses.get(courseOrder); return findById(courseId);
}
private Course findById(int id) {
for (Map.Entry<Integer, Course> course : courses.entrySet()) {
if (course.getKey() == id) {
return course.getValue();
}
}
return null;
} }
} }

View File

@ -3,6 +3,7 @@ package com.baeldung.cxf.jaxrs.implementation;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -10,7 +11,7 @@ import java.util.List;
public class Course { public class Course {
private int id; private int id;
private String name; private String name;
private List<Student> students; private List<Student> students = new ArrayList<>();
public int getId() { public int getId() {
return id; return id;
@ -37,29 +38,49 @@ public class Course {
} }
@GET @GET
@Path("{studentOrder}") @Path("{studentId}")
public Student getStudent(@PathParam("studentOrder")int studentOrder) { public Student getStudent(@PathParam("studentId") int studentId) {
return students.get(studentOrder); return findById(studentId);
} }
@POST @POST
public Response postStudent(Student student) { public Response createStudent(Student student) {
if (students == null) { for (Student element : students) {
students = new ArrayList<>(); if (element.getId() == student.getId()) {
return Response.status(Response.Status.CONFLICT).build();
}
} }
students.add(student); students.add(student);
return Response.ok(student).build(); return Response.ok(student).build();
} }
@DELETE @DELETE
@Path("{studentOrder}") @Path("{studentId}")
public Response deleteStudent(@PathParam("studentOrder") int studentOrder) { public Response deleteStudent(@PathParam("studentId") int studentId) {
Student student = students.get(studentOrder); Student student = findById(studentId);
if (student != null) { if (student == null) {
students.remove(studentOrder); return Response.status(Response.Status.NOT_FOUND).build();
return Response.ok().build();
} else {
return Response.notModified().build();
} }
students.remove(student);
return Response.ok().build();
}
private Student findById(int id) {
for (Student student : students) {
if (student.getId() == id) {
return student;
}
}
return null;
}
@Override
public int hashCode() {
return id + name.hashCode();
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Course) && (id == ((Course) obj).getId()) && (name.equals(((Course) obj).getName()));
} }
} }

View File

@ -22,4 +22,14 @@ public class Student {
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override
public int hashCode() {
return id + name.hashCode();
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Student) && (id == ((Student) obj).getId()) && (name.equals(((Student) obj).getName()));
}
} }

View File

@ -0,0 +1,4 @@
<Course>
<id>2</id>
<name>Apache CXF Support for RESTful</name>
</Course>

View File

@ -0,0 +1,4 @@
<Student>
<id>2</id>
<name>Student B</name>
</Student>

View File

@ -1,4 +1,3 @@
<Student> <Student>
<id>3</id> <id>3</id>
<name>Student C</name> <name>Student C</name>

View File

@ -0,0 +1,4 @@
<Course>
<id>1</id>
<name>REST with Spring</name>
</Course>

View File

@ -0,0 +1,130 @@
package com.baeldung.cxf.jaxrs.implementation;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.bind.JAXB;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class ServiceLiveTest {
private static final String BASE_URL = "http://localhost:8082/baeldung/courses/";
private static CloseableHttpClient client;
@BeforeClass
public static void createClient() {
client = HttpClients.createDefault();
}
@AfterClass
public static void closeClient() throws IOException {
client.close();
}
@Test
public void whenUpdateNonExistentCourse_thenReceiveNotFoundResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "3");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(404, response.getStatusLine().getStatusCode());
}
@Test
public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "1");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(304, response.getStatusLine().getStatusCode());
}
@Test
public void whenUpdateValidCourse_thenReceiveOKResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "2");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(200, response.getStatusLine().getStatusCode());
final Course course = getCourse(2);
assertEquals(2, course.getId());
assertEquals("Apache CXF Support for RESTful", course.getName());
}
@Test
public void whenCreateConflictStudent_thenReceiveConflictResponse() throws IOException {
final HttpPost httpPost = new HttpPost(BASE_URL + "1/students");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml");
httpPost.setEntity(new InputStreamEntity(resourceStream));
httpPost.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPost);
assertEquals(409, response.getStatusLine().getStatusCode());
}
@Test
public void whenCreateValidStudent_thenReceiveOKResponse() throws IOException {
final HttpPost httpPost = new HttpPost(BASE_URL + "2/students");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml");
httpPost.setEntity(new InputStreamEntity(resourceStream));
httpPost.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPost);
assertEquals(200, response.getStatusLine().getStatusCode());
final Student student = getStudent(2, 3);
assertEquals(3, student.getId());
assertEquals("Student C", student.getName());
}
@Test
public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException {
final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3");
final HttpResponse response = client.execute(httpDelete);
assertEquals(404, response.getStatusLine().getStatusCode());
}
@Test
public void whenDeleteValidStudent_thenReceiveOKResponse() throws IOException {
final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1");
final HttpResponse response = client.execute(httpDelete);
assertEquals(200, response.getStatusLine().getStatusCode());
final Course course = getCourse(1);
assertEquals(1, course.getStudents().size());
assertEquals(2, course.getStudents().get(0).getId());
assertEquals("Student B", course.getStudents().get(0).getName());
}
private Course getCourse(int courseOrder) throws IOException {
final URL url = new URL(BASE_URL + courseOrder);
final InputStream input = url.openStream();
return JAXB.unmarshal(new InputStreamReader(input), Course.class);
}
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
final URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
final InputStream input = url.openStream();
return JAXB.unmarshal(new InputStreamReader(input), Student.class);
}
}

View File

@ -1,89 +0,0 @@
package com.baeldung.cxf.jaxrs.implementation;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.xml.bind.JAXB;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import static org.junit.Assert.assertEquals;
public class ServiceTest {
private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
private static CloseableHttpClient client;
@BeforeClass
public static void createClient() {
client = HttpClients.createDefault();
}
@AfterClass
public static void closeClient() throws IOException {
client.close();
}
@Test
public void whenPutCourse_thenCorrect() throws IOException {
HttpPut httpPut = new HttpPut(BASE_URL + "3");
InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
HttpResponse response = client.execute(httpPut);
assertEquals(200, response.getStatusLine().getStatusCode());
Course course = getCourse(3);
assertEquals(3, course.getId());
assertEquals("Apache CXF Support for RESTful", course.getName());
}
@Test
public void whenPostStudent_thenCorrect() throws IOException {
HttpPost httpPost = new HttpPost(BASE_URL + "2/students");
InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("student.xml");
httpPost.setEntity(new InputStreamEntity(resourceStream));
httpPost.setHeader("Content-Type", "text/xml");
HttpResponse response = client.execute(httpPost);
assertEquals(200, response.getStatusLine().getStatusCode());
Student student = getStudent(2, 0);
assertEquals(3, student.getId());
assertEquals("Student C", student.getName());
}
@Test
public void whenDeleteStudent_thenCorrect() throws IOException {
HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/0");
HttpResponse response = client.execute(httpDelete);
assertEquals(200, response.getStatusLine().getStatusCode());
Course course = getCourse(1);
assertEquals(1, course.getStudents().size());
assertEquals(2, course.getStudents().get(0).getId());
assertEquals("Student B", course.getStudents().get(0).getName());
}
private Course getCourse(int courseOrder) throws IOException {
URL url = new URL(BASE_URL + courseOrder);
InputStream input = url.openStream();
return JAXB.unmarshal(new InputStreamReader(input), Course.class);
}
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
InputStream input = url.openStream();
return JAXB.unmarshal(new InputStreamReader(input), Student.class);
}
}

View File

@ -51,7 +51,7 @@
<version>${surefire.version}</version> <version>${surefire.version}</version>
<configuration> <configuration>
<excludes> <excludes>
<exclude>StudentTest.java</exclude> <exclude>**/*LiveTest.java</exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
@ -60,7 +60,7 @@
<profiles> <profiles>
<profile> <profile>
<id>integration</id> <id>live</id>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>

View File

@ -6,7 +6,7 @@ import org.junit.Test;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class StudentTest { public class StudentLiveTest {
private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class); private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
private Baeldung baeldungProxy = (Baeldung) context.getBean("client"); private Baeldung baeldungProxy = (Baeldung) context.getBean("client");

View File

@ -45,8 +45,60 @@
</dependencies> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties> <properties>
<spring.version>4.3.1.RELEASE</spring.version> <spring.version>4.3.1.RELEASE</spring.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -16,7 +16,7 @@ import com.baeldung.spring.service.SpringSuperService;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@ContextConfiguration(classes = { AppConfig.class }) @ContextConfiguration(classes = { AppConfig.class })
public class TestSpringInterceptor { public class SpringInterceptorIntegrationTest {
@Autowired @Autowired
SpringSuperService springSuperService; SpringSuperService springSuperService;

View File

@ -3,36 +3,82 @@ package com.baeldung.encoderdecoder;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class EncoderDecoder { public class EncoderDecoder {
@Test private static final String URL = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
public void givenPlainURL_whenUsingUTF8EncodingScheme_thenEncodeURL() throws UnsupportedEncodingException { private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoder.class);
String plainURL = "http://www.baeldung.com" ;
String encodedURL = URLEncoder.encode(plainURL, StandardCharsets.UTF_8.toString());
Assert.assertThat("http%3A%2F%2Fwww.baeldung.com", CoreMatchers.is(encodedURL)); private String encodeValue(String value) {
String encoded = null;
try {
encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
}
return encoded;
}
private String decode(String value) {
String decoded = null;
try {
decoded = URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
}
return decoded;
} }
@Test @Test
public void givenEncodedURL_whenUsingUTF8EncodingScheme_thenDecodeURL() throws UnsupportedEncodingException { public void givenURL_whenAnalyze_thenCorrect() throws Exception {
String encodedURL = "http%3A%2F%2Fwww.baeldung.com" ; URL url = new URL(URL);
String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_8.toString());
Assert.assertThat("http://www.baeldung.com", CoreMatchers.is(decodedURL)); Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
Assert.assertThat(url.getQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253"));
} }
@Test @Test
public void givenEncodedURL_whenUsingWrongEncodingScheme_thenDecodeInvalidURL() throws UnsupportedEncodingException { public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
String encodedURL = "http%3A%2F%2Fwww.baeldung.com"; Map<String, String> requestParams = new HashMap<>();
requestParams.put("key1", "value 1");
requestParams.put("key2", "value@!$2");
requestParams.put("key3", "value%3");
String decodedURL = URLDecoder.decode(encodedURL, StandardCharsets.UTF_16.toString()); String encodedQuery = requestParams.keySet().stream()
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(Collectors.joining("&"));
String encodedURL = "http://www.baeldung.com?" + encodedQuery;
Assert.assertFalse("http://www.baeldung.com".equals(decodedURL)); Assert.assertThat(URL, CoreMatchers.is(encodedURL));
} }
@Test
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
URL url = new URL(URL);
String query = url.getQuery();
String decodedQuery = Arrays.stream(query.split("&"))
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
.collect(Collectors.joining("&"));
Assert.assertEquals(
"http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
}
} }

View File

@ -18,3 +18,4 @@
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) - [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist) - [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)

View File

@ -1,14 +1,15 @@
package com.baeldung.java.nio.selector; package com.baeldung.java.nio.selector;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel; import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.Set;
import java.util.Iterator; import java.util.Iterator;
import java.net.InetSocketAddress; import java.util.Set;
public class EchoServer { public class EchoServer {
@ -47,4 +48,15 @@ public class EchoServer {
} }
} }
} }
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = EchoServer.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
} }

View File

@ -0,0 +1,23 @@
package com.baeldung.printscreen;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class Screenshot {
private final String path;
public Screenshot(String path) {
this.path = path;
}
public void getScreenshot(int timeToWait) throws Exception {
Thread.sleep(timeToWait);
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, "jpg", new File(path));
}
}

View File

@ -23,8 +23,7 @@ public class EchoClient {
public String sendMessage(String msg) { public String sendMessage(String msg) {
try { try {
out.println(msg); out.println(msg);
String resp = in.readLine(); return in.readLine();
return resp;
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }

View File

@ -26,8 +26,7 @@ public class GreetClient {
public String sendMessage(String msg) { public String sendMessage(String msg) {
try { try {
out.println(msg); out.println(msg);
String resp = in.readLine(); return in.readLine();
return resp;
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }

View File

@ -2,17 +2,20 @@ package com.baeldung.java.nio.selector;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test; import org.junit.Test;
public class EchoTest { public class EchoTest {
@Test @Test
public void givenClient_whenServerEchosMessage_thenCorrect() { public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException {
Process process = EchoServer.start();
EchoClient client = EchoClient.start(); EchoClient client = EchoClient.start();
String resp1 = client.sendMessage("hello"); String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world"); String resp2 = client.sendMessage("world");
assertEquals("hello", resp1); assertEquals("hello", resp1);
assertEquals("world", resp2); assertEquals("world", resp2);
process.destroy();
} }
} }

View File

@ -0,0 +1,26 @@
package com.baeldung.printscreen;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertTrue;
public class ScreenshotTest {
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
private File file = new File("Screenshot.jpg");
@Test
public void testGetScreenshot() throws Exception {
screenshot.getScreenshot(2000);
assertTrue(file.exists());
}
@After
public void tearDown() throws Exception {
file.delete();
}
}

View File

@ -1,7 +1,6 @@
package com.baeldung.socket; package com.baeldung.socket;
import org.junit.After; import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -10,18 +9,22 @@ import static org.junit.Assert.assertEquals;
public class EchoMultiTest { public class EchoMultiTest {
{ private static final Integer PORT = 5555;
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(5555));
}
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT));
Thread.sleep(500);
}
@Test @Test
public void givenClient1_whenServerResponds_thenCorrect() { public void givenClient1_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient(); EchoClient client = new EchoClient();
client.startConnection("127.0.0.1", 5555); client.startConnection("127.0.0.1", PORT);
String msg1 = client.sendMessage("hello"); String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world"); String msg2 = client.sendMessage("world");
String terminate = client.sendMessage("."); String terminate = client.sendMessage(".");
assertEquals(msg1, "hello"); assertEquals(msg1, "hello");
assertEquals(msg2, "world"); assertEquals(msg2, "world");
assertEquals(terminate, "bye"); assertEquals(terminate, "bye");
@ -31,7 +34,7 @@ public class EchoMultiTest {
@Test @Test
public void givenClient2_whenServerResponds_thenCorrect() { public void givenClient2_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient(); EchoClient client = new EchoClient();
client.startConnection("127.0.0.1", 5555); client.startConnection("127.0.0.1", PORT);
String msg1 = client.sendMessage("hello"); String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world"); String msg2 = client.sendMessage("world");
String terminate = client.sendMessage("."); String terminate = client.sendMessage(".");
@ -44,7 +47,7 @@ public class EchoMultiTest {
@Test @Test
public void givenClient3_whenServerResponds_thenCorrect() { public void givenClient3_whenServerResponds_thenCorrect() {
EchoClient client = new EchoClient(); EchoClient client = new EchoClient();
client.startConnection("127.0.0.1", 5555); client.startConnection("127.0.0.1", PORT);
String msg1 = client.sendMessage("hello"); String msg1 = client.sendMessage("hello");
String msg2 = client.sendMessage("world"); String msg2 = client.sendMessage("world");
String terminate = client.sendMessage("."); String terminate = client.sendMessage(".");
@ -53,5 +56,4 @@ public class EchoMultiTest {
assertEquals(terminate, "bye"); assertEquals(terminate, "bye");
client.stopConnection(); client.stopConnection();
} }
} }

View File

@ -2,6 +2,7 @@ package com.baeldung.socket;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -9,15 +10,19 @@ import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class EchoTest { public class EchoTest {
{ private static final Integer PORT = 4444;
Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(4444));
}
EchoClient client = new EchoClient(); @BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT));
Thread.sleep(500);
}
private EchoClient client = new EchoClient();
@Before @Before
public void init() { public void init() {
client.startConnection("127.0.0.1", 4444); client.startConnection("127.0.0.1", PORT);
} }
@Test @Test
@ -37,5 +42,4 @@ public class EchoTest {
public void tearDown() { public void tearDown() {
client.stopConnection(); client.stopConnection();
} }
} }

View File

@ -2,6 +2,7 @@ package com.baeldung.socket;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -10,16 +11,20 @@ import static org.junit.Assert.assertEquals;
public class GreetServerTest { public class GreetServerTest {
GreetClient client; private GreetClient client;
{ private static final Integer PORT = 6666;
Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(6666));
@BeforeClass
public static void start() throws InterruptedException {
Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT));
Thread.sleep(500);
} }
@Before @Before
public void init() { public void init() {
client = new GreetClient(); client = new GreetClient();
client.startConnection("127.0.0.1", 6666); client.startConnection("127.0.0.1", PORT);
} }

View File

@ -2,9 +2,9 @@
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>
<artifactId>flyway-migration</artifactId> <artifactId>flyway</artifactId>
<version>1.0</version> <version>1.0</version>
<name>flyway-migration</name> <name>flyway</name>
<description>A sample project to demonstrate Flyway migrations</description> <description>A sample project to demonstrate Flyway migrations</description>
<dependencies> <dependencies>
<dependency> <dependency>

View File

@ -1,6 +0,0 @@
## Performance of Gson and Jackson
Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity.
###Relevant Articles:
- [Jackson vs Gson: A Quick Look At Performance](http://www.baeldung.com/jackson-gson-performance)

View File

@ -1,27 +1,11 @@
package org.baeldung.httpclient; package org.baeldung.httpclient;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.*;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
@ -29,6 +13,17 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.junit.Test; import org.junit.Test;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/** /**
* This test requires a localhost server over HTTPS <br> * This test requires a localhost server over HTTPS <br>
* It should only be manually run, not part of the automated build * It should only be manually run, not part of the automated build
@ -42,7 +37,7 @@ public class HttpsClientSslLiveTest {
// tests // tests
@Test(expected = SSLException.class) @Test(expected = SSLException.class)
public final void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException { public final void whenHttpsUrlIsConsumed_thenException() throws IOException {
final CloseableHttpClient httpClient = HttpClientBuilder.create().build(); final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
@ -53,12 +48,7 @@ public class HttpsClientSslLiveTest {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @Test
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
@Override
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
final SchemeRegistry registry = new SchemeRegistry(); final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 443, sf)); registry.register(new Scheme("https", 443, sf));
@ -75,12 +65,7 @@ public class HttpsClientSslLiveTest {
@Test @Test
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
@Override
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
@ -108,4 +93,25 @@ public class HttpsClientSslLiveTest {
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} }
@Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, acceptingTrustStrategy).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
e.printStackTrace();
}
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002");
httpGet.setHeader("Accept", "application/xml");
final HttpResponse response = client.execute(httpGet);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
} }

View File

@ -1,16 +1,8 @@
package org.baeldung.httpclient.base; package org.baeldung.httpclient.base;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -23,6 +15,13 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class HttpClientLiveTest { public class HttpClientLiveTest {
private static final String SAMPLE_URL = "http://www.github.com"; private static final String SAMPLE_URL = "http://www.github.com";
@ -56,7 +55,7 @@ public class HttpClientLiveTest {
// tests // tests
@Test(expected = ConnectTimeoutException.class) @Test(expected = ConnectTimeoutException.class)
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws ClientProtocolException, IOException { public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build(); final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(20).build();
final HttpGet request = new HttpGet(SAMPLE_URL); final HttpGet request = new HttpGet(SAMPLE_URL);
request.setConfig(requestConfig); request.setConfig(requestConfig);
@ -66,20 +65,20 @@ public class HttpClientLiveTest {
// tests - configs // tests - configs
@Test @Test
public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws ClientProtocolException, IOException { public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws IOException {
instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build(); instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build();
response = instance.execute(new HttpGet(SAMPLE_URL)); response = instance.execute(new HttpGet(SAMPLE_URL));
} }
@Test @Test
public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws ClientProtocolException, IOException { public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL); final HttpGet request = new HttpGet(SAMPLE_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml"); request.addHeader(HttpHeaders.ACCEPT, "application/xml");
response = instance.execute(request); response = instance.execute(request);
} }
@Test @Test
public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws ClientProtocolException, IOException { public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException {
response = instance.execute(new HttpGet(SAMPLE_URL)); response = instance.execute(new HttpGet(SAMPLE_URL));
final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
@ -89,7 +88,7 @@ public class HttpClientLiveTest {
// tests - cancel request // tests - cancel request
@Test @Test
public final void whenRequestIsCanceled_thenCorrect() throws ClientProtocolException, IOException { public final void whenRequestIsCanceled_thenCorrect() throws IOException {
instance = HttpClients.custom().build(); instance = HttpClients.custom().build();
final HttpGet request = new HttpGet(SAMPLE_URL); final HttpGet request = new HttpGet(SAMPLE_URL);
response = instance.execute(request); response = instance.execute(request);

View File

@ -1,34 +1,33 @@
package org.baeldung.httpclient.base; package org.baeldung.httpclient.base;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class HttpClientSandboxLiveTest { public class HttpClientSandboxLiveTest {
private CloseableHttpClient client; @Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
final AuthScope authscp = new AuthScope("localhost", 8080);
credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass"));
private CloseableHttpResponse response; CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
@After final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1");
public final void after() throws IllegalStateException, IOException { CloseableHttpResponse response = client.execute(httpGet);
if (response == null) {
return; System.out.println(response.getStatusLine());
}
try { try {
final HttpEntity entity = response.getEntity(); final HttpEntity entity = response.getEntity();
@ -41,33 +40,4 @@ public class HttpClientSandboxLiveTest {
response.close(); response.close();
} }
} }
// tests
// simple request - response
@Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws ClientProtocolException, IOException {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
final AuthScope authscp = new AuthScope("localhost", 8080);
credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass"));
client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1");
response = client.execute(httpGet);
System.out.println(response.getStatusLine());
}
@Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException {
final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002");
httpGet.setHeader("Accept", "application/xml");
response = httpClient.execute(httpGet);
}
} }

View File

@ -112,9 +112,54 @@
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -76,9 +76,55 @@
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -97,6 +143,7 @@
<!-- maven plugins --> <!-- maven plugins -->
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- Cassandra --> <!-- Cassandra -->
<cassandra-driver-core.version>3.1.0</cassandra-driver-core.version> <cassandra-driver-core.version>3.1.0</cassandra-driver-core.version>

View File

@ -58,8 +58,51 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -9,7 +9,7 @@ import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = JJWTFunApplication.class) @SpringApplicationConfiguration(classes = JJWTFunApplication.class)
@WebAppConfiguration @WebAppConfiguration
public class DemoApplicationTests { public class DemoApplicationIntegrationTest {
@Test @Test
public void contextLoads() { public void contextLoads() {

View File

@ -55,6 +55,54 @@
</annotationProcessorPaths> </annotationProcessorPaths>
</configuration> </configuration>
</plugin> </plugin>
</plugins>
</build> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml") @ContextConfiguration("classpath:applicationContext.xml")
public class SimpleSourceDestinationMapperTest { public class SimpleSourceDestinationMapperIntegrationTest {
@Autowired @Autowired
SimpleSourceDestinationMapper simpleSourceDestinationMapper; SimpleSourceDestinationMapper simpleSourceDestinationMapper;

16
pom.xml
View File

@ -17,7 +17,7 @@
<module>assertj</module> <module>assertj</module>
<module>apache-cxf</module> <module>apache-cxf</module>
<!-- <module>apache-fop</module> --> <!-- TODO: has a compilation issue --> <!-- <module>apache-fop</module> --> <!-- TODO: has a compilation issue -->
<module>autovalue-tutorial</module> <module>autovalue</module>
<module>cdi</module> <module>cdi</module>
<module>core-java</module> <module>core-java</module>
@ -26,13 +26,14 @@
<!-- <module>core-java-9</module> --> <!-- <module>core-java-9</module> -->
<module>dozer</module> <module>dozer</module>
<module>dependency-injection</module>
<module>deltaspike</module> <module>deltaspike</module>
<module>patterns</module> <module>patterns</module>
<module>feign-client</module> <module>feign</module>
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build --> <!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
<module>flyway</module>
<module>gson</module> <module>gson</module>
<module>guava</module> <module>guava</module>
<module>guava18</module> <module>guava18</module>
@ -46,12 +47,12 @@
<module>jackson</module> <module>jackson</module>
<module>javaxval</module> <module>javaxval</module>
<module>jjwt</module> <module>jjwt</module>
<module>jooq-spring</module>
<module>jpa-storedprocedure</module> <module>jpa-storedprocedure</module>
<module>json</module> <module>json</module>
<module>json-path</module> <module>json-path</module>
<module>junit5</module> <module>junit5</module>
<module>jee7schedule</module> <module>jee7</module>
<!-- <module>jpa-storedprocedure</module> --> <!-- <module>jpa-storedprocedure</module> -->
<module>log4j</module> <module>log4j</module>
@ -75,6 +76,7 @@
<module>spring-autowire</module> <module>spring-autowire</module>
<module>spring-batch</module> <module>spring-batch</module>
<module>spring-boot</module> <module>spring-boot</module>
<module>spring-core</module>
<module>spring-cucumber</module> <module>spring-cucumber</module>
<module>spring-data-cassandra</module> <module>spring-data-cassandra</module>
<module>spring-data-couchbase-2</module> <module>spring-data-couchbase-2</module>
@ -87,8 +89,9 @@
<module>spring-freemarker</module> <module>spring-freemarker</module>
<module>spring-hibernate3</module> <module>spring-hibernate3</module>
<module>spring-hibernate4</module> <module>spring-hibernate4</module>
<module>spring-jpa</module>
<module>spring-jms</module> <module>spring-jms</module>
<module>spring-jooq</module>
<module>spring-jpa</module>
<module>spring-katharsis</module> <module>spring-katharsis</module>
<module>spring-mockito</module> <module>spring-mockito</module>
<module>spring-mvc-java</module> <module>spring-mvc-java</module>
@ -126,6 +129,7 @@
<module>jsf</module> <module>jsf</module>
<module>xml</module> <module>xml</module>
<module>xmlunit2</module>
<module>lombok</module> <module>lombok</module>
<module>redis</module> <module>redis</module>

View File

@ -1,26 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>corejava-printscreen</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>How to Print Screen in Java</name>
<url>https://github.com/eugenp/tutorials</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,38 +0,0 @@
package org.baeldung.corejava;;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class Screenshot {
private String filePath;
private String filenamePrefix;
private String fileType;
private int timeToWait;
public Screenshot(String filePath, String filenamePrefix,
String fileType, int timeToWait) {
this.filePath = filePath;
this.filenamePrefix = filenamePrefix;
this.fileType = fileType;
this.timeToWait = timeToWait;
}
public void getScreenshot() throws Exception {
Thread.sleep(timeToWait);
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
ImageIO.write(img, fileType, setupFileNamePath());
}
private File setupFileNamePath() {
return new File(filePath + filenamePrefix + "." + fileType);
}
private Rectangle getScreenSizedRectangle(final Dimension d) {
return new Rectangle(0, 0, d.width, d.height);
}
}

View File

@ -1,39 +0,0 @@
package org.baeldung.corejava;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
public class ScreenshotTest {
private Screenshot screenshot;
private String filePath;
private String fileName;
private String fileType;
private File file;
@Before
public void setUp() throws Exception {
filePath = "";
fileName = "Screenshot";
fileType = "jpg";
file = new File(filePath + fileName + "." + fileType);
screenshot = new Screenshot(filePath, fileName, fileType, 2000);
}
@Test
public void testGetScreenshot() throws Exception {
screenshot.getScreenshot();
assertTrue(file.exists());
}
@After
public void tearDown() throws Exception {
file.delete();
}
}

View File

@ -20,6 +20,7 @@
<hibernate.version>5.2.1.Final</hibernate.version> <hibernate.version>5.2.1.Final</hibernate.version>
<querydsl.version>4.1.3</querydsl.version> <querydsl.version>4.1.3</querydsl.version>
<slf4j.version>1.7.21</slf4j.version> <slf4j.version>1.7.21</slf4j.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties> </properties>
<dependencies> <dependencies>
@ -166,7 +167,55 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -17,7 +17,7 @@ import junit.framework.Assert;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@Transactional @Transactional
@TransactionConfiguration(defaultRollback = true) @TransactionConfiguration(defaultRollback = true)
public class PersonDaoTest { public class PersonDaoIntegrationTest {
@Autowired @Autowired
private PersonDao personDao; private PersonDao personDao;

View File

@ -1,28 +1,15 @@
package com.baeldung; package com.baeldung;
import org.junit.*;
import redis.clients.jedis.*;
import redis.embedded.RedisServer;
import java.io.IOException; import java.io.IOException;
import java.time.Duration; import java.time.Duration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;
import redis.embedded.RedisServer;
/**
* Unit test for Redis Java library - Jedis.
*/
public class JedisTest { public class JedisTest {
private Jedis jedis; private Jedis jedis;
@ -140,9 +127,9 @@ public class JedisTest {
scores.put("PlayerTwo", 1500.0); scores.put("PlayerTwo", 1500.0);
scores.put("PlayerThree", 8200.0); scores.put("PlayerThree", 8200.0);
for (String player : scores.keySet()) { scores.keySet().forEach(player -> {
jedis.zadd(key, scores.get(player), player); jedis.zadd(key, scores.get(player), player);
} });
Set<String> players = jedis.zrevrange(key, 0, 1); Set<String> players = jedis.zrevrange(key, 0, 1);
Assert.assertEquals("PlayerThree", players.iterator().next()); Assert.assertEquals("PlayerThree", players.iterator().next());

View File

@ -148,12 +148,54 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version> <version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*UnitTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<exclude>**/*LiveTest.java</exclude>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties> <properties>
<!-- marshalling --> <!-- marshalling -->
<jackson.version>2.7.8</jackson.version> <jackson.version>2.7.8</jackson.version>

View File

@ -6,5 +6,5 @@ import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class) @RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:Feature") @CucumberOptions(features = "classpath:Feature")
public class CucumberTest { public class CucumberIntegrationTest {
} }

View File

@ -20,14 +20,35 @@
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version> <version>2.19.1</version>
<configuration> <configuration>
<testSourceDirectory></testSourceDirectory> <testFailureIgnore>true</testFailureIgnore>
<includes> <includes>
<include>Test*.java</include> <include>**/*UnitTest.java</include>
</includes> </includes>
<systemPropertyVariables></systemPropertyVariables>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.seleniumhq.selenium</groupId> <groupId>org.seleniumhq.selenium</groupId>
@ -37,12 +58,12 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.8.1</version> <version>4.12</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.testng</groupId> <groupId>org.testng</groupId>
<artifactId>testng</artifactId> <artifactId>testng</artifactId>
<version>6.9.10</version> <version>6.9.13.6</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -1,6 +1,11 @@
package main.java.com.baeldung.selenium; package main.java.com.baeldung.selenium;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumExample { public class SeleniumExample {
@ -10,6 +15,8 @@ public class SeleniumExample {
public SeleniumExample() { public SeleniumExample() {
webDriver = new FirefoxDriver(); webDriver = new FirefoxDriver();
webDriver.manage().window().maximize();
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
webDriver.get(url); webDriver.get(url);
} }
@ -21,4 +28,30 @@ public class SeleniumExample {
return webDriver.getTitle(); return webDriver.getTitle();
} }
public void getAboutBaeldungPage() {
closeOverlay();
clickAboutLink();
clickAboutUsLink();
}
private void closeOverlay() {
List<WebElement> webElementList = webDriver.findElements(By.tagName("a"));
if (webElementList != null && !webElementList.isEmpty()) {
webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().get().click();
}
}
private void clickAboutLink() {
webDriver.findElement(By.partialLinkText("About")).click();
}
private void clickAboutUsLink() {
webDriver.findElement(By.partialLinkText("About Baeldung.")).click();
}
public boolean isAuthorInformationAvailable() {
return webDriver
.findElement(By.xpath("//*[contains(text(), 'Eugen an engineer')]"))
.isDisplayed();
}
} }

View File

@ -0,0 +1,41 @@
package test.java.com.baeldung.selenium.junit;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class SeleniumWithJUnitLiveTest {
private static SeleniumExample seleniumExample;
private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung";
@BeforeClass
public static void setUp() {
seleniumExample = new SeleniumExample();
}
@AfterClass
public static void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
try {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(actualTitle, expecteTilteAboutBaeldungPage);
assertTrue(seleniumExample.isAuthorInformationAvailable());
} catch (Exception exception) {
exception.printStackTrace();
seleniumExample.closeWindow();
}
}
}

View File

@ -1,32 +0,0 @@
package test.java.com.baeldung.selenium.junit;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestSeleniumWithJUnit {
private SeleniumExample seleniumExample;
private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
@Before
public void setUp() {
seleniumExample = new SeleniumExample();
}
@After
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(actualTitle, expectedTitle);
}
}

View File

@ -0,0 +1,40 @@
package test.java.com.baeldung.selenium.testng;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class SeleniumWithTestNGLiveTest {
private SeleniumExample seleniumExample;
private String expecteTilteAboutBaeldungPage = "About Baeldung | Baeldung";
@BeforeSuite
public void setUp() {
seleniumExample = new SeleniumExample();
}
@AfterSuite
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenAboutBaeldungIsLoaded_thenAboutEugenIsMentionedOnPage() {
try {
seleniumExample.getAboutBaeldungPage();
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(actualTitle, expecteTilteAboutBaeldungPage);
assertTrue(seleniumExample.isAuthorInformationAvailable());
} catch (Exception exception) {
exception.printStackTrace();
seleniumExample.closeWindow();
}
}
}

View File

@ -1,32 +0,0 @@
package test.java.com.baeldung.selenium.testng;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestSeleniumWithTestNG {
private SeleniumExample seleniumExample;
private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials";
@BeforeSuite
public void setUp() {
seleniumExample = new SeleniumExample();
}
@AfterSuite
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String actualTitle = seleniumExample.getTitle();
assertNotNull(actualTitle);
assertEquals(actualTitle, expectedTitle);
}
}

View File

@ -1,2 +0,0 @@
### Relevant Articles:
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)

View File

@ -1,30 +0,0 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>sockets</artifactId>
<version>1.0</version>
<name>sockets</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -65,16 +65,63 @@
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties> <properties>
<spring.version>4.3.2.RELEASE</spring.version> <spring.version>4.3.2.RELEASE</spring.version>
<akka.version>2.4.8</akka.version> <akka.version>2.4.8</akka.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -20,7 +20,7 @@ import static akka.pattern.Patterns.ask;
import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER; import static org.baeldung.akka.SpringExtension.SPRING_EXTENSION_PROVIDER;
@ContextConfiguration(classes = AppConfiguration.class) @ContextConfiguration(classes = AppConfiguration.class)
public class SpringAkkaTest extends AbstractJUnit4SpringContextTests { public class SpringAkkaIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired @Autowired
private ActorSystem system; private ActorSystem system;

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