Merge branch 'master' into missing-modules

This commit is contained in:
Grzegorz Piwowarek 2016-07-23 16:39:06 +03:00
commit c8110b62cd
22 changed files with 858 additions and 576 deletions

View File

@ -5,3 +5,4 @@
### Relevant Articles: ### Relevant Articles:
- [JMockit 101](http://www.baeldung.com/jmockit-101) - [JMockit 101](http://www.baeldung.com/jmockit-101)
- [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations)

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

View File

@ -1,7 +0,0 @@
=========
## A Guide To REST-Assured
### Relevant Articles:

View File

@ -1,143 +1,257 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>rest-assured</artifactId> <artifactId>rest-assured-tutorial</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>1.0</version>
<name>rest-assured</name> <name>rest-assured</name>
<build>
<properties> <plugins>
<!-- maven plugins --> <plugin>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version> <groupId>org.apache.maven.plugins</groupId>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> <artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<mockito.version>1.10.19</mockito.version> <configuration>
<junit.version>4.12</junit.version> <source>8</source>
<wiremock.version>2.1.7</wiremock.version> <target>8</target>
<hamcrest-all.version>1.3</hamcrest-all.version> </configuration>
<json-schema-core.version>1.2.5</json-schema-core.version> </plugin>
<json-schema-validator.version>2.2.6</json-schema-validator.version> </plugins>
<rest-assured.version>3.0.0</rest-assured.version> </build>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
</properties>
<dependencies> <dependencies>
<!-- logging --> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1-b06</version>
</dependency>
<dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<groupId>org.slf4j</groupId> <dependency>
<artifactId>slf4j-api</artifactId> <groupId>javax.servlet</groupId>
<version>${org.slf4j.version}</version> <artifactId>servlet-api</artifactId>
</dependency> <version>2.5</version>
<dependency> </dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId> <!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-security -->
<version>${logback.version}</version> <dependency>
<!-- <scope>runtime</scope> --> <groupId>org.eclipse.jetty</groupId>
</dependency> <artifactId>jetty-security</artifactId>
<dependency> <version>9.2.0.M1</version>
<groupId>org.slf4j</groupId> </dependency>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version> <!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-servlet -->
<scope>runtime</scope> <dependency>
</dependency> <groupId>org.eclipse.jetty</groupId>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly --> <artifactId>jetty-servlet</artifactId>
<groupId>org.slf4j</groupId> <version>9.2.0.M1</version>
<artifactId>log4j-over-slf4j</artifactId> </dependency>
<version>${org.slf4j.version}</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-servlets -->
<!-- utils --> <dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>9.2.0.M1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-io -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-io</artifactId>
<version>9.2.0.M1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-http -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-http</artifactId>
<version>9.2.0.M1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-server -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.0.M1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.eclipse.jetty/jetty-util -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>9.2.0.M1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jayway.restassured/rest-assured-common -->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.fge/uri-template -->
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>uri-template</artifactId>
<version>0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.googlecode.libphonenumber/libphonenumber -->
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>7.4.5</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>msg-simple</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>jackson-coreutils</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>btf</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>2.1.7</version>
</dependency>
<dependency> <dependency>
<groupId>io.rest-assured</groupId> <groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId> <artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version> <version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.6</version>
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-core</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.3</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${rest-assured.version}</version>
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${json-schema-validator.version}</version>
</dependency>
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-core</artifactId>
<version>${json-schema-core.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId> <artifactId>hamcrest-all</artifactId>
<version>${hamcrest-all.version}</version> <version>1.3</version>
<scope>test</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>commons-collections</groupId>
<artifactId>mockito-core</artifactId> <artifactId>commons-collections</artifactId>
<version>${mockito.version}</version> <version>3.2.2</version>
<scope>test</scope> </dependency>
</dependency>
</dependencies> </dependencies>
</project>
<build>
<finalName>rest-assured</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,55 @@
package com.baeldung.restassured;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.Matchers.hasItems;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static io.restassured.RestAssured.get;
import com.github.tomakehurst.wiremock.WireMockServer;
public class RestAssured2Test {
private WireMockServer wireMockServer = new WireMockServer();
private static final String EVENTS_PATH = "/odds";
private static final String APPLICATION_JSON = "application/json";
private static final String ODDS = getJson();
@Before
public void before() throws Exception {
System.out.println("Setting up!");
wireMockServer.start();
configureFor("localhost", 8080);
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_JSON)
.withBody(ODDS)));
}
@Test
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
get("/odds").then().body("odds.findAll { it.status > 0 }.price",
hasItems(5.25f, 1.2f));
}
private static String getJson() {
return Util.inputStreamToString(new RestAssured2Test().getClass()
.getResourceAsStream("/odds.json"));
}
@After
public void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
}

View File

@ -1,206 +1,106 @@
package com.baeldung.restassured; package com.baeldung.restassured;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.fge.jsonschema.SchemaVersion; import com.github.fge.jsonschema.SchemaVersion;
import com.github.fge.jsonschema.cfg.ValidationConfiguration; import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.restassured.module.jsv.JsonSchemaValidator;
import org.junit.Ignore;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.post;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.xml.HasXPath.hasXPath;
public class RestAssuredTest { public class RestAssuredTest {
@Test
public void givenJsonResponse_whenKeyValuePairMatches_thenCorrect() {
JsonSchemaFactory factory = JsonSchemaFactory
.newBuilder()
.setValidationConfiguration(
ValidationConfiguration.newBuilder()
.setDefaultVersion(SchemaVersion.DRAFTV3)
.freeze()).freeze();
JsonSchemaValidator.settings = settings().with()
.jsonSchemaFactory(factory).and().with()
.checkedValidation(false);
}
@Test
public void givenJsonArrayOfSimilarObjects_whenHasGivenValuesForGivenKey_thenCorrect() {
}
private WireMockServer wireMockServer = new WireMockServer(); private WireMockServer wireMockServer = new WireMockServer();
private static final String EVENTS_PATH = "/events?id=390"; private static final String EVENTS_PATH = "/events?id=390";
private static final String APPLICATION_JSON = "application/json"; private static final String APPLICATION_JSON = "application/json";
private static final String GAME_ODDS = getEventJson();
private static final String GAME_ODDS = "" + @Before
"{" + public void before() throws Exception {
" \"id\": 390," + System.out.println("Setting up!");
" \"data\": {" +
" \"countryId\": 35," +
" \"countryName\": \"Norway\"," +
" \"leagueName\": \"Norway 3\"," +
" \"status\": 0," +
" \"sportName\": \"Soccer\"," +
" \"time\": \"2016-06-12T12:00:00Z\"" +
" }," +
" \"odds\": [" +
" {" +
" \"price\": \"1.30\"," +
" \"status\": 0," +
" \"ck\": \"1\"," +
" \"name\": \"1\"" +
" }," +
" {" +
" \"price\": \"5.25\"," +
" \"status\": 0," +
" \"ck\": \"X\"," +
" \"name\": \"X\"" +
" }" +
" ]" +
"}";
@Test
public void givenUrl_whenSuccessOnGetsResponse_andJsonHasRequiredKV_thenCorrect() {
wireMockServer.start(); wireMockServer.start();
configureFor("localhost", 8080); configureFor("localhost", 8080);
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
stubFor(WireMock.get(urlEqualTo(EVENTS_PATH)).willReturn(aResponse() aResponse().withStatus(200)
.withStatus(200) .withHeader("Content-Type", APPLICATION_JSON)
.withHeader("Content-Type", APPLICATION_JSON) .withBody(GAME_ODDS)));
.withBody(GAME_ODDS)));
get("/events?id=390").then().statusCode(200).assertThat()
.body("id", equalTo(390));
wireMockServer.stop();
} }
@Test
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() {
get("/events?id=390").then().assertThat()
.body("odd.ck", equalTo(12.2f));
}
@Test
public void givenUrl_whenSuccessOnGetsResponse_andJsonHasRequiredKV_thenCorrect() {
get("/events?id=390").then().statusCode(200).assertThat()
.body("id", equalTo("390"));
}
@Test @Test
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() { public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() {
wireMockServer.start();
configureFor("localhost", 8080);
stubFor(WireMock.get(urlEqualTo(EVENTS_PATH)).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", APPLICATION_JSON)
.withBody(GAME_ODDS)));
get("/events?id=390").then().assertThat() get("/events?id=390").then().assertThat()
.body("odds.price", hasItems("1.30", "5.25")); .body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20"));
wireMockServer.stop();
} }
@Test
@Test @Ignore
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() { public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
get("/events?id=390").then().assertThat() get("/events?id=390").then().assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json")); .body(matchesJsonSchemaInClasspath("event_0.json"));
} }
@Test @Ignore @Test
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() { public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory
.newBuilder() .newBuilder()
.setValidationConfiguration( .setValidationConfiguration(
ValidationConfiguration.newBuilder() ValidationConfiguration.newBuilder()
.setDefaultVersion(SchemaVersion.DRAFTV4) .setDefaultVersion(SchemaVersion.DRAFTV4)
.freeze()).freeze(); .freeze()).freeze();
get("/events?id=390") get("/events?id=390")
.then() .then()
.assertThat() .assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using( .body(matchesJsonSchemaInClasspath("event_0.json").using(
jsonSchemaFactory)); jsonSchemaFactory));
} }
@Test @Ignore @Test
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() { public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
get("/events?id=390") get("/events?id=390")
.then() .then()
.assertThat() .assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using( .body(matchesJsonSchemaInClasspath("event_0.json").using(
settings().with().checkedValidation(false))); settings().with().checkedValidation(false)));
} }
@Test @Ignore @After
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() { public void after() throws Exception {
get("/odd").then().assertThat().body("odd.ck", equalTo(12.2f)); System.out.println("Running: tearDown");
wireMockServer.stop();
} }
@Test @Ignore private static String getEventJson() {
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() { return Util.inputStreamToString(RestAssuredTest.class
post("/employees").then().assertThat() .getResourceAsStream("/event_0.json"));
.body("employees.employee.first-name", equalTo("Jane"));
}
@Test @Ignore
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
post("/employees").then().assertThat()
.body("employees.employee.first-name", equalTo("Jane"))
.body("employees.employee.last-name", equalTo("Daisy"))
.body("employees.employee.sex", equalTo("f"));
}
@Test @Ignore
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body("employees.employee.first-name", equalTo("Jane"),
"employees.employee.last-name", equalTo("Daisy"),
"employees.employee.sex", equalTo("f"));
}
@Test @Ignore
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body(hasXPath("/employees/employee/first-name",
containsString("Ja")));
}
@Test @Ignore
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
}
@Test @Ignore
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
get("/teachers")
.then()
.body("teachers.teacher.find { it.@department == 'science' }.subject",
hasItems("math", "physics"));
}
@Test @Ignore
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
get("/odds").then().body("odds.findAll { it.status > 0 }.price",
hasItems(1.30f, 1.20f));
} }
} }

View File

@ -0,0 +1,54 @@
package com.baeldung.restassured;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.Matchers.hasItems;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static io.restassured.RestAssured.get;
import com.github.tomakehurst.wiremock.WireMockServer;
public class RestAssuredXML2Test {
private WireMockServer wireMockServer = new WireMockServer();
private static final String EVENTS_PATH = "/teachers";
private static final String APPLICATION_XML = "application/xml";
private static final String TEACHERS = getXml();
@Before
public void before() throws Exception {
System.out.println("Setting up!");
wireMockServer.start();
configureFor("localhost", 8080);
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_XML)
.withBody(TEACHERS)));
}
@Test
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
get("/teachers")
.then()
.body("teachers.teacher.find { it.@department == 'science' }.subject",
hasItems("math", "physics"));
}
private static String getXml() {
return Util
.inputStreamToString(new RestAssuredXML2Test().getClass().getResourceAsStream("/teachers.xml"));
}
@After
public void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.restassured;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.post;
import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.xml.HasXPath.hasXPath;
import java.io.FileNotFoundException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.github.fge.jsonschema.SchemaVersion;
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.tomakehurst.wiremock.WireMockServer;
public class RestAssuredXMLTest {
private WireMockServer wireMockServer = new WireMockServer();
private static final String EVENTS_PATH = "/employees";
private static final String APPLICATION_XML = "application/xml";
private static final String EMPLOYEES = getXml();
@Before
public void before() throws Exception {
System.out.println("Setting up!");
wireMockServer.start();
configureFor("localhost", 8080);
stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_XML)
.withBody(EMPLOYEES)));
}
@Test
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
post("/employees").then().assertThat()
.body("employees.employee.first-name", equalTo("Jane"));
}
@Test
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
post("/employees").then().assertThat()
.body("employees.employee.first-name", equalTo("Jane"))
.body("employees.employee.last-name", equalTo("Daisy"))
.body("employees.employee.sex", equalTo("f"));
}
@Test
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body("employees.employee.first-name", equalTo("Jane"),
"employees.employee.last-name", equalTo("Daisy"),
"employees.employee.sex", equalTo("f"));
}
@Test
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body(hasXPath("/employees/employee/first-name",
containsString("Ja")));
}
@Test
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
post("/employees")
.then()
.assertThat()
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
}
private static String getXml() {
return Util
.inputStreamToString(new RestAssuredXMLTest().getClass().getResourceAsStream("/employees.xml"));
}
@After
public void after() throws Exception {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.restassured;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Util {
public static String inputStreamToString(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}

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

@ -4,19 +4,4 @@
<last-name>Daisy</last-name> <last-name>Daisy</last-name>
<sex>f</sex> <sex>f</sex>
</employee> </employee>
<employee category="unskilled">
<first-name>John</first-name>
<last-name>Doe</last-name>
<sex>m</sex>
</employee>
<employee category="skilled">
<first-name>Billy</first-name>
<last-name>Getty</last-name>
<sex>m</sex>
</employee>
<employee category="skilled">
<first-name>Hill</first-name>
<last-name>Clinton</last-name>
<sex>f</sex>
</employee>
</employees> </employees>

View File

@ -1,5 +1,11 @@
{ {
"id": "390", "id": "390",
"odd": {
"price": "1.20",
"status": 2,
"ck": 12.2,
"name": "2"
},
"data": { "data": {
"countryId": 35, "countryId": 35,
"countryName": "Norway", "countryName": "Norway",
@ -9,25 +15,25 @@
"time": "2016-06-12T12:00:00Z" "time": "2016-06-12T12:00:00Z"
}, },
"odds": [{ "odds": [{
"price": 1.30, "price": "1.30",
"status": 0, "status": 0,
"ck": 12.2, "ck": 12.2,
"name": "1" "name": "1"
}, },
{ {
"price": 5.25, "price":"5.25",
"status": 1, "status": 1,
"ck": 13.1, "ck": 13.1,
"name": "X" "name": "X"
}, },
{ {
"price": 2.70, "price": "2.70",
"status": 0, "status": 0,
"ck": 12.2, "ck": 12.2,
"name": "0" "name": "0"
}, },
{ {
"price": 1.20, "price": "1.20",
"status": 2, "status": 2,
"ck": 13.1, "ck": 13.1,
"name": "2" "name": "2"

View File

@ -0,0 +1,16 @@
## Logger configure
datestamp=yyyy-MM-dd HH:mm:ss
log4j.rootLogger=TRACE, file, console
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=1GB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.File=log/rest-assured.log
log4j.appender.file.threshold=TRACE
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{${datestamp}} %5p: [%c] - %m%n
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=INFO
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{${datestamp}} %5p\: [%c] - %m%n

View File

@ -44,8 +44,9 @@ public class SecurityWithoutCsrfConfig extends WebSecurityConfigurerAdapter {
http http
.csrf().disable() .csrf().disable()
.authorizeRequests() .authorizeRequests()
.antMatchers("/admin/*").hasAnyRole("ROLE_ADMIN") .antMatchers("/auth/admin/*").hasRole("ADMIN")
.anyRequest().authenticated() .antMatchers("/auth/*").hasAnyRole("ADMIN","USER")
.antMatchers("/*").permitAll()
.and() .and()
.httpBasic() .httpBasic()
.and() .and()

View File

@ -14,24 +14,25 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc @EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() { public WebConfig() {
super(); super();
} }
@Bean @Bean
public ViewResolver viewResolver() { public ViewResolver viewResolver() {
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp"); viewResolver.setSuffix(".jsp");
return viewResolver; return viewResolver;
} }
// API // API
@Override @Override
public void addViewControllers(final ViewControllerRegistry registry) { public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry); super.addViewControllers(registry);
registry.addViewController("/graph.html"); registry.addViewController("/graph.html");
registry.addViewController("/csrfHome.html"); registry.addViewController("/csrfHome.html");
} registry.addViewController("/homepage.html");
}
} }

View File

@ -12,21 +12,22 @@ import org.springframework.web.bind.annotation.ResponseStatus;
// to test csrf // to test csrf
@Controller @Controller
@RequestMapping(value = "/auth/")
public class BankController { public class BankController {
private final Logger logger = LoggerFactory.getLogger(getClass()); private final Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping(value = "/transfer", method = RequestMethod.GET) @RequestMapping(value = "/transfer", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { public int transfer(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
logger.info("Transfer to {}", accountNo); logger.info("Transfer to {}", accountNo);
return amount; return amount;
} }
// write - just for test // write - just for test
@RequestMapping(value = "/transfer", method = RequestMethod.POST) @RequestMapping(value = "/transfer", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK) @ResponseStatus(HttpStatus.OK)
public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) { public void create(@RequestParam("accountNo") final int accountNo, @RequestParam("amount") final int amount) {
logger.info("Transfer to {}", accountNo); logger.info("Transfer to {}", accountNo);
} }
} }

View File

@ -29,93 +29,93 @@ import org.springframework.web.util.UriComponentsBuilder;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
@Controller @Controller
@RequestMapping(value = "/foos") @RequestMapping(value = "/auth/foos")
public class FooController { public class FooController {
@Autowired @Autowired
private ApplicationEventPublisher eventPublisher; private ApplicationEventPublisher eventPublisher;
@Autowired @Autowired
private IFooService service; private IFooService service;
public FooController() { public FooController() {
super(); super();
} }
// API // API
@RequestMapping(method = RequestMethod.GET, value = "/count") @RequestMapping(method = RequestMethod.GET, value = "/count")
@ResponseBody @ResponseBody
@ResponseStatus(value = HttpStatus.OK) @ResponseStatus(value = HttpStatus.OK)
public long count() { public long count() {
return 2l; return 2l;
} }
// read - one // read - one
@RequestMapping(value = "/{id}", method = RequestMethod.GET) @RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); final Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return resourceById; return resourceById;
} }
// read - all // read - all
@RequestMapping(method = RequestMethod.GET) @RequestMapping(method = RequestMethod.GET)
@ResponseBody @ResponseBody
public List<Foo> findAll() { public List<Foo> findAll() {
return service.findAll(); return service.findAll();
} }
@RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET)
@ResponseBody @ResponseBody
public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { public List<Foo> findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) {
final Page<Foo> resultPage = service.findPaginated(page, size); final Page<Foo> resultPage = service.findPaginated(page, size);
if (page > resultPage.getTotalPages()) { if (page > resultPage.getTotalPages()) {
throw new MyResourceNotFoundException(); throw new MyResourceNotFoundException();
} }
eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size)); eventPublisher.publishEvent(new PaginatedResultsRetrievedEvent<Foo>(Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));
return resultPage.getContent(); return resultPage.getContent();
} }
// write // write
@RequestMapping(method = RequestMethod.POST) @RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED) @ResponseStatus(HttpStatus.CREATED)
@ResponseBody @ResponseBody
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
Preconditions.checkNotNull(resource); Preconditions.checkNotNull(resource);
final Foo foo = service.create(resource); final Foo foo = service.create(resource);
final Long idOfCreatedResource = foo.getId(); final Long idOfCreatedResource = foo.getId();
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource)); eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
return foo; return foo;
} }
@RequestMapping(value = "/{id}", method = RequestMethod.PUT) @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK) @ResponseStatus(HttpStatus.OK)
public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) {
Preconditions.checkNotNull(resource); Preconditions.checkNotNull(resource);
RestPreconditions.checkFound(service.findOne(resource.getId())); RestPreconditions.checkFound(service.findOne(resource.getId()));
service.update(resource); service.update(resource);
} }
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK) @ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable("id") final Long id) { public void delete(@PathVariable("id") final Long id) {
service.deleteById(id); service.deleteById(id);
} }
@RequestMapping(method = RequestMethod.HEAD) @RequestMapping(method = RequestMethod.HEAD)
@ResponseStatus(HttpStatus.OK) @ResponseStatus(HttpStatus.OK)
public void head(final HttpServletResponse resp) { public void head(final HttpServletResponse resp) {
resp.setContentType(MediaType.APPLICATION_JSON_VALUE); resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
resp.setHeader("bar", "baz"); resp.setHeader("bar", "baz");
} }
} }

View File

@ -0,0 +1,14 @@
package org.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/")
public class HomeController {
public String index() {
return "homepage";
}
}

View File

@ -20,65 +20,66 @@ import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriTemplate; import org.springframework.web.util.UriTemplate;
@Controller @Controller
@RequestMapping(value = "/auth/")
public class RootController { public class RootController {
@Autowired @Autowired
private IMetricService metricService; private IMetricService metricService;
@Autowired @Autowired
private IActuatorMetricService actMetricService; private IActuatorMetricService actMetricService;
public RootController() { public RootController() {
super(); super();
} }
// API // API
// discover // discover
@RequestMapping(value = "admin", method = RequestMethod.GET) @RequestMapping(value = "admin", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.NO_CONTENT) @ResponseStatus(value = HttpStatus.NO_CONTENT)
public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) { public void adminRoot(final HttpServletRequest request, final HttpServletResponse response) {
final String rootUri = request.getRequestURL().toString(); final String rootUri = request.getRequestURL().toString();
final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo"); final URI fooUri = new UriTemplate("{rootUri}/{resource}").expand(rootUri, "foo");
final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection"); final String linkToFoo = LinkUtil.createLinkHeader(fooUri.toASCIIString(), "collection");
response.addHeader("Link", linkToFoo); response.addHeader("Link", linkToFoo);
} }
@RequestMapping(value = "/metric", method = RequestMethod.GET) @RequestMapping(value = "/metric", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Map getMetric() { public Map getMetric() {
return metricService.getFullMetric(); return metricService.getFullMetric();
} }
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/status-metric", method = RequestMethod.GET) @RequestMapping(value = "/status-metric", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Map getStatusMetric() { public Map getStatusMetric() {
return metricService.getStatusMetric(); return metricService.getStatusMetric();
} }
@RequestMapping(value = "/metric-graph", method = RequestMethod.GET) @RequestMapping(value = "/metric-graph", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Object[][] drawMetric() { public Object[][] drawMetric() {
final Object[][] result = metricService.getGraphData(); final Object[][] result = metricService.getGraphData();
for (int i = 1; i < result[0].length; i++) { for (int i = 1; i < result[0].length; i++) {
result[0][i] = result[0][i].toString(); result[0][i] = result[0][i].toString();
} }
return result; return result;
} }
@RequestMapping(value = "/admin/x", method = RequestMethod.GET) @RequestMapping(value = "/admin/x", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public String sampleAdminPage() { public String sampleAdminPage() {
return "Hello"; return "Hello";
} }
@RequestMapping(value = "/my-error-page", method = RequestMethod.GET) @RequestMapping(value = "/my-error-page", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public String sampleErrorPage() { public String sampleErrorPage() {
return "Error Occurred"; return "Error Occurred";
} }
} }

View File

@ -37,96 +37,97 @@ import cz.jirutka.rsql.parser.ast.Node;
//@EnableSpringDataWebSupport //@EnableSpringDataWebSupport
@Controller @Controller
@RequestMapping(value = "/auth/")
public class UserController { public class UserController {
@Autowired @Autowired
private IUserDAO service; private IUserDAO service;
@Autowired @Autowired
private UserRepository dao; private UserRepository dao;
@Autowired @Autowired
private MyUserRepository myUserRepository; private MyUserRepository myUserRepository;
public UserController() { public UserController() {
super(); super();
} }
// API - READ // API - READ
@RequestMapping(method = RequestMethod.GET, value = "/users") @RequestMapping(method = RequestMethod.GET, value = "/users")
@ResponseBody @ResponseBody
public List<User> findAll(@RequestParam(value = "search", required = false) final String search) { public List<User> findAll(@RequestParam(value = "search", required = false) final String search) {
final List<SearchCriteria> params = new ArrayList<SearchCriteria>(); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
if (search != null) { if (search != null) {
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
final Matcher matcher = pattern.matcher(search + ","); final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) { while (matcher.find()) {
params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3))); params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
} }
} }
return service.searchUser(params); return service.searchUser(params);
} }
@RequestMapping(method = RequestMethod.GET, value = "/users/spec") @RequestMapping(method = RequestMethod.GET, value = "/users/spec")
@ResponseBody @ResponseBody
public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) { public List<User> findAllBySpecification(@RequestParam(value = "search") final String search) {
final UserSpecificationsBuilder builder = new UserSpecificationsBuilder(); final UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET); final String operationSetExper = Joiner.on("|").join(SearchOperation.SIMPLE_OPERATION_SET);
final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),"); final Pattern pattern = Pattern.compile("(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
final Matcher matcher = pattern.matcher(search + ","); final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) { while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5)); builder.with(matcher.group(1), matcher.group(2), matcher.group(4), matcher.group(3), matcher.group(5));
} }
final Specification<User> spec = builder.build(); final Specification<User> spec = builder.build();
return dao.findAll(spec); return dao.findAll(spec);
} }
@RequestMapping(method = RequestMethod.GET, value = "/myusers") @RequestMapping(method = RequestMethod.GET, value = "/myusers")
@ResponseBody @ResponseBody
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) { public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") final String search) {
final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder(); final MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
if (search != null) { if (search != null) {
final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),"); final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
final Matcher matcher = pattern.matcher(search + ","); final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) { while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(3)); builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
} }
} }
final BooleanExpression exp = builder.build(); final BooleanExpression exp = builder.build();
return myUserRepository.findAll(exp); return myUserRepository.findAll(exp);
} }
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql") @RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
@ResponseBody @ResponseBody
public List<User> findAllByRsql(@RequestParam(value = "search") final String search) { public List<User> findAllByRsql(@RequestParam(value = "search") final String search) {
final Node rootNode = new RSQLParser().parse(search); final Node rootNode = new RSQLParser().parse(search);
final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>()); final Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
return dao.findAll(spec); return dao.findAll(spec);
} }
@RequestMapping(method = RequestMethod.GET, value = "/api/myusers") @RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
@ResponseBody @ResponseBody
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) { public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) final Predicate predicate) {
return myUserRepository.findAll(predicate); return myUserRepository.findAll(predicate);
} }
// API - WRITE // API - WRITE
@RequestMapping(method = RequestMethod.POST, value = "/users") @RequestMapping(method = RequestMethod.POST, value = "/users")
@ResponseStatus(HttpStatus.CREATED) @ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody final User resource) { public void create(@RequestBody final User resource) {
Preconditions.checkNotNull(resource); Preconditions.checkNotNull(resource);
dao.save(resource); dao.save(resource);
} }
@RequestMapping(method = RequestMethod.POST, value = "/myusers") @RequestMapping(method = RequestMethod.POST, value = "/myusers")
@ResponseStatus(HttpStatus.CREATED) @ResponseStatus(HttpStatus.CREATED)
public void addMyUser(@RequestBody final MyUser resource) { public void addMyUser(@RequestBody final MyUser resource) {
Preconditions.checkNotNull(resource); Preconditions.checkNotNull(resource);
myUserRepository.save(resource); myUserRepository.save(resource);
} }
} }

View File

@ -23,26 +23,30 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@WebAppConfiguration @WebAppConfiguration
public class CsrfAbstractIntegrationTest { public class CsrfAbstractIntegrationTest {
@Autowired @Autowired
private WebApplicationContext context; private WebApplicationContext context;
@Autowired @Autowired
private Filter springSecurityFilterChain; private Filter springSecurityFilterChain;
protected MockMvc mvc; protected MockMvc mvc;
// //
@Before @Before
public void setup() { public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
} }
protected RequestPostProcessor testUser() { protected RequestPostProcessor testUser() {
return user("user").password("userPass").roles("USER"); return user("user").password("userPass").roles("USER");
} }
protected String createFoo() throws JsonProcessingException { protected RequestPostProcessor testAdmin() {
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); return user("admin").password("adminPass").roles("USER", "ADMIN");
} }
protected String createFoo() throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6)));
}
} }

View File

@ -1,5 +1,6 @@
package org.baeldung.security.csrf; package org.baeldung.security.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -13,14 +14,33 @@ import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class }) @ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest { public class CsrfDisabledIntegrationTest extends CsrfAbstractIntegrationTest {
@Test @Test
public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception { public void givenNotAuth_whenAddFoo_thenUnauthorized() throws Exception {
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized()); mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo())).andExpect(status().isUnauthorized());
} }
@Test @Test
public void givenAuth_whenAddFoo_thenCreated() throws Exception { public void givenAuth_whenAddFoo_thenCreated() throws Exception {
mvc.perform(post("/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated()); mvc.perform(post("/auth/foos").contentType(MediaType.APPLICATION_JSON).content(createFoo()).with(testUser())).andExpect(status().isCreated());
} }
@Test
public void accessMainPageWithoutAuthorization() throws Exception {
mvc.perform(get("/graph.html").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
@Test
public void accessOtherPages() throws Exception {
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100"))
.andExpect(status().isUnauthorized()); // without authorization
mvc.perform(get("/auth/transfer").contentType(MediaType.APPLICATION_JSON).param("accountNo", "1").param("amount", "100").with(testUser()))
.andExpect(status().isOk()); // with authorization
}
@Test
public void accessAdminPage() throws Exception {
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isUnauthorized()); //without authorization
mvc.perform(get("/auth/admin/x").contentType(MediaType.APPLICATION_JSON).with(testAdmin())).andExpect(status().isOk()); //with authorization
}
} }